Add xref-pulse-on-jump
[emacs.git] / lib-src / etags.c
blobb1361dbe7ad6f197847b59fd1ed23d3fd366901c
1 /* Tags file maker to go with GNU Emacs -*- coding: utf-8 -*-
3 Copyright (C) 1984 The Regents of the University of California
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
7 met:
8 1. Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright
11 notice, this list of conditions and the following disclaimer in the
12 documentation and/or other materials provided with the
13 distribution.
14 3. Neither the name of the University nor the names of its
15 contributors may be used to endorse or promote products derived
16 from this software without specific prior written permission.
18 THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
19 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
22 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
27 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
28 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 Copyright (C) 1984, 1987-1989, 1993-1995, 1998-2015 Free Software
32 Foundation, Inc.
34 This file is not considered part of GNU Emacs.
36 This program is free software: you can redistribute it and/or modify
37 it under the terms of the GNU General Public License as published by
38 the Free Software Foundation, either version 3 of the License, or
39 (at your option) any later version.
41 This program is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 GNU General Public License for more details.
46 You should have received a copy of the GNU General Public License
47 along with this program. If not, see <http://www.gnu.org/licenses/>. */
50 /* NB To comply with the above BSD license, copyright information is
51 reproduced in etc/ETAGS.README. That file should be updated when the
52 above notices are.
54 To the best of our knowledge, this code was originally based on the
55 ctags.c distributed with BSD4.2, which was copyrighted by the
56 University of California, as described above. */
60 * Authors:
61 * 1983 Ctags originally by Ken Arnold.
62 * 1984 Fortran added by Jim Kleckner.
63 * 1984 Ed Pelegri-Llopart added C typedefs.
64 * 1985 Emacs TAGS format by Richard Stallman.
65 * 1989 Sam Kendall added C++.
66 * 1992 Joseph B. Wells improved C and C++ parsing.
67 * 1993 Francesco Potortì reorganized C and C++.
68 * 1994 Line-by-line regexp tags by Tom Tromey.
69 * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba).
70 * 2002 #line directives by Francesco Potortì.
72 * Francesco Potortì <pot@gnu.org> has maintained and improved it since 1993.
76 * If you want to add support for a new language, start by looking at the LUA
77 * language, which is the simplest. Alternatively, consider distributing etags
78 * together with a configuration file containing regexp definitions for etags.
81 char pot_etags_version[] = "@(#) pot revision number is 17.38.1.4";
83 #ifdef DEBUG
84 # undef DEBUG
85 # define DEBUG true
86 #else
87 # define DEBUG false
88 # define NDEBUG /* disable assert */
89 #endif
91 #include <config.h>
93 #ifndef _GNU_SOURCE
94 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
95 #endif
97 /* WIN32_NATIVE is for XEmacs.
98 MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
99 #ifdef WIN32_NATIVE
100 # undef MSDOS
101 # undef WINDOWSNT
102 # define WINDOWSNT
103 #endif /* WIN32_NATIVE */
105 #ifdef MSDOS
106 # undef MSDOS
107 # define MSDOS true
108 # include <sys/param.h>
109 #else
110 # define MSDOS false
111 #endif /* MSDOS */
113 #ifdef WINDOWSNT
114 # include <direct.h>
115 # define MAXPATHLEN _MAX_PATH
116 # undef HAVE_NTGUI
117 # undef DOS_NT
118 # define DOS_NT
119 #endif /* WINDOWSNT */
121 #include <unistd.h>
122 #include <stdarg.h>
123 #include <stdlib.h>
124 #include <string.h>
125 #include <sysstdio.h>
126 #include <ctype.h>
127 #include <errno.h>
128 #include <sys/types.h>
129 #include <sys/stat.h>
130 #include <binary-io.h>
131 #include <c-strcase.h>
133 #include <assert.h>
134 #ifdef NDEBUG
135 # undef assert /* some systems have a buggy assert.h */
136 # define assert(x) ((void) 0)
137 #endif
139 #include <getopt.h>
140 #include <regex.h>
142 /* Define CTAGS to make the program "ctags" compatible with the usual one.
143 Leave it undefined to make the program "etags", which makes emacs-style
144 tag tables and tags typedefs, #defines and struct/union/enum by default. */
145 #ifdef CTAGS
146 # undef CTAGS
147 # define CTAGS true
148 #else
149 # define CTAGS false
150 #endif
152 #define streq(s,t) (assert ((s)!=NULL || (t)!=NULL), !strcmp (s, t))
153 #define strcaseeq(s,t) (assert ((s)!=NULL && (t)!=NULL), !c_strcasecmp (s, t))
154 #define strneq(s,t,n) (assert ((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
155 #define strncaseeq(s,t,n) (assert ((s)!=NULL && (t)!=NULL), !c_strncasecmp (s, t, n))
157 #define CHARS 256 /* 2^sizeof(char) */
158 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
159 #define iswhite(c) (_wht[CHAR (c)]) /* c is white (see white) */
160 #define notinname(c) (_nin[CHAR (c)]) /* c is not in a name (see nonam) */
161 #define begtoken(c) (_btk[CHAR (c)]) /* c can start token (see begtk) */
162 #define intoken(c) (_itk[CHAR (c)]) /* c can be in token (see midtk) */
163 #define endtoken(c) (_etk[CHAR (c)]) /* c ends tokens (see endtk) */
165 #define ISALNUM(c) isalnum (CHAR (c))
166 #define ISALPHA(c) isalpha (CHAR (c))
167 #define ISDIGIT(c) isdigit (CHAR (c))
168 #define ISLOWER(c) islower (CHAR (c))
170 #define lowcase(c) tolower (CHAR (c))
174 * xnew, xrnew -- allocate, reallocate storage
176 * SYNOPSIS: Type *xnew (int n, Type);
177 * void xrnew (OldPointer, int n, Type);
179 #define xnew(n, Type) ((Type *) xmalloc ((n) * sizeof (Type)))
180 #define xrnew(op, n, Type) ((op) = (Type *) xrealloc (op, (n) * sizeof (Type)))
182 typedef void Lang_function (FILE *);
184 typedef struct
186 const char *suffix; /* file name suffix for this compressor */
187 const char *command; /* takes one arg and decompresses to stdout */
188 } compressor;
190 typedef struct
192 const char *name; /* language name */
193 const char *help; /* detailed help for the language */
194 Lang_function *function; /* parse function */
195 const char **suffixes; /* name suffixes of this language's files */
196 const char **filenames; /* names of this language's files */
197 const char **interpreters; /* interpreters for this language */
198 bool metasource; /* source used to generate other sources */
199 } language;
201 typedef struct fdesc
203 struct fdesc *next; /* for the linked list */
204 char *infname; /* uncompressed input file name */
205 char *infabsname; /* absolute uncompressed input file name */
206 char *infabsdir; /* absolute dir of input file */
207 char *taggedfname; /* file name to write in tagfile */
208 language *lang; /* language of file */
209 char *prop; /* file properties to write in tagfile */
210 bool usecharno; /* etags tags shall contain char number */
211 bool written; /* entry written in the tags file */
212 } fdesc;
214 typedef struct node_st
215 { /* sorting structure */
216 struct node_st *left, *right; /* left and right sons */
217 fdesc *fdp; /* description of file to whom tag belongs */
218 char *name; /* tag name */
219 char *regex; /* search regexp */
220 bool valid; /* write this tag on the tag file */
221 bool is_func; /* function tag: use regexp in CTAGS mode */
222 bool been_warned; /* warning already given for duplicated tag */
223 int lno; /* line number tag is on */
224 long cno; /* character number line starts on */
225 } node;
228 * A `linebuffer' is a structure which holds a line of text.
229 * `readline_internal' reads a line from a stream into a linebuffer
230 * and works regardless of the length of the line.
231 * SIZE is the size of BUFFER, LEN is the length of the string in
232 * BUFFER after readline reads it.
234 typedef struct
236 long size;
237 int len;
238 char *buffer;
239 } linebuffer;
241 /* Used to support mixing of --lang and file names. */
242 typedef struct
244 enum {
245 at_language, /* a language specification */
246 at_regexp, /* a regular expression */
247 at_filename, /* a file name */
248 at_stdin, /* read from stdin here */
249 at_end /* stop parsing the list */
250 } arg_type; /* argument type */
251 language *lang; /* language associated with the argument */
252 char *what; /* the argument itself */
253 } argument;
255 /* Structure defining a regular expression. */
256 typedef struct regexp
258 struct regexp *p_next; /* pointer to next in list */
259 language *lang; /* if set, use only for this language */
260 char *pattern; /* the regexp pattern */
261 char *name; /* tag name */
262 struct re_pattern_buffer *pat; /* the compiled pattern */
263 struct re_registers regs; /* re registers */
264 bool error_signaled; /* already signaled for this regexp */
265 bool force_explicit_name; /* do not allow implicit tag name */
266 bool ignore_case; /* ignore case when matching */
267 bool multi_line; /* do a multi-line match on the whole file */
268 } regexp;
271 /* Many compilers barf on this:
272 Lang_function Ada_funcs;
273 so let's write it this way */
274 static void Ada_funcs (FILE *);
275 static void Asm_labels (FILE *);
276 static void C_entries (int c_ext, FILE *);
277 static void default_C_entries (FILE *);
278 static void plain_C_entries (FILE *);
279 static void Cjava_entries (FILE *);
280 static void Cobol_paragraphs (FILE *);
281 static void Cplusplus_entries (FILE *);
282 static void Cstar_entries (FILE *);
283 static void Erlang_functions (FILE *);
284 static void Forth_words (FILE *);
285 static void Fortran_functions (FILE *);
286 static void HTML_labels (FILE *);
287 static void Lisp_functions (FILE *);
288 static void Lua_functions (FILE *);
289 static void Makefile_targets (FILE *);
290 static void Pascal_functions (FILE *);
291 static void Perl_functions (FILE *);
292 static void PHP_functions (FILE *);
293 static void PS_functions (FILE *);
294 static void Prolog_functions (FILE *);
295 static void Python_functions (FILE *);
296 static void Scheme_functions (FILE *);
297 static void TeX_commands (FILE *);
298 static void Texinfo_nodes (FILE *);
299 static void Yacc_entries (FILE *);
300 static void just_read_file (FILE *);
302 static language *get_language_from_langname (const char *);
303 static void readline (linebuffer *, FILE *);
304 static long readline_internal (linebuffer *, FILE *);
305 static bool nocase_tail (const char *);
306 static void get_tag (char *, char **);
308 static void analyze_regex (char *);
309 static void free_regexps (void);
310 static void regex_tag_multiline (void);
311 static void error (const char *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2);
312 static _Noreturn void suggest_asking_for_help (void);
313 _Noreturn void fatal (const char *, const char *);
314 static _Noreturn void pfatal (const char *);
315 static void add_node (node *, node **);
317 static void init (void);
318 static void process_file_name (char *, language *);
319 static void process_file (FILE *, char *, language *);
320 static void find_entries (FILE *);
321 static void free_tree (node *);
322 static void free_fdesc (fdesc *);
323 static void pfnote (char *, bool, char *, int, int, long);
324 static void invalidate_nodes (fdesc *, node **);
325 static void put_entries (node *);
327 static char *concat (const char *, const char *, const char *);
328 static char *skip_spaces (char *);
329 static char *skip_non_spaces (char *);
330 static char *skip_name (char *);
331 static char *savenstr (const char *, int);
332 static char *savestr (const char *);
333 static char *etags_getcwd (void);
334 static char *relative_filename (char *, char *);
335 static char *absolute_filename (char *, char *);
336 static char *absolute_dirname (char *, char *);
337 static bool filename_is_absolute (char *f);
338 static void canonicalize_filename (char *);
339 static void linebuffer_init (linebuffer *);
340 static void linebuffer_setlen (linebuffer *, int);
341 static void *xmalloc (size_t);
342 static void *xrealloc (void *, size_t);
345 static char searchar = '/'; /* use /.../ searches */
347 static char *tagfile; /* output file */
348 static char *progname; /* name this program was invoked with */
349 static char *cwd; /* current working directory */
350 static char *tagfiledir; /* directory of tagfile */
351 static FILE *tagf; /* ioptr for tags file */
352 static ptrdiff_t whatlen_max; /* maximum length of any 'what' member */
354 static fdesc *fdhead; /* head of file description list */
355 static fdesc *curfdp; /* current file description */
356 static int lineno; /* line number of current line */
357 static long charno; /* current character number */
358 static long linecharno; /* charno of start of current line */
359 static char *dbp; /* pointer to start of current tag */
361 static const int invalidcharno = -1;
363 static node *nodehead; /* the head of the binary tree of tags */
364 static node *last_node; /* the last node created */
366 static linebuffer lb; /* the current line */
367 static linebuffer filebuf; /* a buffer containing the whole file */
368 static linebuffer token_name; /* a buffer containing a tag name */
370 /* boolean "functions" (see init) */
371 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
372 static const char
373 /* white chars */
374 *white = " \f\t\n\r\v",
375 /* not in a name */
376 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
377 /* token ending chars */
378 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
379 /* token starting chars */
380 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
381 /* valid in-token chars */
382 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
384 static bool append_to_tagfile; /* -a: append to tags */
385 /* The next five default to true in C and derived languages. */
386 static bool typedefs; /* -t: create tags for C and Ada typedefs */
387 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
388 /* 0 struct/enum/union decls, and C++ */
389 /* member functions. */
390 static bool constantypedefs; /* -d: create tags for C #define, enum */
391 /* constants and variables. */
392 /* -D: opposite of -d. Default under ctags. */
393 static int globals; /* create tags for global variables */
394 static int members; /* create tags for C member variables */
395 static int declarations; /* --declarations: tag them and extern in C&Co*/
396 static int no_line_directive; /* ignore #line directives (undocumented) */
397 static int no_duplicates; /* no duplicate tags for ctags (undocumented) */
398 static bool update; /* -u: update tags */
399 static bool vgrind_style; /* -v: create vgrind style index output */
400 static bool no_warnings; /* -w: suppress warnings (undocumented) */
401 static bool cxref_style; /* -x: create cxref style output */
402 static bool cplusplus; /* .[hc] means C++, not C (undocumented) */
403 static bool ignoreindent; /* -I: ignore indentation in C */
404 static int packages_only; /* --packages-only: in Ada, only tag packages*/
406 /* STDIN is defined in LynxOS system headers */
407 #ifdef STDIN
408 # undef STDIN
409 #endif
411 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
412 static bool parsing_stdin; /* --parse-stdin used */
414 static regexp *p_head; /* list of all regexps */
415 static bool need_filebuf; /* some regexes are multi-line */
417 static struct option longopts[] =
419 { "append", no_argument, NULL, 'a' },
420 { "packages-only", no_argument, &packages_only, 1 },
421 { "c++", no_argument, NULL, 'C' },
422 { "declarations", no_argument, &declarations, 1 },
423 { "no-line-directive", no_argument, &no_line_directive, 1 },
424 { "no-duplicates", no_argument, &no_duplicates, 1 },
425 { "help", no_argument, NULL, 'h' },
426 { "help", no_argument, NULL, 'H' },
427 { "ignore-indentation", no_argument, NULL, 'I' },
428 { "language", required_argument, NULL, 'l' },
429 { "members", no_argument, &members, 1 },
430 { "no-members", no_argument, &members, 0 },
431 { "output", required_argument, NULL, 'o' },
432 { "regex", required_argument, NULL, 'r' },
433 { "no-regex", no_argument, NULL, 'R' },
434 { "ignore-case-regex", required_argument, NULL, 'c' },
435 { "parse-stdin", required_argument, NULL, STDIN },
436 { "version", no_argument, NULL, 'V' },
438 #if CTAGS /* Ctags options */
439 { "backward-search", no_argument, NULL, 'B' },
440 { "cxref", no_argument, NULL, 'x' },
441 { "defines", no_argument, NULL, 'd' },
442 { "globals", no_argument, &globals, 1 },
443 { "typedefs", no_argument, NULL, 't' },
444 { "typedefs-and-c++", no_argument, NULL, 'T' },
445 { "update", no_argument, NULL, 'u' },
446 { "vgrind", no_argument, NULL, 'v' },
447 { "no-warn", no_argument, NULL, 'w' },
449 #else /* Etags options */
450 { "no-defines", no_argument, NULL, 'D' },
451 { "no-globals", no_argument, &globals, 0 },
452 { "include", required_argument, NULL, 'i' },
453 #endif
454 { NULL }
457 static compressor compressors[] =
459 { "z", "gzip -d -c"},
460 { "Z", "gzip -d -c"},
461 { "gz", "gzip -d -c"},
462 { "GZ", "gzip -d -c"},
463 { "bz2", "bzip2 -d -c" },
464 { "xz", "xz -d -c" },
465 { NULL }
469 * Language stuff.
472 /* Ada code */
473 static const char *Ada_suffixes [] =
474 { "ads", "adb", "ada", NULL };
475 static const char Ada_help [] =
476 "In Ada code, functions, procedures, packages, tasks and types are\n\
477 tags. Use the `--packages-only' option to create tags for\n\
478 packages only.\n\
479 Ada tag names have suffixes indicating the type of entity:\n\
480 Entity type: Qualifier:\n\
481 ------------ ----------\n\
482 function /f\n\
483 procedure /p\n\
484 package spec /s\n\
485 package body /b\n\
486 type /t\n\
487 task /k\n\
488 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
489 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
490 will just search for any tag `bidule'.";
492 /* Assembly code */
493 static const char *Asm_suffixes [] =
494 { "a", /* Unix assembler */
495 "asm", /* Microcontroller assembly */
496 "def", /* BSO/Tasking definition includes */
497 "inc", /* Microcontroller include files */
498 "ins", /* Microcontroller include files */
499 "s", "sa", /* Unix assembler */
500 "S", /* cpp-processed Unix assembler */
501 "src", /* BSO/Tasking C compiler output */
502 NULL
504 static const char Asm_help [] =
505 "In assembler code, labels appearing at the beginning of a line,\n\
506 followed by a colon, are tags.";
509 /* Note that .c and .h can be considered C++, if the --c++ flag was
510 given, or if the `class' or `template' keywords are met inside the file.
511 That is why default_C_entries is called for these. */
512 static const char *default_C_suffixes [] =
513 { "c", "h", NULL };
514 #if CTAGS /* C help for Ctags */
515 static const char default_C_help [] =
516 "In C code, any C function is a tag. Use -t to tag typedefs.\n\
517 Use -T to tag definitions of `struct', `union' and `enum'.\n\
518 Use -d to tag `#define' macro definitions and `enum' constants.\n\
519 Use --globals to tag global variables.\n\
520 You can tag function declarations and external variables by\n\
521 using `--declarations', and struct members by using `--members'.";
522 #else /* C help for Etags */
523 static const char default_C_help [] =
524 "In C code, any C function or typedef is a tag, and so are\n\
525 definitions of `struct', `union' and `enum'. `#define' macro\n\
526 definitions and `enum' constants are tags unless you specify\n\
527 `--no-defines'. Global variables are tags unless you specify\n\
528 `--no-globals' and so are struct members unless you specify\n\
529 `--no-members'. Use of `--no-globals', `--no-defines' and\n\
530 `--no-members' can make the tags table file much smaller.\n\
531 You can tag function declarations and external variables by\n\
532 using `--declarations'.";
533 #endif /* C help for Ctags and Etags */
535 static const char *Cplusplus_suffixes [] =
536 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
537 "M", /* Objective C++ */
538 "pdb", /* PostScript with C syntax */
539 NULL };
540 static const char Cplusplus_help [] =
541 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
542 --help --lang=c --lang=c++ for full help.)\n\
543 In addition to C tags, member functions are also recognized. Member\n\
544 variables are recognized unless you use the `--no-members' option.\n\
545 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
546 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
547 `operator+'.";
549 static const char *Cjava_suffixes [] =
550 { "java", NULL };
551 static char Cjava_help [] =
552 "In Java code, all the tags constructs of C and C++ code are\n\
553 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
556 static const char *Cobol_suffixes [] =
557 { "COB", "cob", NULL };
558 static char Cobol_help [] =
559 "In Cobol code, tags are paragraph names; that is, any word\n\
560 starting in column 8 and followed by a period.";
562 static const char *Cstar_suffixes [] =
563 { "cs", "hs", NULL };
565 static const char *Erlang_suffixes [] =
566 { "erl", "hrl", NULL };
567 static const char Erlang_help [] =
568 "In Erlang code, the tags are the functions, records and macros\n\
569 defined in the file.";
571 const char *Forth_suffixes [] =
572 { "fth", "tok", NULL };
573 static const char Forth_help [] =
574 "In Forth code, tags are words defined by `:',\n\
575 constant, code, create, defer, value, variable, buffer:, field.";
577 static const char *Fortran_suffixes [] =
578 { "F", "f", "f90", "for", NULL };
579 static const char Fortran_help [] =
580 "In Fortran code, functions, subroutines and block data are tags.";
582 static const char *HTML_suffixes [] =
583 { "htm", "html", "shtml", NULL };
584 static const char HTML_help [] =
585 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
586 `h3' headers. Also, tags are `name=' in anchors and all\n\
587 occurrences of `id='.";
589 static const char *Lisp_suffixes [] =
590 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
591 static const char Lisp_help [] =
592 "In Lisp code, any function defined with `defun', any variable\n\
593 defined with `defvar' or `defconst', and in general the first\n\
594 argument of any expression that starts with `(def' in column zero\n\
595 is a tag.\n\
596 The `--declarations' option tags \"(defvar foo)\" constructs too.";
598 static const char *Lua_suffixes [] =
599 { "lua", "LUA", NULL };
600 static const char Lua_help [] =
601 "In Lua scripts, all functions are tags.";
603 static const char *Makefile_filenames [] =
604 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
605 static const char Makefile_help [] =
606 "In makefiles, targets are tags; additionally, variables are tags\n\
607 unless you specify `--no-globals'.";
609 static const char *Objc_suffixes [] =
610 { "lm", /* Objective lex file */
611 "m", /* Objective C file */
612 NULL };
613 static const char Objc_help [] =
614 "In Objective C code, tags include Objective C definitions for classes,\n\
615 class categories, methods and protocols. Tags for variables and\n\
616 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
617 (Use --help --lang=c --lang=objc --lang=java for full help.)";
619 static const char *Pascal_suffixes [] =
620 { "p", "pas", NULL };
621 static const char Pascal_help [] =
622 "In Pascal code, the tags are the functions and procedures defined\n\
623 in the file.";
624 /* " // this is for working around an Emacs highlighting bug... */
626 static const char *Perl_suffixes [] =
627 { "pl", "pm", NULL };
628 static const char *Perl_interpreters [] =
629 { "perl", "@PERL@", NULL };
630 static const char Perl_help [] =
631 "In Perl code, the tags are the packages, subroutines and variables\n\
632 defined by the `package', `sub', `my' and `local' keywords. Use\n\
633 `--globals' if you want to tag global variables. Tags for\n\
634 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
635 defined in the default package is `main::SUB'.";
637 static const char *PHP_suffixes [] =
638 { "php", "php3", "php4", NULL };
639 static const char PHP_help [] =
640 "In PHP code, tags are functions, classes and defines. Unless you use\n\
641 the `--no-members' option, vars are tags too.";
643 static const char *plain_C_suffixes [] =
644 { "pc", /* Pro*C file */
645 NULL };
647 static const char *PS_suffixes [] =
648 { "ps", "psw", NULL }; /* .psw is for PSWrap */
649 static const char PS_help [] =
650 "In PostScript code, the tags are the functions.";
652 static const char *Prolog_suffixes [] =
653 { "prolog", NULL };
654 static const char Prolog_help [] =
655 "In Prolog code, tags are predicates and rules at the beginning of\n\
656 line.";
658 static const char *Python_suffixes [] =
659 { "py", NULL };
660 static const char Python_help [] =
661 "In Python code, `def' or `class' at the beginning of a line\n\
662 generate a tag.";
664 /* Can't do the `SCM' or `scm' prefix with a version number. */
665 static const char *Scheme_suffixes [] =
666 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
667 static const char Scheme_help [] =
668 "In Scheme code, tags include anything defined with `def' or with a\n\
669 construct whose name starts with `def'. They also include\n\
670 variables set with `set!' at top level in the file.";
672 static const char *TeX_suffixes [] =
673 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
674 static const char TeX_help [] =
675 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
676 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
677 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
678 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
679 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
681 Other commands can be specified by setting the environment variable\n\
682 `TEXTAGS' to a colon-separated list like, for example,\n\
683 TEXTAGS=\"mycommand:myothercommand\".";
686 static const char *Texinfo_suffixes [] =
687 { "texi", "texinfo", "txi", NULL };
688 static const char Texinfo_help [] =
689 "for texinfo files, lines starting with @node are tagged.";
691 static const char *Yacc_suffixes [] =
692 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
693 static const char Yacc_help [] =
694 "In Bison or Yacc input files, each rule defines as a tag the\n\
695 nonterminal it constructs. The portions of the file that contain\n\
696 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
697 for full help).";
699 static const char auto_help [] =
700 "`auto' is not a real language, it indicates to use\n\
701 a default language for files base on file name suffix and file contents.";
703 static const char none_help [] =
704 "`none' is not a real language, it indicates to only do\n\
705 regexp processing on files.";
707 static const char no_lang_help [] =
708 "No detailed help available for this language.";
712 * Table of languages.
714 * It is ok for a given function to be listed under more than one
715 * name. I just didn't.
718 static language lang_names [] =
720 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
721 { "asm", Asm_help, Asm_labels, Asm_suffixes },
722 { "c", default_C_help, default_C_entries, default_C_suffixes },
723 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
724 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
725 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
726 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
727 { "forth", Forth_help, Forth_words, Forth_suffixes },
728 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
729 { "html", HTML_help, HTML_labels, HTML_suffixes },
730 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
731 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
732 { "lua", Lua_help, Lua_functions, Lua_suffixes },
733 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
734 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
735 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
736 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
737 { "php", PHP_help, PHP_functions, PHP_suffixes },
738 { "postscript",PS_help, PS_functions, PS_suffixes },
739 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
740 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
741 { "python", Python_help, Python_functions, Python_suffixes },
742 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
743 { "tex", TeX_help, TeX_commands, TeX_suffixes },
744 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
745 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,true},
746 { "auto", auto_help }, /* default guessing scheme */
747 { "none", none_help, just_read_file }, /* regexp matching only */
748 { NULL } /* end of list */
752 static void
753 print_language_names (void)
755 language *lang;
756 const char **name, **ext;
758 puts ("\nThese are the currently supported languages, along with the\n\
759 default file names and dot suffixes:");
760 for (lang = lang_names; lang->name != NULL; lang++)
762 printf (" %-*s", 10, lang->name);
763 if (lang->filenames != NULL)
764 for (name = lang->filenames; *name != NULL; name++)
765 printf (" %s", *name);
766 if (lang->suffixes != NULL)
767 for (ext = lang->suffixes; *ext != NULL; ext++)
768 printf (" .%s", *ext);
769 puts ("");
771 puts ("where `auto' means use default language for files based on file\n\
772 name suffix, and `none' means only do regexp processing on files.\n\
773 If no language is specified and no matching suffix is found,\n\
774 the first line of the file is read for a sharp-bang (#!) sequence\n\
775 followed by the name of an interpreter. If no such sequence is found,\n\
776 Fortran is tried first; if no tags are found, C is tried next.\n\
777 When parsing any C file, a \"class\" or \"template\" keyword\n\
778 switches to C++.");
779 puts ("Compressed files are supported using gzip, bzip2, and xz.\n\
781 For detailed help on a given language use, for example,\n\
782 etags --help --lang=ada.");
785 #ifndef EMACS_NAME
786 # define EMACS_NAME "standalone"
787 #endif
788 #ifndef VERSION
789 # define VERSION "17.38.1.4"
790 #endif
791 static _Noreturn void
792 print_version (void)
794 char emacs_copyright[] = COPYRIGHT;
796 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
797 puts (emacs_copyright);
798 puts ("This program is distributed under the terms in ETAGS.README");
800 exit (EXIT_SUCCESS);
803 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
804 # define PRINT_UNDOCUMENTED_OPTIONS_HELP false
805 #endif
807 static _Noreturn void
808 print_help (argument *argbuffer)
810 bool help_for_lang = false;
812 for (; argbuffer->arg_type != at_end; argbuffer++)
813 if (argbuffer->arg_type == at_language)
815 if (help_for_lang)
816 puts ("");
817 puts (argbuffer->lang->help);
818 help_for_lang = true;
821 if (help_for_lang)
822 exit (EXIT_SUCCESS);
824 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
826 These are the options accepted by %s.\n", progname, progname);
827 puts ("You may use unambiguous abbreviations for the long option names.");
828 puts (" A - as file name means read names from stdin (one per line).\n\
829 Absolute names are stored in the output file as they are.\n\
830 Relative ones are stored relative to the output file's directory.\n");
832 puts ("-a, --append\n\
833 Append tag entries to existing tags file.");
835 puts ("--packages-only\n\
836 For Ada files, only generate tags for packages.");
838 if (CTAGS)
839 puts ("-B, --backward-search\n\
840 Write the search commands for the tag entries using '?', the\n\
841 backward-search command instead of '/', the forward-search command.");
843 /* This option is mostly obsolete, because etags can now automatically
844 detect C++. Retained for backward compatibility and for debugging and
845 experimentation. In principle, we could want to tag as C++ even
846 before any "class" or "template" keyword.
847 puts ("-C, --c++\n\
848 Treat files whose name suffix defaults to C language as C++ files.");
851 puts ("--declarations\n\
852 In C and derived languages, create tags for function declarations,");
853 if (CTAGS)
854 puts ("\tand create tags for extern variables if --globals is used.");
855 else
856 puts
857 ("\tand create tags for extern variables unless --no-globals is used.");
859 if (CTAGS)
860 puts ("-d, --defines\n\
861 Create tag entries for C #define constants and enum constants, too.");
862 else
863 puts ("-D, --no-defines\n\
864 Don't create tag entries for C #define constants and enum constants.\n\
865 This makes the tags file smaller.");
867 if (!CTAGS)
868 puts ("-i FILE, --include=FILE\n\
869 Include a note in tag file indicating that, when searching for\n\
870 a tag, one should also consult the tags file FILE after\n\
871 checking the current file.");
873 puts ("-l LANG, --language=LANG\n\
874 Force the following files to be considered as written in the\n\
875 named language up to the next --language=LANG option.");
877 if (CTAGS)
878 puts ("--globals\n\
879 Create tag entries for global variables in some languages.");
880 else
881 puts ("--no-globals\n\
882 Do not create tag entries for global variables in some\n\
883 languages. This makes the tags file smaller.");
885 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
886 puts ("--no-line-directive\n\
887 Ignore #line preprocessor directives in C and derived languages.");
889 if (CTAGS)
890 puts ("--members\n\
891 Create tag entries for members of structures in some languages.");
892 else
893 puts ("--no-members\n\
894 Do not create tag entries for members of structures\n\
895 in some languages.");
897 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
898 Make a tag for each line matching a regular expression pattern\n\
899 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
900 files only. REGEXFILE is a file containing one REGEXP per line.\n\
901 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
902 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
903 puts (" If TAGNAME/ is present, the tags created are named.\n\
904 For example Tcl named tags can be created with:\n\
905 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
906 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
907 `m' means to allow multi-line matches, `s' implies `m' and\n\
908 causes dot to match any character, including newline.");
910 puts ("-R, --no-regex\n\
911 Don't create tags from regexps for the following files.");
913 puts ("-I, --ignore-indentation\n\
914 In C and C++ do not assume that a closing brace in the first\n\
915 column is the final brace of a function or structure definition.");
917 puts ("-o FILE, --output=FILE\n\
918 Write the tags to FILE.");
920 puts ("--parse-stdin=NAME\n\
921 Read from standard input and record tags as belonging to file NAME.");
923 if (CTAGS)
925 puts ("-t, --typedefs\n\
926 Generate tag entries for C and Ada typedefs.");
927 puts ("-T, --typedefs-and-c++\n\
928 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
929 and C++ member functions.");
932 if (CTAGS)
933 puts ("-u, --update\n\
934 Update the tag entries for the given files, leaving tag\n\
935 entries for other files in place. Currently, this is\n\
936 implemented by deleting the existing entries for the given\n\
937 files and then rewriting the new entries at the end of the\n\
938 tags file. It is often faster to simply rebuild the entire\n\
939 tag file than to use this.");
941 if (CTAGS)
943 puts ("-v, --vgrind\n\
944 Print on the standard output an index of items intended for\n\
945 human consumption, similar to the output of vgrind. The index\n\
946 is sorted, and gives the page number of each item.");
948 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
949 puts ("-w, --no-duplicates\n\
950 Do not create duplicate tag entries, for compatibility with\n\
951 traditional ctags.");
953 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
954 puts ("-w, --no-warn\n\
955 Suppress warning messages about duplicate tag entries.");
957 puts ("-x, --cxref\n\
958 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
959 The output uses line numbers instead of page numbers, but\n\
960 beyond that the differences are cosmetic; try both to see\n\
961 which you like.");
964 puts ("-V, --version\n\
965 Print the version of the program.\n\
966 -h, --help\n\
967 Print this help message.\n\
968 Followed by one or more `--language' options prints detailed\n\
969 help about tag generation for the specified languages.");
971 print_language_names ();
973 puts ("");
974 puts ("Report bugs to bug-gnu-emacs@gnu.org");
976 exit (EXIT_SUCCESS);
981 main (int argc, char **argv)
983 int i;
984 unsigned int nincluded_files;
985 char **included_files;
986 argument *argbuffer;
987 int current_arg, file_count;
988 linebuffer filename_lb;
989 bool help_asked = false;
990 ptrdiff_t len;
991 char *optstring;
992 int opt;
994 progname = argv[0];
995 nincluded_files = 0;
996 included_files = xnew (argc, char *);
997 current_arg = 0;
998 file_count = 0;
1000 /* Allocate enough no matter what happens. Overkill, but each one
1001 is small. */
1002 argbuffer = xnew (argc, argument);
1005 * Always find typedefs and structure tags.
1006 * Also default to find macro constants, enum constants, struct
1007 * members and global variables. Do it for both etags and ctags.
1009 typedefs = typedefs_or_cplusplus = constantypedefs = true;
1010 globals = members = true;
1012 /* When the optstring begins with a '-' getopt_long does not rearrange the
1013 non-options arguments to be at the end, but leaves them alone. */
1014 optstring = concat ("-ac:Cf:Il:o:r:RSVhH",
1015 (CTAGS) ? "BxdtTuvw" : "Di:",
1016 "");
1018 while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1019 switch (opt)
1021 case 0:
1022 /* If getopt returns 0, then it has already processed a
1023 long-named option. We should do nothing. */
1024 break;
1026 case 1:
1027 /* This means that a file name has been seen. Record it. */
1028 argbuffer[current_arg].arg_type = at_filename;
1029 argbuffer[current_arg].what = optarg;
1030 len = strlen (optarg);
1031 if (whatlen_max < len)
1032 whatlen_max = len;
1033 ++current_arg;
1034 ++file_count;
1035 break;
1037 case STDIN:
1038 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1039 argbuffer[current_arg].arg_type = at_stdin;
1040 argbuffer[current_arg].what = optarg;
1041 len = strlen (optarg);
1042 if (whatlen_max < len)
1043 whatlen_max = len;
1044 ++current_arg;
1045 ++file_count;
1046 if (parsing_stdin)
1047 fatal ("cannot parse standard input more than once", (char *)NULL);
1048 parsing_stdin = true;
1049 break;
1051 /* Common options. */
1052 case 'a': append_to_tagfile = true; break;
1053 case 'C': cplusplus = true; break;
1054 case 'f': /* for compatibility with old makefiles */
1055 case 'o':
1056 if (tagfile)
1058 error ("-o option may only be given once.");
1059 suggest_asking_for_help ();
1060 /* NOTREACHED */
1062 tagfile = optarg;
1063 break;
1064 case 'I':
1065 case 'S': /* for backward compatibility */
1066 ignoreindent = true;
1067 break;
1068 case 'l':
1070 language *lang = get_language_from_langname (optarg);
1071 if (lang != NULL)
1073 argbuffer[current_arg].lang = lang;
1074 argbuffer[current_arg].arg_type = at_language;
1075 ++current_arg;
1078 break;
1079 case 'c':
1080 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1081 optarg = concat (optarg, "i", ""); /* memory leak here */
1082 /* FALLTHRU */
1083 case 'r':
1084 argbuffer[current_arg].arg_type = at_regexp;
1085 argbuffer[current_arg].what = optarg;
1086 len = strlen (optarg);
1087 if (whatlen_max < len)
1088 whatlen_max = len;
1089 ++current_arg;
1090 break;
1091 case 'R':
1092 argbuffer[current_arg].arg_type = at_regexp;
1093 argbuffer[current_arg].what = NULL;
1094 ++current_arg;
1095 break;
1096 case 'V':
1097 print_version ();
1098 break;
1099 case 'h':
1100 case 'H':
1101 help_asked = true;
1102 break;
1104 /* Etags options */
1105 case 'D': constantypedefs = false; break;
1106 case 'i': included_files[nincluded_files++] = optarg; break;
1108 /* Ctags options. */
1109 case 'B': searchar = '?'; break;
1110 case 'd': constantypedefs = true; break;
1111 case 't': typedefs = true; break;
1112 case 'T': typedefs = typedefs_or_cplusplus = true; break;
1113 case 'u': update = true; break;
1114 case 'v': vgrind_style = true; /*FALLTHRU*/
1115 case 'x': cxref_style = true; break;
1116 case 'w': no_warnings = true; break;
1117 default:
1118 suggest_asking_for_help ();
1119 /* NOTREACHED */
1122 /* No more options. Store the rest of arguments. */
1123 for (; optind < argc; optind++)
1125 argbuffer[current_arg].arg_type = at_filename;
1126 argbuffer[current_arg].what = argv[optind];
1127 len = strlen (argv[optind]);
1128 if (whatlen_max < len)
1129 whatlen_max = len;
1130 ++current_arg;
1131 ++file_count;
1134 argbuffer[current_arg].arg_type = at_end;
1136 if (help_asked)
1137 print_help (argbuffer);
1138 /* NOTREACHED */
1140 if (nincluded_files == 0 && file_count == 0)
1142 error ("no input files specified.");
1143 suggest_asking_for_help ();
1144 /* NOTREACHED */
1147 if (tagfile == NULL)
1148 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1149 cwd = etags_getcwd (); /* the current working directory */
1150 if (cwd[strlen (cwd) - 1] != '/')
1152 char *oldcwd = cwd;
1153 cwd = concat (oldcwd, "/", "");
1154 free (oldcwd);
1157 /* Compute base directory for relative file names. */
1158 if (streq (tagfile, "-")
1159 || strneq (tagfile, "/dev/", 5))
1160 tagfiledir = cwd; /* relative file names are relative to cwd */
1161 else
1163 canonicalize_filename (tagfile);
1164 tagfiledir = absolute_dirname (tagfile, cwd);
1167 init (); /* set up boolean "functions" */
1169 linebuffer_init (&lb);
1170 linebuffer_init (&filename_lb);
1171 linebuffer_init (&filebuf);
1172 linebuffer_init (&token_name);
1174 if (!CTAGS)
1176 if (streq (tagfile, "-"))
1178 tagf = stdout;
1179 SET_BINARY (fileno (stdout));
1181 else
1182 tagf = fopen (tagfile, append_to_tagfile ? "ab" : "wb");
1183 if (tagf == NULL)
1184 pfatal (tagfile);
1188 * Loop through files finding functions.
1190 for (i = 0; i < current_arg; i++)
1192 static language *lang; /* non-NULL if language is forced */
1193 char *this_file;
1195 switch (argbuffer[i].arg_type)
1197 case at_language:
1198 lang = argbuffer[i].lang;
1199 break;
1200 case at_regexp:
1201 analyze_regex (argbuffer[i].what);
1202 break;
1203 case at_filename:
1204 this_file = argbuffer[i].what;
1205 /* Input file named "-" means read file names from stdin
1206 (one per line) and use them. */
1207 if (streq (this_file, "-"))
1209 if (parsing_stdin)
1210 fatal ("cannot parse standard input AND read file names from it",
1211 (char *)NULL);
1212 while (readline_internal (&filename_lb, stdin) > 0)
1213 process_file_name (filename_lb.buffer, lang);
1215 else
1216 process_file_name (this_file, lang);
1217 break;
1218 case at_stdin:
1219 this_file = argbuffer[i].what;
1220 process_file (stdin, this_file, lang);
1221 break;
1225 free_regexps ();
1226 free (lb.buffer);
1227 free (filebuf.buffer);
1228 free (token_name.buffer);
1230 if (!CTAGS || cxref_style)
1232 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1233 put_entries (nodehead);
1234 free_tree (nodehead);
1235 nodehead = NULL;
1236 if (!CTAGS)
1238 fdesc *fdp;
1240 /* Output file entries that have no tags. */
1241 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1242 if (!fdp->written)
1243 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1245 while (nincluded_files-- > 0)
1246 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1248 if (fclose (tagf) == EOF)
1249 pfatal (tagfile);
1252 exit (EXIT_SUCCESS);
1255 /* From here on, we are in (CTAGS && !cxref_style) */
1256 if (update)
1258 char *cmd =
1259 xmalloc (strlen (tagfile) + whatlen_max +
1260 sizeof "mv..OTAGS;fgrep -v '\t\t' OTAGS >;rm OTAGS");
1261 for (i = 0; i < current_arg; ++i)
1263 switch (argbuffer[i].arg_type)
1265 case at_filename:
1266 case at_stdin:
1267 break;
1268 default:
1269 continue; /* the for loop */
1271 char *z = stpcpy (cmd, "mv ");
1272 z = stpcpy (z, tagfile);
1273 z = stpcpy (z, " OTAGS;fgrep -v '\t");
1274 z = stpcpy (z, argbuffer[i].what);
1275 z = stpcpy (z, "\t' OTAGS >");
1276 z = stpcpy (z, tagfile);
1277 strcpy (z, ";rm OTAGS");
1278 if (system (cmd) != EXIT_SUCCESS)
1279 fatal ("failed to execute shell command", (char *)NULL);
1281 free (cmd);
1282 append_to_tagfile = true;
1285 tagf = fopen (tagfile, append_to_tagfile ? "ab" : "wb");
1286 if (tagf == NULL)
1287 pfatal (tagfile);
1288 put_entries (nodehead); /* write all the tags (CTAGS) */
1289 free_tree (nodehead);
1290 nodehead = NULL;
1291 if (fclose (tagf) == EOF)
1292 pfatal (tagfile);
1294 if (CTAGS)
1295 if (append_to_tagfile || update)
1297 char *cmd = xmalloc (2 * strlen (tagfile) + sizeof "sort -u -o..");
1298 /* Maybe these should be used:
1299 setenv ("LC_COLLATE", "C", 1);
1300 setenv ("LC_ALL", "C", 1); */
1301 char *z = stpcpy (cmd, "sort -u -o ");
1302 z = stpcpy (z, tagfile);
1303 *z++ = ' ';
1304 strcpy (z, tagfile);
1305 exit (system (cmd));
1307 return EXIT_SUCCESS;
1312 * Return a compressor given the file name. If EXTPTR is non-zero,
1313 * return a pointer into FILE where the compressor-specific
1314 * extension begins. If no compressor is found, NULL is returned
1315 * and EXTPTR is not significant.
1316 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1318 static compressor *
1319 get_compressor_from_suffix (char *file, char **extptr)
1321 compressor *compr;
1322 char *slash, *suffix;
1324 /* File has been processed by canonicalize_filename,
1325 so we don't need to consider backslashes on DOS_NT. */
1326 slash = strrchr (file, '/');
1327 suffix = strrchr (file, '.');
1328 if (suffix == NULL || suffix < slash)
1329 return NULL;
1330 if (extptr != NULL)
1331 *extptr = suffix;
1332 suffix += 1;
1333 /* Let those poor souls who live with DOS 8+3 file name limits get
1334 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1335 Only the first do loop is run if not MSDOS */
1338 for (compr = compressors; compr->suffix != NULL; compr++)
1339 if (streq (compr->suffix, suffix))
1340 return compr;
1341 if (!MSDOS)
1342 break; /* do it only once: not really a loop */
1343 if (extptr != NULL)
1344 *extptr = ++suffix;
1345 } while (*suffix != '\0');
1346 return NULL;
1352 * Return a language given the name.
1354 static language *
1355 get_language_from_langname (const char *name)
1357 language *lang;
1359 if (name == NULL)
1360 error ("empty language name");
1361 else
1363 for (lang = lang_names; lang->name != NULL; lang++)
1364 if (streq (name, lang->name))
1365 return lang;
1366 error ("unknown language \"%s\"", name);
1369 return NULL;
1374 * Return a language given the interpreter name.
1376 static language *
1377 get_language_from_interpreter (char *interpreter)
1379 language *lang;
1380 const char **iname;
1382 if (interpreter == NULL)
1383 return NULL;
1384 for (lang = lang_names; lang->name != NULL; lang++)
1385 if (lang->interpreters != NULL)
1386 for (iname = lang->interpreters; *iname != NULL; iname++)
1387 if (streq (*iname, interpreter))
1388 return lang;
1390 return NULL;
1396 * Return a language given the file name.
1398 static language *
1399 get_language_from_filename (char *file, int case_sensitive)
1401 language *lang;
1402 const char **name, **ext, *suffix;
1404 /* Try whole file name first. */
1405 for (lang = lang_names; lang->name != NULL; lang++)
1406 if (lang->filenames != NULL)
1407 for (name = lang->filenames; *name != NULL; name++)
1408 if ((case_sensitive)
1409 ? streq (*name, file)
1410 : strcaseeq (*name, file))
1411 return lang;
1413 /* If not found, try suffix after last dot. */
1414 suffix = strrchr (file, '.');
1415 if (suffix == NULL)
1416 return NULL;
1417 suffix += 1;
1418 for (lang = lang_names; lang->name != NULL; lang++)
1419 if (lang->suffixes != NULL)
1420 for (ext = lang->suffixes; *ext != NULL; ext++)
1421 if ((case_sensitive)
1422 ? streq (*ext, suffix)
1423 : strcaseeq (*ext, suffix))
1424 return lang;
1425 return NULL;
1430 * This routine is called on each file argument.
1432 static void
1433 process_file_name (char *file, language *lang)
1435 struct stat stat_buf;
1436 FILE *inf;
1437 fdesc *fdp;
1438 compressor *compr;
1439 char *compressed_name, *uncompressed_name;
1440 char *ext, *real_name;
1441 int retval;
1443 canonicalize_filename (file);
1444 if (streq (file, tagfile) && !streq (tagfile, "-"))
1446 error ("skipping inclusion of %s in self.", file);
1447 return;
1449 if ((compr = get_compressor_from_suffix (file, &ext)) == NULL)
1451 compressed_name = NULL;
1452 real_name = uncompressed_name = savestr (file);
1454 else
1456 real_name = compressed_name = savestr (file);
1457 uncompressed_name = savenstr (file, ext - file);
1460 /* If the canonicalized uncompressed name
1461 has already been dealt with, skip it silently. */
1462 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1464 assert (fdp->infname != NULL);
1465 if (streq (uncompressed_name, fdp->infname))
1466 goto cleanup;
1469 if (stat (real_name, &stat_buf) != 0)
1471 /* Reset real_name and try with a different name. */
1472 real_name = NULL;
1473 if (compressed_name != NULL) /* try with the given suffix */
1475 if (stat (uncompressed_name, &stat_buf) == 0)
1476 real_name = uncompressed_name;
1478 else /* try all possible suffixes */
1480 for (compr = compressors; compr->suffix != NULL; compr++)
1482 compressed_name = concat (file, ".", compr->suffix);
1483 if (stat (compressed_name, &stat_buf) != 0)
1485 if (MSDOS)
1487 char *suf = compressed_name + strlen (file);
1488 size_t suflen = strlen (compr->suffix) + 1;
1489 for ( ; suf[1]; suf++, suflen--)
1491 memmove (suf, suf + 1, suflen);
1492 if (stat (compressed_name, &stat_buf) == 0)
1494 real_name = compressed_name;
1495 break;
1498 if (real_name != NULL)
1499 break;
1500 } /* MSDOS */
1501 free (compressed_name);
1502 compressed_name = NULL;
1504 else
1506 real_name = compressed_name;
1507 break;
1511 if (real_name == NULL)
1513 perror (file);
1514 goto cleanup;
1516 } /* try with a different name */
1518 if (!S_ISREG (stat_buf.st_mode))
1520 error ("skipping %s: it is not a regular file.", real_name);
1521 goto cleanup;
1523 if (real_name == compressed_name)
1525 char *cmd = concat (compr->command, " ", real_name);
1526 inf = popen (cmd, "r" FOPEN_BINARY);
1527 free (cmd);
1529 else
1530 inf = fopen (real_name, "r" FOPEN_BINARY);
1531 if (inf == NULL)
1533 perror (real_name);
1534 goto cleanup;
1537 process_file (inf, uncompressed_name, lang);
1539 if (real_name == compressed_name)
1540 retval = pclose (inf);
1541 else
1542 retval = fclose (inf);
1543 if (retval < 0)
1544 pfatal (file);
1546 cleanup:
1547 free (compressed_name);
1548 free (uncompressed_name);
1549 last_node = NULL;
1550 curfdp = NULL;
1551 return;
1554 static void
1555 process_file (FILE *fh, char *fn, language *lang)
1557 static const fdesc emptyfdesc;
1558 fdesc *fdp;
1560 /* Create a new input file description entry. */
1561 fdp = xnew (1, fdesc);
1562 *fdp = emptyfdesc;
1563 fdp->next = fdhead;
1564 fdp->infname = savestr (fn);
1565 fdp->lang = lang;
1566 fdp->infabsname = absolute_filename (fn, cwd);
1567 fdp->infabsdir = absolute_dirname (fn, cwd);
1568 if (filename_is_absolute (fn))
1570 /* An absolute file name. Canonicalize it. */
1571 fdp->taggedfname = absolute_filename (fn, NULL);
1573 else
1575 /* A file name relative to cwd. Make it relative
1576 to the directory of the tags file. */
1577 fdp->taggedfname = relative_filename (fn, tagfiledir);
1579 fdp->usecharno = true; /* use char position when making tags */
1580 fdp->prop = NULL;
1581 fdp->written = false; /* not written on tags file yet */
1583 fdhead = fdp;
1584 curfdp = fdhead; /* the current file description */
1586 find_entries (fh);
1588 /* If not Ctags, and if this is not metasource and if it contained no #line
1589 directives, we can write the tags and free all nodes pointing to
1590 curfdp. */
1591 if (!CTAGS
1592 && curfdp->usecharno /* no #line directives in this file */
1593 && !curfdp->lang->metasource)
1595 node *np, *prev;
1597 /* Look for the head of the sublist relative to this file. See add_node
1598 for the structure of the node tree. */
1599 prev = NULL;
1600 for (np = nodehead; np != NULL; prev = np, np = np->left)
1601 if (np->fdp == curfdp)
1602 break;
1604 /* If we generated tags for this file, write and delete them. */
1605 if (np != NULL)
1607 /* This is the head of the last sublist, if any. The following
1608 instructions depend on this being true. */
1609 assert (np->left == NULL);
1611 assert (fdhead == curfdp);
1612 assert (last_node->fdp == curfdp);
1613 put_entries (np); /* write tags for file curfdp->taggedfname */
1614 free_tree (np); /* remove the written nodes */
1615 if (prev == NULL)
1616 nodehead = NULL; /* no nodes left */
1617 else
1618 prev->left = NULL; /* delete the pointer to the sublist */
1624 * This routine sets up the boolean pseudo-functions which work
1625 * by setting boolean flags dependent upon the corresponding character.
1626 * Every char which is NOT in that string is not a white char. Therefore,
1627 * all of the array "_wht" is set to false, and then the elements
1628 * subscripted by the chars in "white" are set to true. Thus "_wht"
1629 * of a char is true if it is the string "white", else false.
1631 static void
1632 init (void)
1634 const char *sp;
1635 int i;
1637 for (i = 0; i < CHARS; i++)
1638 iswhite (i) = notinname (i) = begtoken (i) = intoken (i) = endtoken (i)
1639 = false;
1640 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = true;
1641 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = true;
1642 notinname ('\0') = notinname ('\n');
1643 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = true;
1644 begtoken ('\0') = begtoken ('\n');
1645 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = true;
1646 intoken ('\0') = intoken ('\n');
1647 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = true;
1648 endtoken ('\0') = endtoken ('\n');
1652 * This routine opens the specified file and calls the function
1653 * which finds the function and type definitions.
1655 static void
1656 find_entries (FILE *inf)
1658 char *cp;
1659 language *lang = curfdp->lang;
1660 Lang_function *parser = NULL;
1662 /* If user specified a language, use it. */
1663 if (lang != NULL && lang->function != NULL)
1665 parser = lang->function;
1668 /* Else try to guess the language given the file name. */
1669 if (parser == NULL)
1671 lang = get_language_from_filename (curfdp->infname, true);
1672 if (lang != NULL && lang->function != NULL)
1674 curfdp->lang = lang;
1675 parser = lang->function;
1679 /* Else look for sharp-bang as the first two characters. */
1680 if (parser == NULL
1681 && readline_internal (&lb, inf) > 0
1682 && lb.len >= 2
1683 && lb.buffer[0] == '#'
1684 && lb.buffer[1] == '!')
1686 char *lp;
1688 /* Set lp to point at the first char after the last slash in the
1689 line or, if no slashes, at the first nonblank. Then set cp to
1690 the first successive blank and terminate the string. */
1691 lp = strrchr (lb.buffer+2, '/');
1692 if (lp != NULL)
1693 lp += 1;
1694 else
1695 lp = skip_spaces (lb.buffer + 2);
1696 cp = skip_non_spaces (lp);
1697 *cp = '\0';
1699 if (strlen (lp) > 0)
1701 lang = get_language_from_interpreter (lp);
1702 if (lang != NULL && lang->function != NULL)
1704 curfdp->lang = lang;
1705 parser = lang->function;
1710 /* We rewind here, even if inf may be a pipe. We fail if the
1711 length of the first line is longer than the pipe block size,
1712 which is unlikely. */
1713 rewind (inf);
1715 /* Else try to guess the language given the case insensitive file name. */
1716 if (parser == NULL)
1718 lang = get_language_from_filename (curfdp->infname, false);
1719 if (lang != NULL && lang->function != NULL)
1721 curfdp->lang = lang;
1722 parser = lang->function;
1726 /* Else try Fortran or C. */
1727 if (parser == NULL)
1729 node *old_last_node = last_node;
1731 curfdp->lang = get_language_from_langname ("fortran");
1732 find_entries (inf);
1734 if (old_last_node == last_node)
1735 /* No Fortran entries found. Try C. */
1737 /* We do not tag if rewind fails.
1738 Only the file name will be recorded in the tags file. */
1739 rewind (inf);
1740 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1741 find_entries (inf);
1743 return;
1746 if (!no_line_directive
1747 && curfdp->lang != NULL && curfdp->lang->metasource)
1748 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1749 file, or anyway we parsed a file that is automatically generated from
1750 this one. If this is the case, the bingo.c file contained #line
1751 directives that generated tags pointing to this file. Let's delete
1752 them all before parsing this file, which is the real source. */
1754 fdesc **fdpp = &fdhead;
1755 while (*fdpp != NULL)
1756 if (*fdpp != curfdp
1757 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1758 /* We found one of those! We must delete both the file description
1759 and all tags referring to it. */
1761 fdesc *badfdp = *fdpp;
1763 /* Delete the tags referring to badfdp->taggedfname
1764 that were obtained from badfdp->infname. */
1765 invalidate_nodes (badfdp, &nodehead);
1767 *fdpp = badfdp->next; /* remove the bad description from the list */
1768 free_fdesc (badfdp);
1770 else
1771 fdpp = &(*fdpp)->next; /* advance the list pointer */
1774 assert (parser != NULL);
1776 /* Generic initializations before reading from file. */
1777 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1779 /* Generic initializations before parsing file with readline. */
1780 lineno = 0; /* reset global line number */
1781 charno = 0; /* reset global char number */
1782 linecharno = 0; /* reset global char number of line start */
1784 parser (inf);
1786 regex_tag_multiline ();
1791 * Check whether an implicitly named tag should be created,
1792 * then call `pfnote'.
1793 * NAME is a string that is internally copied by this function.
1795 * TAGS format specification
1796 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1797 * The following is explained in some more detail in etc/ETAGS.EBNF.
1799 * make_tag creates tags with "implicit tag names" (unnamed tags)
1800 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1801 * 1. NAME does not contain any of the characters in NONAM;
1802 * 2. LINESTART contains name as either a rightmost, or rightmost but
1803 * one character, substring;
1804 * 3. the character, if any, immediately before NAME in LINESTART must
1805 * be a character in NONAM;
1806 * 4. the character, if any, immediately after NAME in LINESTART must
1807 * also be a character in NONAM.
1809 * The implementation uses the notinname() macro, which recognizes the
1810 * characters stored in the string `nonam'.
1811 * etags.el needs to use the same characters that are in NONAM.
1813 static void
1814 make_tag (const char *name, /* tag name, or NULL if unnamed */
1815 int namelen, /* tag length */
1816 bool is_func, /* tag is a function */
1817 char *linestart, /* start of the line where tag is */
1818 int linelen, /* length of the line where tag is */
1819 int lno, /* line number */
1820 long int cno) /* character number */
1822 bool named = (name != NULL && namelen > 0);
1823 char *nname = NULL;
1825 if (!CTAGS && named) /* maybe set named to false */
1826 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1827 such that etags.el can guess a name from it. */
1829 int i;
1830 register const char *cp = name;
1832 for (i = 0; i < namelen; i++)
1833 if (notinname (*cp++))
1834 break;
1835 if (i == namelen) /* rule #1 */
1837 cp = linestart + linelen - namelen;
1838 if (notinname (linestart[linelen-1]))
1839 cp -= 1; /* rule #4 */
1840 if (cp >= linestart /* rule #2 */
1841 && (cp == linestart
1842 || notinname (cp[-1])) /* rule #3 */
1843 && strneq (name, cp, namelen)) /* rule #2 */
1844 named = false; /* use implicit tag name */
1848 if (named)
1849 nname = savenstr (name, namelen);
1851 pfnote (nname, is_func, linestart, linelen, lno, cno);
1854 /* Record a tag. */
1855 static void
1856 pfnote (char *name, bool is_func, char *linestart, int linelen, int lno,
1857 long int cno)
1858 /* tag name, or NULL if unnamed */
1859 /* tag is a function */
1860 /* start of the line where tag is */
1861 /* length of the line where tag is */
1862 /* line number */
1863 /* character number */
1865 register node *np;
1867 assert (name == NULL || name[0] != '\0');
1868 if (CTAGS && name == NULL)
1869 return;
1871 np = xnew (1, node);
1873 /* If ctags mode, change name "main" to M<thisfilename>. */
1874 if (CTAGS && !cxref_style && streq (name, "main"))
1876 char *fp = strrchr (curfdp->taggedfname, '/');
1877 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
1878 fp = strrchr (np->name, '.');
1879 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
1880 fp[0] = '\0';
1882 else
1883 np->name = name;
1884 np->valid = true;
1885 np->been_warned = false;
1886 np->fdp = curfdp;
1887 np->is_func = is_func;
1888 np->lno = lno;
1889 if (np->fdp->usecharno)
1890 /* Our char numbers are 0-base, because of C language tradition?
1891 ctags compatibility? old versions compatibility? I don't know.
1892 Anyway, since emacs's are 1-base we expect etags.el to take care
1893 of the difference. If we wanted to have 1-based numbers, we would
1894 uncomment the +1 below. */
1895 np->cno = cno /* + 1 */ ;
1896 else
1897 np->cno = invalidcharno;
1898 np->left = np->right = NULL;
1899 if (CTAGS && !cxref_style)
1901 if (strlen (linestart) < 50)
1902 np->regex = concat (linestart, "$", "");
1903 else
1904 np->regex = savenstr (linestart, 50);
1906 else
1907 np->regex = savenstr (linestart, linelen);
1909 add_node (np, &nodehead);
1913 * free_tree ()
1914 * recurse on left children, iterate on right children.
1916 static void
1917 free_tree (register node *np)
1919 while (np)
1921 register node *node_right = np->right;
1922 free_tree (np->left);
1923 free (np->name);
1924 free (np->regex);
1925 free (np);
1926 np = node_right;
1931 * free_fdesc ()
1932 * delete a file description
1934 static void
1935 free_fdesc (register fdesc *fdp)
1937 free (fdp->infname);
1938 free (fdp->infabsname);
1939 free (fdp->infabsdir);
1940 free (fdp->taggedfname);
1941 free (fdp->prop);
1942 free (fdp);
1946 * add_node ()
1947 * Adds a node to the tree of nodes. In etags mode, sort by file
1948 * name. In ctags mode, sort by tag name. Make no attempt at
1949 * balancing.
1951 * add_node is the only function allowed to add nodes, so it can
1952 * maintain state.
1954 static void
1955 add_node (node *np, node **cur_node_p)
1957 register int dif;
1958 register node *cur_node = *cur_node_p;
1960 if (cur_node == NULL)
1962 *cur_node_p = np;
1963 last_node = np;
1964 return;
1967 if (!CTAGS)
1968 /* Etags Mode */
1970 /* For each file name, tags are in a linked sublist on the right
1971 pointer. The first tags of different files are a linked list
1972 on the left pointer. last_node points to the end of the last
1973 used sublist. */
1974 if (last_node != NULL && last_node->fdp == np->fdp)
1976 /* Let's use the same sublist as the last added node. */
1977 assert (last_node->right == NULL);
1978 last_node->right = np;
1979 last_node = np;
1981 else if (cur_node->fdp == np->fdp)
1983 /* Scanning the list we found the head of a sublist which is
1984 good for us. Let's scan this sublist. */
1985 add_node (np, &cur_node->right);
1987 else
1988 /* The head of this sublist is not good for us. Let's try the
1989 next one. */
1990 add_node (np, &cur_node->left);
1991 } /* if ETAGS mode */
1993 else
1995 /* Ctags Mode */
1996 dif = strcmp (np->name, cur_node->name);
1999 * If this tag name matches an existing one, then
2000 * do not add the node, but maybe print a warning.
2002 if (no_duplicates && !dif)
2004 if (np->fdp == cur_node->fdp)
2006 if (!no_warnings)
2008 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2009 np->fdp->infname, lineno, np->name);
2010 fprintf (stderr, "Second entry ignored\n");
2013 else if (!cur_node->been_warned && !no_warnings)
2015 fprintf
2016 (stderr,
2017 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2018 np->fdp->infname, cur_node->fdp->infname, np->name);
2019 cur_node->been_warned = true;
2021 return;
2024 /* Actually add the node */
2025 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2026 } /* if CTAGS mode */
2030 * invalidate_nodes ()
2031 * Scan the node tree and invalidate all nodes pointing to the
2032 * given file description (CTAGS case) or free them (ETAGS case).
2034 static void
2035 invalidate_nodes (fdesc *badfdp, node **npp)
2037 node *np = *npp;
2039 if (np == NULL)
2040 return;
2042 if (CTAGS)
2044 if (np->left != NULL)
2045 invalidate_nodes (badfdp, &np->left);
2046 if (np->fdp == badfdp)
2047 np->valid = false;
2048 if (np->right != NULL)
2049 invalidate_nodes (badfdp, &np->right);
2051 else
2053 assert (np->fdp != NULL);
2054 if (np->fdp == badfdp)
2056 *npp = np->left; /* detach the sublist from the list */
2057 np->left = NULL; /* isolate it */
2058 free_tree (np); /* free it */
2059 invalidate_nodes (badfdp, npp);
2061 else
2062 invalidate_nodes (badfdp, &np->left);
2067 static int total_size_of_entries (node *);
2068 static int number_len (long) ATTRIBUTE_CONST;
2070 /* Length of a non-negative number's decimal representation. */
2071 static int
2072 number_len (long int num)
2074 int len = 1;
2075 while ((num /= 10) > 0)
2076 len += 1;
2077 return len;
2081 * Return total number of characters that put_entries will output for
2082 * the nodes in the linked list at the right of the specified node.
2083 * This count is irrelevant with etags.el since emacs 19.34 at least,
2084 * but is still supplied for backward compatibility.
2086 static int
2087 total_size_of_entries (register node *np)
2089 register int total = 0;
2091 for (; np != NULL; np = np->right)
2092 if (np->valid)
2094 total += strlen (np->regex) + 1; /* pat\177 */
2095 if (np->name != NULL)
2096 total += strlen (np->name) + 1; /* name\001 */
2097 total += number_len ((long) np->lno) + 1; /* lno, */
2098 if (np->cno != invalidcharno) /* cno */
2099 total += number_len (np->cno);
2100 total += 1; /* newline */
2103 return total;
2106 static void
2107 put_entries (register node *np)
2109 register char *sp;
2110 static fdesc *fdp = NULL;
2112 if (np == NULL)
2113 return;
2115 /* Output subentries that precede this one */
2116 if (CTAGS)
2117 put_entries (np->left);
2119 /* Output this entry */
2120 if (np->valid)
2122 if (!CTAGS)
2124 /* Etags mode */
2125 if (fdp != np->fdp)
2127 fdp = np->fdp;
2128 fprintf (tagf, "\f\n%s,%d\n",
2129 fdp->taggedfname, total_size_of_entries (np));
2130 fdp->written = true;
2132 fputs (np->regex, tagf);
2133 fputc ('\177', tagf);
2134 if (np->name != NULL)
2136 fputs (np->name, tagf);
2137 fputc ('\001', tagf);
2139 fprintf (tagf, "%d,", np->lno);
2140 if (np->cno != invalidcharno)
2141 fprintf (tagf, "%ld", np->cno);
2142 fputs ("\n", tagf);
2144 else
2146 /* Ctags mode */
2147 if (np->name == NULL)
2148 error ("internal error: NULL name in ctags mode.");
2150 if (cxref_style)
2152 if (vgrind_style)
2153 fprintf (stdout, "%s %s %d\n",
2154 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2155 else
2156 fprintf (stdout, "%-16s %3d %-16s %s\n",
2157 np->name, np->lno, np->fdp->taggedfname, np->regex);
2159 else
2161 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2163 if (np->is_func)
2164 { /* function or #define macro with args */
2165 putc (searchar, tagf);
2166 putc ('^', tagf);
2168 for (sp = np->regex; *sp; sp++)
2170 if (*sp == '\\' || *sp == searchar)
2171 putc ('\\', tagf);
2172 putc (*sp, tagf);
2174 putc (searchar, tagf);
2176 else
2177 { /* anything else; text pattern inadequate */
2178 fprintf (tagf, "%d", np->lno);
2180 putc ('\n', tagf);
2183 } /* if this node contains a valid tag */
2185 /* Output subentries that follow this one */
2186 put_entries (np->right);
2187 if (!CTAGS)
2188 put_entries (np->left);
2192 /* C extensions. */
2193 #define C_EXT 0x00fff /* C extensions */
2194 #define C_PLAIN 0x00000 /* C */
2195 #define C_PLPL 0x00001 /* C++ */
2196 #define C_STAR 0x00003 /* C* */
2197 #define C_JAVA 0x00005 /* JAVA */
2198 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2199 #define YACC 0x10000 /* yacc file */
2202 * The C symbol tables.
2204 enum sym_type
2206 st_none,
2207 st_C_objprot, st_C_objimpl, st_C_objend,
2208 st_C_gnumacro,
2209 st_C_ignore, st_C_attribute,
2210 st_C_javastruct,
2211 st_C_operator,
2212 st_C_class, st_C_template,
2213 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2216 /* Feed stuff between (but not including) %[ and %] lines to:
2217 gperf -m 5
2219 %compare-strncmp
2220 %enum
2221 %struct-type
2222 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2224 if, 0, st_C_ignore
2225 for, 0, st_C_ignore
2226 while, 0, st_C_ignore
2227 switch, 0, st_C_ignore
2228 return, 0, st_C_ignore
2229 __attribute__, 0, st_C_attribute
2230 GTY, 0, st_C_attribute
2231 @interface, 0, st_C_objprot
2232 @protocol, 0, st_C_objprot
2233 @implementation,0, st_C_objimpl
2234 @end, 0, st_C_objend
2235 import, (C_JAVA & ~C_PLPL), st_C_ignore
2236 package, (C_JAVA & ~C_PLPL), st_C_ignore
2237 friend, C_PLPL, st_C_ignore
2238 extends, (C_JAVA & ~C_PLPL), st_C_javastruct
2239 implements, (C_JAVA & ~C_PLPL), st_C_javastruct
2240 interface, (C_JAVA & ~C_PLPL), st_C_struct
2241 class, 0, st_C_class
2242 namespace, C_PLPL, st_C_struct
2243 domain, C_STAR, st_C_struct
2244 union, 0, st_C_struct
2245 struct, 0, st_C_struct
2246 extern, 0, st_C_extern
2247 enum, 0, st_C_enum
2248 typedef, 0, st_C_typedef
2249 define, 0, st_C_define
2250 undef, 0, st_C_define
2251 operator, C_PLPL, st_C_operator
2252 template, 0, st_C_template
2253 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2254 DEFUN, 0, st_C_gnumacro
2255 SYSCALL, 0, st_C_gnumacro
2256 ENTRY, 0, st_C_gnumacro
2257 PSEUDO, 0, st_C_gnumacro
2258 # These are defined inside C functions, so currently they are not met.
2259 # EXFUN used in glibc, DEFVAR_* in emacs.
2260 #EXFUN, 0, st_C_gnumacro
2261 #DEFVAR_, 0, st_C_gnumacro
2263 and replace lines between %< and %> with its output, then:
2264 - remove the #if characterset check
2265 - make in_word_set static and not inline. */
2266 /*%<*/
2267 /* C code produced by gperf version 3.0.1 */
2268 /* Command-line: gperf -m 5 */
2269 /* Computed positions: -k'2-3' */
2271 struct C_stab_entry { const char *name; int c_ext; enum sym_type type; };
2272 /* maximum key range = 33, duplicates = 0 */
2274 static int
2275 hash (const char *str, int len)
2277 static char const asso_values[] =
2279 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2280 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2281 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2282 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2283 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2284 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2285 35, 35, 35, 35, 35, 35, 35, 35, 35, 3,
2286 26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2287 35, 35, 35, 24, 0, 35, 35, 35, 35, 0,
2288 35, 35, 35, 35, 35, 1, 35, 16, 35, 6,
2289 23, 0, 0, 35, 22, 0, 35, 35, 5, 0,
2290 0, 15, 1, 35, 6, 35, 8, 19, 35, 16,
2291 4, 5, 35, 35, 35, 35, 35, 35, 35, 35,
2292 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2293 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2294 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2295 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2296 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2297 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2298 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2299 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2300 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2301 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2302 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2303 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2304 35, 35, 35, 35, 35, 35
2306 int hval = len;
2308 switch (hval)
2310 default:
2311 hval += asso_values[(unsigned char) str[2]];
2312 /*FALLTHROUGH*/
2313 case 2:
2314 hval += asso_values[(unsigned char) str[1]];
2315 break;
2317 return hval;
2320 static struct C_stab_entry *
2321 in_word_set (register const char *str, register unsigned int len)
2323 enum
2325 TOTAL_KEYWORDS = 33,
2326 MIN_WORD_LENGTH = 2,
2327 MAX_WORD_LENGTH = 15,
2328 MIN_HASH_VALUE = 2,
2329 MAX_HASH_VALUE = 34
2332 static struct C_stab_entry wordlist[] =
2334 {""}, {""},
2335 {"if", 0, st_C_ignore},
2336 {"GTY", 0, st_C_attribute},
2337 {"@end", 0, st_C_objend},
2338 {"union", 0, st_C_struct},
2339 {"define", 0, st_C_define},
2340 {"import", (C_JAVA & ~C_PLPL), st_C_ignore},
2341 {"template", 0, st_C_template},
2342 {"operator", C_PLPL, st_C_operator},
2343 {"@interface", 0, st_C_objprot},
2344 {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct},
2345 {"friend", C_PLPL, st_C_ignore},
2346 {"typedef", 0, st_C_typedef},
2347 {"return", 0, st_C_ignore},
2348 {"@implementation",0, st_C_objimpl},
2349 {"@protocol", 0, st_C_objprot},
2350 {"interface", (C_JAVA & ~C_PLPL), st_C_struct},
2351 {"extern", 0, st_C_extern},
2352 {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct},
2353 {"struct", 0, st_C_struct},
2354 {"domain", C_STAR, st_C_struct},
2355 {"switch", 0, st_C_ignore},
2356 {"enum", 0, st_C_enum},
2357 {"for", 0, st_C_ignore},
2358 {"namespace", C_PLPL, st_C_struct},
2359 {"class", 0, st_C_class},
2360 {"while", 0, st_C_ignore},
2361 {"undef", 0, st_C_define},
2362 {"package", (C_JAVA & ~C_PLPL), st_C_ignore},
2363 {"__attribute__", 0, st_C_attribute},
2364 {"SYSCALL", 0, st_C_gnumacro},
2365 {"ENTRY", 0, st_C_gnumacro},
2366 {"PSEUDO", 0, st_C_gnumacro},
2367 {"DEFUN", 0, st_C_gnumacro}
2370 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2372 int key = hash (str, len);
2374 if (key <= MAX_HASH_VALUE && key >= 0)
2376 const char *s = wordlist[key].name;
2378 if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2379 return &wordlist[key];
2382 return 0;
2384 /*%>*/
2386 static enum sym_type
2387 C_symtype (char *str, int len, int c_ext)
2389 register struct C_stab_entry *se = in_word_set (str, len);
2391 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2392 return st_none;
2393 return se->type;
2398 * Ignoring __attribute__ ((list))
2400 static bool inattribute; /* looking at an __attribute__ construct */
2403 * C functions and variables are recognized using a simple
2404 * finite automaton. fvdef is its state variable.
2406 static enum
2408 fvnone, /* nothing seen */
2409 fdefunkey, /* Emacs DEFUN keyword seen */
2410 fdefunname, /* Emacs DEFUN name seen */
2411 foperator, /* func: operator keyword seen (cplpl) */
2412 fvnameseen, /* function or variable name seen */
2413 fstartlist, /* func: just after open parenthesis */
2414 finlist, /* func: in parameter list */
2415 flistseen, /* func: after parameter list */
2416 fignore, /* func: before open brace */
2417 vignore /* var-like: ignore until ';' */
2418 } fvdef;
2420 static bool fvextern; /* func or var: extern keyword seen; */
2423 * typedefs are recognized using a simple finite automaton.
2424 * typdef is its state variable.
2426 static enum
2428 tnone, /* nothing seen */
2429 tkeyseen, /* typedef keyword seen */
2430 ttypeseen, /* defined type seen */
2431 tinbody, /* inside typedef body */
2432 tend, /* just before typedef tag */
2433 tignore /* junk after typedef tag */
2434 } typdef;
2437 * struct-like structures (enum, struct and union) are recognized
2438 * using another simple finite automaton. `structdef' is its state
2439 * variable.
2441 static enum
2443 snone, /* nothing seen yet,
2444 or in struct body if bracelev > 0 */
2445 skeyseen, /* struct-like keyword seen */
2446 stagseen, /* struct-like tag seen */
2447 scolonseen /* colon seen after struct-like tag */
2448 } structdef;
2451 * When objdef is different from onone, objtag is the name of the class.
2453 static const char *objtag = "<uninited>";
2456 * Yet another little state machine to deal with preprocessor lines.
2458 static enum
2460 dnone, /* nothing seen */
2461 dsharpseen, /* '#' seen as first char on line */
2462 ddefineseen, /* '#' and 'define' seen */
2463 dignorerest /* ignore rest of line */
2464 } definedef;
2467 * State machine for Objective C protocols and implementations.
2468 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2470 static enum
2472 onone, /* nothing seen */
2473 oprotocol, /* @interface or @protocol seen */
2474 oimplementation, /* @implementations seen */
2475 otagseen, /* class name seen */
2476 oparenseen, /* parenthesis before category seen */
2477 ocatseen, /* category name seen */
2478 oinbody, /* in @implementation body */
2479 omethodsign, /* in @implementation body, after +/- */
2480 omethodtag, /* after method name */
2481 omethodcolon, /* after method colon */
2482 omethodparm, /* after method parameter */
2483 oignore /* wait for @end */
2484 } objdef;
2488 * Use this structure to keep info about the token read, and how it
2489 * should be tagged. Used by the make_C_tag function to build a tag.
2491 static struct tok
2493 char *line; /* string containing the token */
2494 int offset; /* where the token starts in LINE */
2495 int length; /* token length */
2497 The previous members can be used to pass strings around for generic
2498 purposes. The following ones specifically refer to creating tags. In this
2499 case the token contained here is the pattern that will be used to create a
2500 tag.
2502 bool valid; /* do not create a tag; the token should be
2503 invalidated whenever a state machine is
2504 reset prematurely */
2505 bool named; /* create a named tag */
2506 int lineno; /* source line number of tag */
2507 long linepos; /* source char number of tag */
2508 } token; /* latest token read */
2511 * Variables and functions for dealing with nested structures.
2512 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2514 static void pushclass_above (int, char *, int);
2515 static void popclass_above (int);
2516 static void write_classname (linebuffer *, const char *qualifier);
2518 static struct {
2519 char **cname; /* nested class names */
2520 int *bracelev; /* nested class brace level */
2521 int nl; /* class nesting level (elements used) */
2522 int size; /* length of the array */
2523 } cstack; /* stack for nested declaration tags */
2524 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2525 #define nestlev (cstack.nl)
2526 /* After struct keyword or in struct body, not inside a nested function. */
2527 #define instruct (structdef == snone && nestlev > 0 \
2528 && bracelev == cstack.bracelev[nestlev-1] + 1)
2530 static void
2531 pushclass_above (int bracelev, char *str, int len)
2533 int nl;
2535 popclass_above (bracelev);
2536 nl = cstack.nl;
2537 if (nl >= cstack.size)
2539 int size = cstack.size *= 2;
2540 xrnew (cstack.cname, size, char *);
2541 xrnew (cstack.bracelev, size, int);
2543 assert (nl == 0 || cstack.bracelev[nl-1] < bracelev);
2544 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2545 cstack.bracelev[nl] = bracelev;
2546 cstack.nl = nl + 1;
2549 static void
2550 popclass_above (int bracelev)
2552 int nl;
2554 for (nl = cstack.nl - 1;
2555 nl >= 0 && cstack.bracelev[nl] >= bracelev;
2556 nl--)
2558 free (cstack.cname[nl]);
2559 cstack.nl = nl;
2563 static void
2564 write_classname (linebuffer *cn, const char *qualifier)
2566 int i, len;
2567 int qlen = strlen (qualifier);
2569 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2571 len = 0;
2572 cn->len = 0;
2573 cn->buffer[0] = '\0';
2575 else
2577 len = strlen (cstack.cname[0]);
2578 linebuffer_setlen (cn, len);
2579 strcpy (cn->buffer, cstack.cname[0]);
2581 for (i = 1; i < cstack.nl; i++)
2583 char *s = cstack.cname[i];
2584 if (s == NULL)
2585 continue;
2586 linebuffer_setlen (cn, len + qlen + strlen (s));
2587 len += sprintf (cn->buffer + len, "%s%s", qualifier, s);
2592 static bool consider_token (char *, int, int, int *, int, int, bool *);
2593 static void make_C_tag (bool);
2596 * consider_token ()
2597 * checks to see if the current token is at the start of a
2598 * function or variable, or corresponds to a typedef, or
2599 * is a struct/union/enum tag, or #define, or an enum constant.
2601 * *IS_FUNC_OR_VAR gets true if the token is a function or #define macro
2602 * with args. C_EXTP points to which language we are looking at.
2604 * Globals
2605 * fvdef IN OUT
2606 * structdef IN OUT
2607 * definedef IN OUT
2608 * typdef IN OUT
2609 * objdef IN OUT
2612 static bool
2613 consider_token (char *str, int len, int c, int *c_extp,
2614 int bracelev, int parlev, bool *is_func_or_var)
2615 /* IN: token pointer */
2616 /* IN: token length */
2617 /* IN: first char after the token */
2618 /* IN, OUT: C extensions mask */
2619 /* IN: brace level */
2620 /* IN: parenthesis level */
2621 /* OUT: function or variable found */
2623 /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2624 structtype is the type of the preceding struct-like keyword, and
2625 structbracelev is the brace level where it has been seen. */
2626 static enum sym_type structtype;
2627 static int structbracelev;
2628 static enum sym_type toktype;
2631 toktype = C_symtype (str, len, *c_extp);
2634 * Skip __attribute__
2636 if (toktype == st_C_attribute)
2638 inattribute = true;
2639 return false;
2643 * Advance the definedef state machine.
2645 switch (definedef)
2647 case dnone:
2648 /* We're not on a preprocessor line. */
2649 if (toktype == st_C_gnumacro)
2651 fvdef = fdefunkey;
2652 return false;
2654 break;
2655 case dsharpseen:
2656 if (toktype == st_C_define)
2658 definedef = ddefineseen;
2660 else
2662 definedef = dignorerest;
2664 return false;
2665 case ddefineseen:
2667 * Make a tag for any macro, unless it is a constant
2668 * and constantypedefs is false.
2670 definedef = dignorerest;
2671 *is_func_or_var = (c == '(');
2672 if (!*is_func_or_var && !constantypedefs)
2673 return false;
2674 else
2675 return true;
2676 case dignorerest:
2677 return false;
2678 default:
2679 error ("internal error: definedef value.");
2683 * Now typedefs
2685 switch (typdef)
2687 case tnone:
2688 if (toktype == st_C_typedef)
2690 if (typedefs)
2691 typdef = tkeyseen;
2692 fvextern = false;
2693 fvdef = fvnone;
2694 return false;
2696 break;
2697 case tkeyseen:
2698 switch (toktype)
2700 case st_none:
2701 case st_C_class:
2702 case st_C_struct:
2703 case st_C_enum:
2704 typdef = ttypeseen;
2706 break;
2707 case ttypeseen:
2708 if (structdef == snone && fvdef == fvnone)
2710 fvdef = fvnameseen;
2711 return true;
2713 break;
2714 case tend:
2715 switch (toktype)
2717 case st_C_class:
2718 case st_C_struct:
2719 case st_C_enum:
2720 return false;
2722 return true;
2725 switch (toktype)
2727 case st_C_javastruct:
2728 if (structdef == stagseen)
2729 structdef = scolonseen;
2730 return false;
2731 case st_C_template:
2732 case st_C_class:
2733 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2734 && bracelev == 0
2735 && definedef == dnone && structdef == snone
2736 && typdef == tnone && fvdef == fvnone)
2737 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2738 if (toktype == st_C_template)
2739 break;
2740 /* FALLTHRU */
2741 case st_C_struct:
2742 case st_C_enum:
2743 if (parlev == 0
2744 && fvdef != vignore
2745 && (typdef == tkeyseen
2746 || (typedefs_or_cplusplus && structdef == snone)))
2748 structdef = skeyseen;
2749 structtype = toktype;
2750 structbracelev = bracelev;
2751 if (fvdef == fvnameseen)
2752 fvdef = fvnone;
2754 return false;
2757 if (structdef == skeyseen)
2759 structdef = stagseen;
2760 return true;
2763 if (typdef != tnone)
2764 definedef = dnone;
2766 /* Detect Objective C constructs. */
2767 switch (objdef)
2769 case onone:
2770 switch (toktype)
2772 case st_C_objprot:
2773 objdef = oprotocol;
2774 return false;
2775 case st_C_objimpl:
2776 objdef = oimplementation;
2777 return false;
2779 break;
2780 case oimplementation:
2781 /* Save the class tag for functions or variables defined inside. */
2782 objtag = savenstr (str, len);
2783 objdef = oinbody;
2784 return false;
2785 case oprotocol:
2786 /* Save the class tag for categories. */
2787 objtag = savenstr (str, len);
2788 objdef = otagseen;
2789 *is_func_or_var = true;
2790 return true;
2791 case oparenseen:
2792 objdef = ocatseen;
2793 *is_func_or_var = true;
2794 return true;
2795 case oinbody:
2796 break;
2797 case omethodsign:
2798 if (parlev == 0)
2800 fvdef = fvnone;
2801 objdef = omethodtag;
2802 linebuffer_setlen (&token_name, len);
2803 memcpy (token_name.buffer, str, len);
2804 token_name.buffer[len] = '\0';
2805 return true;
2807 return false;
2808 case omethodcolon:
2809 if (parlev == 0)
2810 objdef = omethodparm;
2811 return false;
2812 case omethodparm:
2813 if (parlev == 0)
2815 int oldlen = token_name.len;
2816 fvdef = fvnone;
2817 objdef = omethodtag;
2818 linebuffer_setlen (&token_name, oldlen + len);
2819 memcpy (token_name.buffer + oldlen, str, len);
2820 token_name.buffer[oldlen + len] = '\0';
2821 return true;
2823 return false;
2824 case oignore:
2825 if (toktype == st_C_objend)
2827 /* Memory leakage here: the string pointed by objtag is
2828 never released, because many tests would be needed to
2829 avoid breaking on incorrect input code. The amount of
2830 memory leaked here is the sum of the lengths of the
2831 class tags.
2832 free (objtag); */
2833 objdef = onone;
2835 return false;
2838 /* A function, variable or enum constant? */
2839 switch (toktype)
2841 case st_C_extern:
2842 fvextern = true;
2843 switch (fvdef)
2845 case finlist:
2846 case flistseen:
2847 case fignore:
2848 case vignore:
2849 break;
2850 default:
2851 fvdef = fvnone;
2853 return false;
2854 case st_C_ignore:
2855 fvextern = false;
2856 fvdef = vignore;
2857 return false;
2858 case st_C_operator:
2859 fvdef = foperator;
2860 *is_func_or_var = true;
2861 return true;
2862 case st_none:
2863 if (constantypedefs
2864 && structdef == snone
2865 && structtype == st_C_enum && bracelev > structbracelev)
2866 return true; /* enum constant */
2867 switch (fvdef)
2869 case fdefunkey:
2870 if (bracelev > 0)
2871 break;
2872 fvdef = fdefunname; /* GNU macro */
2873 *is_func_or_var = true;
2874 return true;
2875 case fvnone:
2876 switch (typdef)
2878 case ttypeseen:
2879 return false;
2880 case tnone:
2881 if ((strneq (str, "asm", 3) && endtoken (str[3]))
2882 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
2884 fvdef = vignore;
2885 return false;
2887 break;
2889 /* FALLTHRU */
2890 case fvnameseen:
2891 if (len >= 10 && strneq (str+len-10, "::operator", 10))
2893 if (*c_extp & C_AUTO) /* automatic detection of C++ */
2894 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2895 fvdef = foperator;
2896 *is_func_or_var = true;
2897 return true;
2899 if (bracelev > 0 && !instruct)
2900 break;
2901 fvdef = fvnameseen; /* function or variable */
2902 *is_func_or_var = true;
2903 return true;
2905 break;
2908 return false;
2913 * C_entries often keeps pointers to tokens or lines which are older than
2914 * the line currently read. By keeping two line buffers, and switching
2915 * them at end of line, it is possible to use those pointers.
2917 static struct
2919 long linepos;
2920 linebuffer lb;
2921 } lbs[2];
2923 #define current_lb_is_new (newndx == curndx)
2924 #define switch_line_buffers() (curndx = 1 - curndx)
2926 #define curlb (lbs[curndx].lb)
2927 #define newlb (lbs[newndx].lb)
2928 #define curlinepos (lbs[curndx].linepos)
2929 #define newlinepos (lbs[newndx].linepos)
2931 #define plainc ((c_ext & C_EXT) == C_PLAIN)
2932 #define cplpl (c_ext & C_PLPL)
2933 #define cjava ((c_ext & C_JAVA) == C_JAVA)
2935 #define CNL_SAVE_DEFINEDEF() \
2936 do { \
2937 curlinepos = charno; \
2938 readline (&curlb, inf); \
2939 lp = curlb.buffer; \
2940 quotednl = false; \
2941 newndx = curndx; \
2942 } while (0)
2944 #define CNL() \
2945 do { \
2946 CNL_SAVE_DEFINEDEF(); \
2947 if (savetoken.valid) \
2949 token = savetoken; \
2950 savetoken.valid = false; \
2952 definedef = dnone; \
2953 } while (0)
2956 static void
2957 make_C_tag (bool isfun)
2959 /* This function is never called when token.valid is false, but
2960 we must protect against invalid input or internal errors. */
2961 if (token.valid)
2962 make_tag (token_name.buffer, token_name.len, isfun, token.line,
2963 token.offset+token.length+1, token.lineno, token.linepos);
2964 else if (DEBUG)
2965 { /* this branch is optimized away if !DEBUG */
2966 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
2967 token_name.len + 17, isfun, token.line,
2968 token.offset+token.length+1, token.lineno, token.linepos);
2969 error ("INVALID TOKEN");
2972 token.valid = false;
2977 * C_entries ()
2978 * This routine finds functions, variables, typedefs,
2979 * #define's, enum constants and struct/union/enum definitions in
2980 * C syntax and adds them to the list.
2982 static void
2983 C_entries (int c_ext, FILE *inf)
2984 /* extension of C */
2985 /* input file */
2987 register char c; /* latest char read; '\0' for end of line */
2988 register char *lp; /* pointer one beyond the character `c' */
2989 int curndx, newndx; /* indices for current and new lb */
2990 register int tokoff; /* offset in line of start of current token */
2991 register int toklen; /* length of current token */
2992 const char *qualifier; /* string used to qualify names */
2993 int qlen; /* length of qualifier */
2994 int bracelev; /* current brace level */
2995 int bracketlev; /* current bracket level */
2996 int parlev; /* current parenthesis level */
2997 int attrparlev; /* __attribute__ parenthesis level */
2998 int templatelev; /* current template level */
2999 int typdefbracelev; /* bracelev where a typedef struct body begun */
3000 bool incomm, inquote, inchar, quotednl, midtoken;
3001 bool yacc_rules; /* in the rules part of a yacc file */
3002 struct tok savetoken = {0}; /* token saved during preprocessor handling */
3005 linebuffer_init (&lbs[0].lb);
3006 linebuffer_init (&lbs[1].lb);
3007 if (cstack.size == 0)
3009 cstack.size = (DEBUG) ? 1 : 4;
3010 cstack.nl = 0;
3011 cstack.cname = xnew (cstack.size, char *);
3012 cstack.bracelev = xnew (cstack.size, int);
3015 tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3016 curndx = newndx = 0;
3017 lp = curlb.buffer;
3018 *lp = 0;
3020 fvdef = fvnone; fvextern = false; typdef = tnone;
3021 structdef = snone; definedef = dnone; objdef = onone;
3022 yacc_rules = false;
3023 midtoken = inquote = inchar = incomm = quotednl = false;
3024 token.valid = savetoken.valid = false;
3025 bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3026 if (cjava)
3027 { qualifier = "."; qlen = 1; }
3028 else
3029 { qualifier = "::"; qlen = 2; }
3032 while (!feof (inf))
3034 c = *lp++;
3035 if (c == '\\')
3037 /* If we are at the end of the line, the next character is a
3038 '\0'; do not skip it, because it is what tells us
3039 to read the next line. */
3040 if (*lp == '\0')
3042 quotednl = true;
3043 continue;
3045 lp++;
3046 c = ' ';
3048 else if (incomm)
3050 switch (c)
3052 case '*':
3053 if (*lp == '/')
3055 c = *lp++;
3056 incomm = false;
3058 break;
3059 case '\0':
3060 /* Newlines inside comments do not end macro definitions in
3061 traditional cpp. */
3062 CNL_SAVE_DEFINEDEF ();
3063 break;
3065 continue;
3067 else if (inquote)
3069 switch (c)
3071 case '"':
3072 inquote = false;
3073 break;
3074 case '\0':
3075 /* Newlines inside strings do not end macro definitions
3076 in traditional cpp, even though compilers don't
3077 usually accept them. */
3078 CNL_SAVE_DEFINEDEF ();
3079 break;
3081 continue;
3083 else if (inchar)
3085 switch (c)
3087 case '\0':
3088 /* Hmmm, something went wrong. */
3089 CNL ();
3090 /* FALLTHRU */
3091 case '\'':
3092 inchar = false;
3093 break;
3095 continue;
3097 else switch (c)
3099 case '"':
3100 inquote = true;
3101 if (bracketlev > 0)
3102 continue;
3103 if (inattribute)
3104 break;
3105 switch (fvdef)
3107 case fdefunkey:
3108 case fstartlist:
3109 case finlist:
3110 case fignore:
3111 case vignore:
3112 break;
3113 default:
3114 fvextern = false;
3115 fvdef = fvnone;
3117 continue;
3118 case '\'':
3119 inchar = true;
3120 if (bracketlev > 0)
3121 continue;
3122 if (inattribute)
3123 break;
3124 if (fvdef != finlist && fvdef != fignore && fvdef != vignore)
3126 fvextern = false;
3127 fvdef = fvnone;
3129 continue;
3130 case '/':
3131 if (*lp == '*')
3133 incomm = true;
3134 lp++;
3135 c = ' ';
3136 if (bracketlev > 0)
3137 continue;
3139 else if (/* cplpl && */ *lp == '/')
3141 c = '\0';
3143 break;
3144 case '%':
3145 if ((c_ext & YACC) && *lp == '%')
3147 /* Entering or exiting rules section in yacc file. */
3148 lp++;
3149 definedef = dnone; fvdef = fvnone; fvextern = false;
3150 typdef = tnone; structdef = snone;
3151 midtoken = inquote = inchar = incomm = quotednl = false;
3152 bracelev = 0;
3153 yacc_rules = !yacc_rules;
3154 continue;
3156 else
3157 break;
3158 case '#':
3159 if (definedef == dnone)
3161 char *cp;
3162 bool cpptoken = true;
3164 /* Look back on this line. If all blanks, or nonblanks
3165 followed by an end of comment, this is a preprocessor
3166 token. */
3167 for (cp = newlb.buffer; cp < lp-1; cp++)
3168 if (!iswhite (*cp))
3170 if (*cp == '*' && cp[1] == '/')
3172 cp++;
3173 cpptoken = true;
3175 else
3176 cpptoken = false;
3178 if (cpptoken)
3179 definedef = dsharpseen;
3180 } /* if (definedef == dnone) */
3181 continue;
3182 case '[':
3183 bracketlev++;
3184 continue;
3185 default:
3186 if (bracketlev > 0)
3188 if (c == ']')
3189 --bracketlev;
3190 else if (c == '\0')
3191 CNL_SAVE_DEFINEDEF ();
3192 continue;
3194 break;
3195 } /* switch (c) */
3198 /* Consider token only if some involved conditions are satisfied. */
3199 if (typdef != tignore
3200 && definedef != dignorerest
3201 && fvdef != finlist
3202 && templatelev == 0
3203 && (definedef != dnone
3204 || structdef != scolonseen)
3205 && !inattribute)
3207 if (midtoken)
3209 if (endtoken (c))
3211 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3212 /* This handles :: in the middle,
3213 but not at the beginning of an identifier.
3214 Also, space-separated :: is not recognized. */
3216 if (c_ext & C_AUTO) /* automatic detection of C++ */
3217 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3218 lp += 2;
3219 toklen += 2;
3220 c = lp[-1];
3221 goto still_in_token;
3223 else
3225 bool funorvar = false;
3227 if (yacc_rules
3228 || consider_token (newlb.buffer + tokoff, toklen, c,
3229 &c_ext, bracelev, parlev,
3230 &funorvar))
3232 if (fvdef == foperator)
3234 char *oldlp = lp;
3235 lp = skip_spaces (lp-1);
3236 if (*lp != '\0')
3237 lp += 1;
3238 while (*lp != '\0'
3239 && !iswhite (*lp) && *lp != '(')
3240 lp += 1;
3241 c = *lp++;
3242 toklen += lp - oldlp;
3244 token.named = false;
3245 if (!plainc
3246 && nestlev > 0 && definedef == dnone)
3247 /* in struct body */
3249 int len;
3250 write_classname (&token_name, qualifier);
3251 len = token_name.len;
3252 linebuffer_setlen (&token_name, len+qlen+toklen);
3253 sprintf (token_name.buffer + len, "%s%.*s",
3254 qualifier, toklen, newlb.buffer + tokoff);
3255 token.named = true;
3257 else if (objdef == ocatseen)
3258 /* Objective C category */
3260 int len = strlen (objtag) + 2 + toklen;
3261 linebuffer_setlen (&token_name, len);
3262 sprintf (token_name.buffer, "%s(%.*s)",
3263 objtag, toklen, newlb.buffer + tokoff);
3264 token.named = true;
3266 else if (objdef == omethodtag
3267 || objdef == omethodparm)
3268 /* Objective C method */
3270 token.named = true;
3272 else if (fvdef == fdefunname)
3273 /* GNU DEFUN and similar macros */
3275 bool defun = (newlb.buffer[tokoff] == 'F');
3276 int off = tokoff;
3277 int len = toklen;
3279 /* Rewrite the tag so that emacs lisp DEFUNs
3280 can be found by their elisp name */
3281 if (defun)
3283 off += 1;
3284 len -= 1;
3286 linebuffer_setlen (&token_name, len);
3287 memcpy (token_name.buffer,
3288 newlb.buffer + off, len);
3289 token_name.buffer[len] = '\0';
3290 if (defun)
3291 while (--len >= 0)
3292 if (token_name.buffer[len] == '_')
3293 token_name.buffer[len] = '-';
3294 token.named = defun;
3296 else
3298 linebuffer_setlen (&token_name, toklen);
3299 memcpy (token_name.buffer,
3300 newlb.buffer + tokoff, toklen);
3301 token_name.buffer[toklen] = '\0';
3302 /* Name macros and members. */
3303 token.named = (structdef == stagseen
3304 || typdef == ttypeseen
3305 || typdef == tend
3306 || (funorvar
3307 && definedef == dignorerest)
3308 || (funorvar
3309 && definedef == dnone
3310 && structdef == snone
3311 && bracelev > 0));
3313 token.lineno = lineno;
3314 token.offset = tokoff;
3315 token.length = toklen;
3316 token.line = newlb.buffer;
3317 token.linepos = newlinepos;
3318 token.valid = true;
3320 if (definedef == dnone
3321 && (fvdef == fvnameseen
3322 || fvdef == foperator
3323 || structdef == stagseen
3324 || typdef == tend
3325 || typdef == ttypeseen
3326 || objdef != onone))
3328 if (current_lb_is_new)
3329 switch_line_buffers ();
3331 else if (definedef != dnone
3332 || fvdef == fdefunname
3333 || instruct)
3334 make_C_tag (funorvar);
3336 else /* not yacc and consider_token failed */
3338 if (inattribute && fvdef == fignore)
3340 /* We have just met __attribute__ after a
3341 function parameter list: do not tag the
3342 function again. */
3343 fvdef = fvnone;
3346 midtoken = false;
3348 } /* if (endtoken (c)) */
3349 else if (intoken (c))
3350 still_in_token:
3352 toklen++;
3353 continue;
3355 } /* if (midtoken) */
3356 else if (begtoken (c))
3358 switch (definedef)
3360 case dnone:
3361 switch (fvdef)
3363 case fstartlist:
3364 /* This prevents tagging fb in
3365 void (__attribute__((noreturn)) *fb) (void);
3366 Fixing this is not easy and not very important. */
3367 fvdef = finlist;
3368 continue;
3369 case flistseen:
3370 if (plainc || declarations)
3372 make_C_tag (true); /* a function */
3373 fvdef = fignore;
3375 break;
3377 if (structdef == stagseen && !cjava)
3379 popclass_above (bracelev);
3380 structdef = snone;
3382 break;
3383 case dsharpseen:
3384 savetoken = token;
3385 break;
3387 if (!yacc_rules || lp == newlb.buffer + 1)
3389 tokoff = lp - 1 - newlb.buffer;
3390 toklen = 1;
3391 midtoken = true;
3393 continue;
3394 } /* if (begtoken) */
3395 } /* if must look at token */
3398 /* Detect end of line, colon, comma, semicolon and various braces
3399 after having handled a token.*/
3400 switch (c)
3402 case ':':
3403 if (inattribute)
3404 break;
3405 if (yacc_rules && token.offset == 0 && token.valid)
3407 make_C_tag (false); /* a yacc function */
3408 break;
3410 if (definedef != dnone)
3411 break;
3412 switch (objdef)
3414 case otagseen:
3415 objdef = oignore;
3416 make_C_tag (true); /* an Objective C class */
3417 break;
3418 case omethodtag:
3419 case omethodparm:
3420 objdef = omethodcolon;
3421 int toklen = token_name.len;
3422 linebuffer_setlen (&token_name, toklen + 1);
3423 strcpy (token_name.buffer + toklen, ":");
3424 break;
3426 if (structdef == stagseen)
3428 structdef = scolonseen;
3429 break;
3431 /* Should be useless, but may be work as a safety net. */
3432 if (cplpl && fvdef == flistseen)
3434 make_C_tag (true); /* a function */
3435 fvdef = fignore;
3436 break;
3438 break;
3439 case ';':
3440 if (definedef != dnone || inattribute)
3441 break;
3442 switch (typdef)
3444 case tend:
3445 case ttypeseen:
3446 make_C_tag (false); /* a typedef */
3447 typdef = tnone;
3448 fvdef = fvnone;
3449 break;
3450 case tnone:
3451 case tinbody:
3452 case tignore:
3453 switch (fvdef)
3455 case fignore:
3456 if (typdef == tignore || cplpl)
3457 fvdef = fvnone;
3458 break;
3459 case fvnameseen:
3460 if ((globals && bracelev == 0 && (!fvextern || declarations))
3461 || (members && instruct))
3462 make_C_tag (false); /* a variable */
3463 fvextern = false;
3464 fvdef = fvnone;
3465 token.valid = false;
3466 break;
3467 case flistseen:
3468 if ((declarations
3469 && (cplpl || !instruct)
3470 && (typdef == tnone || (typdef != tignore && instruct)))
3471 || (members
3472 && plainc && instruct))
3473 make_C_tag (true); /* a function */
3474 /* FALLTHRU */
3475 default:
3476 fvextern = false;
3477 fvdef = fvnone;
3478 if (declarations
3479 && cplpl && structdef == stagseen)
3480 make_C_tag (false); /* forward declaration */
3481 else
3482 token.valid = false;
3483 } /* switch (fvdef) */
3484 /* FALLTHRU */
3485 default:
3486 if (!instruct)
3487 typdef = tnone;
3489 if (structdef == stagseen)
3490 structdef = snone;
3491 break;
3492 case ',':
3493 if (definedef != dnone || inattribute)
3494 break;
3495 switch (objdef)
3497 case omethodtag:
3498 case omethodparm:
3499 make_C_tag (true); /* an Objective C method */
3500 objdef = oinbody;
3501 break;
3503 switch (fvdef)
3505 case fdefunkey:
3506 case foperator:
3507 case fstartlist:
3508 case finlist:
3509 case fignore:
3510 case vignore:
3511 break;
3512 case fdefunname:
3513 fvdef = fignore;
3514 break;
3515 case fvnameseen:
3516 if (parlev == 0
3517 && ((globals
3518 && bracelev == 0
3519 && templatelev == 0
3520 && (!fvextern || declarations))
3521 || (members && instruct)))
3522 make_C_tag (false); /* a variable */
3523 break;
3524 case flistseen:
3525 if ((declarations && typdef == tnone && !instruct)
3526 || (members && typdef != tignore && instruct))
3528 make_C_tag (true); /* a function */
3529 fvdef = fvnameseen;
3531 else if (!declarations)
3532 fvdef = fvnone;
3533 token.valid = false;
3534 break;
3535 default:
3536 fvdef = fvnone;
3538 if (structdef == stagseen)
3539 structdef = snone;
3540 break;
3541 case ']':
3542 if (definedef != dnone || inattribute)
3543 break;
3544 if (structdef == stagseen)
3545 structdef = snone;
3546 switch (typdef)
3548 case ttypeseen:
3549 case tend:
3550 typdef = tignore;
3551 make_C_tag (false); /* a typedef */
3552 break;
3553 case tnone:
3554 case tinbody:
3555 switch (fvdef)
3557 case foperator:
3558 case finlist:
3559 case fignore:
3560 case vignore:
3561 break;
3562 case fvnameseen:
3563 if ((members && bracelev == 1)
3564 || (globals && bracelev == 0
3565 && (!fvextern || declarations)))
3566 make_C_tag (false); /* a variable */
3567 /* FALLTHRU */
3568 default:
3569 fvdef = fvnone;
3571 break;
3573 break;
3574 case '(':
3575 if (inattribute)
3577 attrparlev++;
3578 break;
3580 if (definedef != dnone)
3581 break;
3582 if (objdef == otagseen && parlev == 0)
3583 objdef = oparenseen;
3584 switch (fvdef)
3586 case fvnameseen:
3587 if (typdef == ttypeseen
3588 && *lp != '*'
3589 && !instruct)
3591 /* This handles constructs like:
3592 typedef void OperatorFun (int fun); */
3593 make_C_tag (false);
3594 typdef = tignore;
3595 fvdef = fignore;
3596 break;
3598 /* FALLTHRU */
3599 case foperator:
3600 fvdef = fstartlist;
3601 break;
3602 case flistseen:
3603 fvdef = finlist;
3604 break;
3606 parlev++;
3607 break;
3608 case ')':
3609 if (inattribute)
3611 if (--attrparlev == 0)
3612 inattribute = false;
3613 break;
3615 if (definedef != dnone)
3616 break;
3617 if (objdef == ocatseen && parlev == 1)
3619 make_C_tag (true); /* an Objective C category */
3620 objdef = oignore;
3622 if (--parlev == 0)
3624 switch (fvdef)
3626 case fstartlist:
3627 case finlist:
3628 fvdef = flistseen;
3629 break;
3631 if (!instruct
3632 && (typdef == tend
3633 || typdef == ttypeseen))
3635 typdef = tignore;
3636 make_C_tag (false); /* a typedef */
3639 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
3640 parlev = 0;
3641 break;
3642 case '{':
3643 if (definedef != dnone)
3644 break;
3645 if (typdef == ttypeseen)
3647 /* Whenever typdef is set to tinbody (currently only
3648 here), typdefbracelev should be set to bracelev. */
3649 typdef = tinbody;
3650 typdefbracelev = bracelev;
3652 switch (fvdef)
3654 case flistseen:
3655 make_C_tag (true); /* a function */
3656 /* FALLTHRU */
3657 case fignore:
3658 fvdef = fvnone;
3659 break;
3660 case fvnone:
3661 switch (objdef)
3663 case otagseen:
3664 make_C_tag (true); /* an Objective C class */
3665 objdef = oignore;
3666 break;
3667 case omethodtag:
3668 case omethodparm:
3669 make_C_tag (true); /* an Objective C method */
3670 objdef = oinbody;
3671 break;
3672 default:
3673 /* Neutralize `extern "C" {' grot. */
3674 if (bracelev == 0 && structdef == snone && nestlev == 0
3675 && typdef == tnone)
3676 bracelev = -1;
3678 break;
3680 switch (structdef)
3682 case skeyseen: /* unnamed struct */
3683 pushclass_above (bracelev, NULL, 0);
3684 structdef = snone;
3685 break;
3686 case stagseen: /* named struct or enum */
3687 case scolonseen: /* a class */
3688 pushclass_above (bracelev,token.line+token.offset, token.length);
3689 structdef = snone;
3690 make_C_tag (false); /* a struct or enum */
3691 break;
3693 bracelev += 1;
3694 break;
3695 case '*':
3696 if (definedef != dnone)
3697 break;
3698 if (fvdef == fstartlist)
3700 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
3701 token.valid = false;
3703 break;
3704 case '}':
3705 if (definedef != dnone)
3706 break;
3707 bracelev -= 1;
3708 if (!ignoreindent && lp == newlb.buffer + 1)
3710 if (bracelev != 0)
3711 token.valid = false; /* unexpected value, token unreliable */
3712 bracelev = 0; /* reset brace level if first column */
3713 parlev = 0; /* also reset paren level, just in case... */
3715 else if (bracelev < 0)
3717 token.valid = false; /* something gone amiss, token unreliable */
3718 bracelev = 0;
3720 if (bracelev == 0 && fvdef == vignore)
3721 fvdef = fvnone; /* end of function */
3722 popclass_above (bracelev);
3723 structdef = snone;
3724 /* Only if typdef == tinbody is typdefbracelev significant. */
3725 if (typdef == tinbody && bracelev <= typdefbracelev)
3727 assert (bracelev == typdefbracelev);
3728 typdef = tend;
3730 break;
3731 case '=':
3732 if (definedef != dnone)
3733 break;
3734 switch (fvdef)
3736 case foperator:
3737 case finlist:
3738 case fignore:
3739 case vignore:
3740 break;
3741 case fvnameseen:
3742 if ((members && bracelev == 1)
3743 || (globals && bracelev == 0 && (!fvextern || declarations)))
3744 make_C_tag (false); /* a variable */
3745 /* FALLTHRU */
3746 default:
3747 fvdef = vignore;
3749 break;
3750 case '<':
3751 if (cplpl
3752 && (structdef == stagseen || fvdef == fvnameseen))
3754 templatelev++;
3755 break;
3757 goto resetfvdef;
3758 case '>':
3759 if (templatelev > 0)
3761 templatelev--;
3762 break;
3764 goto resetfvdef;
3765 case '+':
3766 case '-':
3767 if (objdef == oinbody && bracelev == 0)
3769 objdef = omethodsign;
3770 break;
3772 /* FALLTHRU */
3773 resetfvdef:
3774 case '#': case '~': case '&': case '%': case '/':
3775 case '|': case '^': case '!': case '.': case '?':
3776 if (definedef != dnone)
3777 break;
3778 /* These surely cannot follow a function tag in C. */
3779 switch (fvdef)
3781 case foperator:
3782 case finlist:
3783 case fignore:
3784 case vignore:
3785 break;
3786 default:
3787 fvdef = fvnone;
3789 break;
3790 case '\0':
3791 if (objdef == otagseen)
3793 make_C_tag (true); /* an Objective C class */
3794 objdef = oignore;
3796 /* If a macro spans multiple lines don't reset its state. */
3797 if (quotednl)
3798 CNL_SAVE_DEFINEDEF ();
3799 else
3800 CNL ();
3801 break;
3802 } /* switch (c) */
3804 } /* while not eof */
3806 free (lbs[0].lb.buffer);
3807 free (lbs[1].lb.buffer);
3811 * Process either a C++ file or a C file depending on the setting
3812 * of a global flag.
3814 static void
3815 default_C_entries (FILE *inf)
3817 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
3820 /* Always do plain C. */
3821 static void
3822 plain_C_entries (FILE *inf)
3824 C_entries (0, inf);
3827 /* Always do C++. */
3828 static void
3829 Cplusplus_entries (FILE *inf)
3831 C_entries (C_PLPL, inf);
3834 /* Always do Java. */
3835 static void
3836 Cjava_entries (FILE *inf)
3838 C_entries (C_JAVA, inf);
3841 /* Always do C*. */
3842 static void
3843 Cstar_entries (FILE *inf)
3845 C_entries (C_STAR, inf);
3848 /* Always do Yacc. */
3849 static void
3850 Yacc_entries (FILE *inf)
3852 C_entries (YACC, inf);
3856 /* Useful macros. */
3857 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
3858 for (; /* loop initialization */ \
3859 !feof (file_pointer) /* loop test */ \
3860 && /* instructions at start of loop */ \
3861 (readline (&line_buffer, file_pointer), \
3862 char_pointer = line_buffer.buffer, \
3863 true); \
3866 #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \
3867 ((assert ("" kw), true) /* syntax error if not a literal string */ \
3868 && strneq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3869 && notinname ((cp)[sizeof (kw)-1]) /* end of kw */ \
3870 && ((cp) = skip_spaces ((cp)+sizeof (kw)-1))) /* skip spaces */
3872 /* Similar to LOOKING_AT but does not use notinname, does not skip */
3873 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
3874 ((assert ("" kw), true) /* syntax error if not a literal string */ \
3875 && strncaseeq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3876 && ((cp) += sizeof (kw)-1)) /* skip spaces */
3879 * Read a file, but do no processing. This is used to do regexp
3880 * matching on files that have no language defined.
3882 static void
3883 just_read_file (FILE *inf)
3885 while (!feof (inf))
3886 readline (&lb, inf);
3890 /* Fortran parsing */
3892 static void F_takeprec (void);
3893 static void F_getit (FILE *);
3895 static void
3896 F_takeprec (void)
3898 dbp = skip_spaces (dbp);
3899 if (*dbp != '*')
3900 return;
3901 dbp++;
3902 dbp = skip_spaces (dbp);
3903 if (strneq (dbp, "(*)", 3))
3905 dbp += 3;
3906 return;
3908 if (!ISDIGIT (*dbp))
3910 --dbp; /* force failure */
3911 return;
3914 dbp++;
3915 while (ISDIGIT (*dbp));
3918 static void
3919 F_getit (FILE *inf)
3921 register char *cp;
3923 dbp = skip_spaces (dbp);
3924 if (*dbp == '\0')
3926 readline (&lb, inf);
3927 dbp = lb.buffer;
3928 if (dbp[5] != '&')
3929 return;
3930 dbp += 6;
3931 dbp = skip_spaces (dbp);
3933 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
3934 return;
3935 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
3936 continue;
3937 make_tag (dbp, cp-dbp, true,
3938 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
3942 static void
3943 Fortran_functions (FILE *inf)
3945 LOOP_ON_INPUT_LINES (inf, lb, dbp)
3947 if (*dbp == '%')
3948 dbp++; /* Ratfor escape to fortran */
3949 dbp = skip_spaces (dbp);
3950 if (*dbp == '\0')
3951 continue;
3953 if (LOOKING_AT_NOCASE (dbp, "recursive"))
3954 dbp = skip_spaces (dbp);
3956 if (LOOKING_AT_NOCASE (dbp, "pure"))
3957 dbp = skip_spaces (dbp);
3959 if (LOOKING_AT_NOCASE (dbp, "elemental"))
3960 dbp = skip_spaces (dbp);
3962 switch (lowcase (*dbp))
3964 case 'i':
3965 if (nocase_tail ("integer"))
3966 F_takeprec ();
3967 break;
3968 case 'r':
3969 if (nocase_tail ("real"))
3970 F_takeprec ();
3971 break;
3972 case 'l':
3973 if (nocase_tail ("logical"))
3974 F_takeprec ();
3975 break;
3976 case 'c':
3977 if (nocase_tail ("complex") || nocase_tail ("character"))
3978 F_takeprec ();
3979 break;
3980 case 'd':
3981 if (nocase_tail ("double"))
3983 dbp = skip_spaces (dbp);
3984 if (*dbp == '\0')
3985 continue;
3986 if (nocase_tail ("precision"))
3987 break;
3988 continue;
3990 break;
3992 dbp = skip_spaces (dbp);
3993 if (*dbp == '\0')
3994 continue;
3995 switch (lowcase (*dbp))
3997 case 'f':
3998 if (nocase_tail ("function"))
3999 F_getit (inf);
4000 continue;
4001 case 's':
4002 if (nocase_tail ("subroutine"))
4003 F_getit (inf);
4004 continue;
4005 case 'e':
4006 if (nocase_tail ("entry"))
4007 F_getit (inf);
4008 continue;
4009 case 'b':
4010 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4012 dbp = skip_spaces (dbp);
4013 if (*dbp == '\0') /* assume un-named */
4014 make_tag ("blockdata", 9, true,
4015 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4016 else
4017 F_getit (inf); /* look for name */
4019 continue;
4026 * Ada parsing
4027 * Original code by
4028 * Philippe Waroquiers (1998)
4031 /* Once we are positioned after an "interesting" keyword, let's get
4032 the real tag value necessary. */
4033 static void
4034 Ada_getit (FILE *inf, const char *name_qualifier)
4036 register char *cp;
4037 char *name;
4038 char c;
4040 while (!feof (inf))
4042 dbp = skip_spaces (dbp);
4043 if (*dbp == '\0'
4044 || (dbp[0] == '-' && dbp[1] == '-'))
4046 readline (&lb, inf);
4047 dbp = lb.buffer;
4049 switch (lowcase (*dbp))
4051 case 'b':
4052 if (nocase_tail ("body"))
4054 /* Skipping body of procedure body or package body or ....
4055 resetting qualifier to body instead of spec. */
4056 name_qualifier = "/b";
4057 continue;
4059 break;
4060 case 't':
4061 /* Skipping type of task type or protected type ... */
4062 if (nocase_tail ("type"))
4063 continue;
4064 break;
4066 if (*dbp == '"')
4068 dbp += 1;
4069 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4070 continue;
4072 else
4074 dbp = skip_spaces (dbp);
4075 for (cp = dbp;
4076 (*cp != '\0'
4077 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4078 cp++)
4079 continue;
4080 if (cp == dbp)
4081 return;
4083 c = *cp;
4084 *cp = '\0';
4085 name = concat (dbp, name_qualifier, "");
4086 *cp = c;
4087 make_tag (name, strlen (name), true,
4088 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4089 free (name);
4090 if (c == '"')
4091 dbp = cp + 1;
4092 return;
4096 static void
4097 Ada_funcs (FILE *inf)
4099 bool inquote = false;
4100 bool skip_till_semicolumn = false;
4102 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4104 while (*dbp != '\0')
4106 /* Skip a string i.e. "abcd". */
4107 if (inquote || (*dbp == '"'))
4109 dbp = strchr (dbp + !inquote, '"');
4110 if (dbp != NULL)
4112 inquote = false;
4113 dbp += 1;
4114 continue; /* advance char */
4116 else
4118 inquote = true;
4119 break; /* advance line */
4123 /* Skip comments. */
4124 if (dbp[0] == '-' && dbp[1] == '-')
4125 break; /* advance line */
4127 /* Skip character enclosed in single quote i.e. 'a'
4128 and skip single quote starting an attribute i.e. 'Image. */
4129 if (*dbp == '\'')
4131 dbp++ ;
4132 if (*dbp != '\0')
4133 dbp++;
4134 continue;
4137 if (skip_till_semicolumn)
4139 if (*dbp == ';')
4140 skip_till_semicolumn = false;
4141 dbp++;
4142 continue; /* advance char */
4145 /* Search for beginning of a token. */
4146 if (!begtoken (*dbp))
4148 dbp++;
4149 continue; /* advance char */
4152 /* We are at the beginning of a token. */
4153 switch (lowcase (*dbp))
4155 case 'f':
4156 if (!packages_only && nocase_tail ("function"))
4157 Ada_getit (inf, "/f");
4158 else
4159 break; /* from switch */
4160 continue; /* advance char */
4161 case 'p':
4162 if (!packages_only && nocase_tail ("procedure"))
4163 Ada_getit (inf, "/p");
4164 else if (nocase_tail ("package"))
4165 Ada_getit (inf, "/s");
4166 else if (nocase_tail ("protected")) /* protected type */
4167 Ada_getit (inf, "/t");
4168 else
4169 break; /* from switch */
4170 continue; /* advance char */
4172 case 'u':
4173 if (typedefs && !packages_only && nocase_tail ("use"))
4175 /* when tagging types, avoid tagging use type Pack.Typename;
4176 for this, we will skip everything till a ; */
4177 skip_till_semicolumn = true;
4178 continue; /* advance char */
4181 case 't':
4182 if (!packages_only && nocase_tail ("task"))
4183 Ada_getit (inf, "/k");
4184 else if (typedefs && !packages_only && nocase_tail ("type"))
4186 Ada_getit (inf, "/t");
4187 while (*dbp != '\0')
4188 dbp += 1;
4190 else
4191 break; /* from switch */
4192 continue; /* advance char */
4195 /* Look for the end of the token. */
4196 while (!endtoken (*dbp))
4197 dbp++;
4199 } /* advance char */
4200 } /* advance line */
4205 * Unix and microcontroller assembly tag handling
4206 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4207 * Idea by Bob Weiner, Motorola Inc. (1994)
4209 static void
4210 Asm_labels (FILE *inf)
4212 register char *cp;
4214 LOOP_ON_INPUT_LINES (inf, lb, cp)
4216 /* If first char is alphabetic or one of [_.$], test for colon
4217 following identifier. */
4218 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4220 /* Read past label. */
4221 cp++;
4222 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4223 cp++;
4224 if (*cp == ':' || iswhite (*cp))
4225 /* Found end of label, so copy it and add it to the table. */
4226 make_tag (lb.buffer, cp - lb.buffer, true,
4227 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4234 * Perl support
4235 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4236 * /^use constant[ \t\n]+[^ \t\n{=,;]+/
4237 * Perl variable names: /^(my|local).../
4238 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4239 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4240 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4242 static void
4243 Perl_functions (FILE *inf)
4245 char *package = savestr ("main"); /* current package name */
4246 register char *cp;
4248 LOOP_ON_INPUT_LINES (inf, lb, cp)
4250 cp = skip_spaces (cp);
4252 if (LOOKING_AT (cp, "package"))
4254 free (package);
4255 get_tag (cp, &package);
4257 else if (LOOKING_AT (cp, "sub"))
4259 char *pos, *sp;
4261 subr:
4262 sp = cp;
4263 while (!notinname (*cp))
4264 cp++;
4265 if (cp == sp)
4266 continue; /* nothing found */
4267 if ((pos = strchr (sp, ':')) != NULL
4268 && pos < cp && pos[1] == ':')
4269 /* The name is already qualified. */
4270 make_tag (sp, cp - sp, true,
4271 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4272 else
4273 /* Qualify it. */
4275 char savechar, *name;
4277 savechar = *cp;
4278 *cp = '\0';
4279 name = concat (package, "::", sp);
4280 *cp = savechar;
4281 make_tag (name, strlen (name), true,
4282 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4283 free (name);
4286 else if (LOOKING_AT (cp, "use constant")
4287 || LOOKING_AT (cp, "use constant::defer"))
4289 /* For hash style multi-constant like
4290 use constant { FOO => 123,
4291 BAR => 456 };
4292 only the first FOO is picked up. Parsing across the value
4293 expressions would be difficult in general, due to possible nested
4294 hashes, here-documents, etc. */
4295 if (*cp == '{')
4296 cp = skip_spaces (cp+1);
4297 goto subr;
4299 else if (globals) /* only if we are tagging global vars */
4301 /* Skip a qualifier, if any. */
4302 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4303 /* After "my" or "local", but before any following paren or space. */
4304 char *varstart = cp;
4306 if (qual /* should this be removed? If yes, how? */
4307 && (*cp == '$' || *cp == '@' || *cp == '%'))
4309 varstart += 1;
4311 cp++;
4312 while (ISALNUM (*cp) || *cp == '_');
4314 else if (qual)
4316 /* Should be examining a variable list at this point;
4317 could insist on seeing an open parenthesis. */
4318 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4319 cp++;
4321 else
4322 continue;
4324 make_tag (varstart, cp - varstart, false,
4325 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4328 free (package);
4333 * Python support
4334 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4335 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4336 * More ideas by seb bacon <seb@jamkit.com> (2002)
4338 static void
4339 Python_functions (FILE *inf)
4341 register char *cp;
4343 LOOP_ON_INPUT_LINES (inf, lb, cp)
4345 cp = skip_spaces (cp);
4346 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4348 char *name = cp;
4349 while (!notinname (*cp) && *cp != ':')
4350 cp++;
4351 make_tag (name, cp - name, true,
4352 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4359 * PHP support
4360 * Look for:
4361 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4362 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4363 * - /^[ \t]*define\(\"[^\"]+/
4364 * Only with --members:
4365 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4366 * Idea by Diez B. Roggisch (2001)
4368 static void
4369 PHP_functions (FILE *inf)
4371 char *cp, *name;
4372 bool search_identifier = false;
4374 LOOP_ON_INPUT_LINES (inf, lb, cp)
4376 cp = skip_spaces (cp);
4377 name = cp;
4378 if (search_identifier
4379 && *cp != '\0')
4381 while (!notinname (*cp))
4382 cp++;
4383 make_tag (name, cp - name, true,
4384 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4385 search_identifier = false;
4387 else if (LOOKING_AT (cp, "function"))
4389 if (*cp == '&')
4390 cp = skip_spaces (cp+1);
4391 if (*cp != '\0')
4393 name = cp;
4394 while (!notinname (*cp))
4395 cp++;
4396 make_tag (name, cp - name, true,
4397 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4399 else
4400 search_identifier = true;
4402 else if (LOOKING_AT (cp, "class"))
4404 if (*cp != '\0')
4406 name = cp;
4407 while (*cp != '\0' && !iswhite (*cp))
4408 cp++;
4409 make_tag (name, cp - name, false,
4410 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4412 else
4413 search_identifier = true;
4415 else if (strneq (cp, "define", 6)
4416 && (cp = skip_spaces (cp+6))
4417 && *cp++ == '('
4418 && (*cp == '"' || *cp == '\''))
4420 char quote = *cp++;
4421 name = cp;
4422 while (*cp != quote && *cp != '\0')
4423 cp++;
4424 make_tag (name, cp - name, false,
4425 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4427 else if (members
4428 && LOOKING_AT (cp, "var")
4429 && *cp == '$')
4431 name = cp;
4432 while (!notinname (*cp))
4433 cp++;
4434 make_tag (name, cp - name, false,
4435 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4442 * Cobol tag functions
4443 * We could look for anything that could be a paragraph name.
4444 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4445 * Idea by Corny de Souza (1993)
4447 static void
4448 Cobol_paragraphs (FILE *inf)
4450 register char *bp, *ep;
4452 LOOP_ON_INPUT_LINES (inf, lb, bp)
4454 if (lb.len < 9)
4455 continue;
4456 bp += 8;
4458 /* If eoln, compiler option or comment ignore whole line. */
4459 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4460 continue;
4462 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4463 continue;
4464 if (*ep++ == '.')
4465 make_tag (bp, ep - bp, true,
4466 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4472 * Makefile support
4473 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4475 static void
4476 Makefile_targets (FILE *inf)
4478 register char *bp;
4480 LOOP_ON_INPUT_LINES (inf, lb, bp)
4482 if (*bp == '\t' || *bp == '#')
4483 continue;
4484 while (*bp != '\0' && *bp != '=' && *bp != ':')
4485 bp++;
4486 if (*bp == ':' || (globals && *bp == '='))
4488 /* We should detect if there is more than one tag, but we do not.
4489 We just skip initial and final spaces. */
4490 char * namestart = skip_spaces (lb.buffer);
4491 while (--bp > namestart)
4492 if (!notinname (*bp))
4493 break;
4494 make_tag (namestart, bp - namestart + 1, true,
4495 lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4502 * Pascal parsing
4503 * Original code by Mosur K. Mohan (1989)
4505 * Locates tags for procedures & functions. Doesn't do any type- or
4506 * var-definitions. It does look for the keyword "extern" or
4507 * "forward" immediately following the procedure statement; if found,
4508 * the tag is skipped.
4510 static void
4511 Pascal_functions (FILE *inf)
4513 linebuffer tline; /* mostly copied from C_entries */
4514 long save_lcno;
4515 int save_lineno, namelen, taglen;
4516 char c, *name;
4518 bool /* each of these flags is true if: */
4519 incomment, /* point is inside a comment */
4520 inquote, /* point is inside '..' string */
4521 get_tagname, /* point is after PROCEDURE/FUNCTION
4522 keyword, so next item = potential tag */
4523 found_tag, /* point is after a potential tag */
4524 inparms, /* point is within parameter-list */
4525 verify_tag; /* point has passed the parm-list, so the
4526 next token will determine whether this
4527 is a FORWARD/EXTERN to be ignored, or
4528 whether it is a real tag */
4530 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4531 name = NULL; /* keep compiler quiet */
4532 dbp = lb.buffer;
4533 *dbp = '\0';
4534 linebuffer_init (&tline);
4536 incomment = inquote = false;
4537 found_tag = false; /* have a proc name; check if extern */
4538 get_tagname = false; /* found "procedure" keyword */
4539 inparms = false; /* found '(' after "proc" */
4540 verify_tag = false; /* check if "extern" is ahead */
4543 while (!feof (inf)) /* long main loop to get next char */
4545 c = *dbp++;
4546 if (c == '\0') /* if end of line */
4548 readline (&lb, inf);
4549 dbp = lb.buffer;
4550 if (*dbp == '\0')
4551 continue;
4552 if (!((found_tag && verify_tag)
4553 || get_tagname))
4554 c = *dbp++; /* only if don't need *dbp pointing
4555 to the beginning of the name of
4556 the procedure or function */
4558 if (incomment)
4560 if (c == '}') /* within { } comments */
4561 incomment = false;
4562 else if (c == '*' && *dbp == ')') /* within (* *) comments */
4564 dbp++;
4565 incomment = false;
4567 continue;
4569 else if (inquote)
4571 if (c == '\'')
4572 inquote = false;
4573 continue;
4575 else
4576 switch (c)
4578 case '\'':
4579 inquote = true; /* found first quote */
4580 continue;
4581 case '{': /* found open { comment */
4582 incomment = true;
4583 continue;
4584 case '(':
4585 if (*dbp == '*') /* found open (* comment */
4587 incomment = true;
4588 dbp++;
4590 else if (found_tag) /* found '(' after tag, i.e., parm-list */
4591 inparms = true;
4592 continue;
4593 case ')': /* end of parms list */
4594 if (inparms)
4595 inparms = false;
4596 continue;
4597 case ';':
4598 if (found_tag && !inparms) /* end of proc or fn stmt */
4600 verify_tag = true;
4601 break;
4603 continue;
4605 if (found_tag && verify_tag && (*dbp != ' '))
4607 /* Check if this is an "extern" declaration. */
4608 if (*dbp == '\0')
4609 continue;
4610 if (lowcase (*dbp) == 'e')
4612 if (nocase_tail ("extern")) /* superfluous, really! */
4614 found_tag = false;
4615 verify_tag = false;
4618 else if (lowcase (*dbp) == 'f')
4620 if (nocase_tail ("forward")) /* check for forward reference */
4622 found_tag = false;
4623 verify_tag = false;
4626 if (found_tag && verify_tag) /* not external proc, so make tag */
4628 found_tag = false;
4629 verify_tag = false;
4630 make_tag (name, namelen, true,
4631 tline.buffer, taglen, save_lineno, save_lcno);
4632 continue;
4635 if (get_tagname) /* grab name of proc or fn */
4637 char *cp;
4639 if (*dbp == '\0')
4640 continue;
4642 /* Find block name. */
4643 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
4644 continue;
4646 /* Save all values for later tagging. */
4647 linebuffer_setlen (&tline, lb.len);
4648 strcpy (tline.buffer, lb.buffer);
4649 save_lineno = lineno;
4650 save_lcno = linecharno;
4651 name = tline.buffer + (dbp - lb.buffer);
4652 namelen = cp - dbp;
4653 taglen = cp - lb.buffer + 1;
4655 dbp = cp; /* set dbp to e-o-token */
4656 get_tagname = false;
4657 found_tag = true;
4658 continue;
4660 /* And proceed to check for "extern". */
4662 else if (!incomment && !inquote && !found_tag)
4664 /* Check for proc/fn keywords. */
4665 switch (lowcase (c))
4667 case 'p':
4668 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
4669 get_tagname = true;
4670 continue;
4671 case 'f':
4672 if (nocase_tail ("unction"))
4673 get_tagname = true;
4674 continue;
4677 } /* while not eof */
4679 free (tline.buffer);
4684 * Lisp tag functions
4685 * look for (def or (DEF, quote or QUOTE
4688 static void L_getit (void);
4690 static void
4691 L_getit (void)
4693 if (*dbp == '\'') /* Skip prefix quote */
4694 dbp++;
4695 else if (*dbp == '(')
4697 dbp++;
4698 /* Try to skip "(quote " */
4699 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
4700 /* Ok, then skip "(" before name in (defstruct (foo)) */
4701 dbp = skip_spaces (dbp);
4703 get_tag (dbp, NULL);
4706 static void
4707 Lisp_functions (FILE *inf)
4709 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4711 if (dbp[0] != '(')
4712 continue;
4714 /* "(defvar foo)" is a declaration rather than a definition. */
4715 if (! declarations)
4717 char *p = dbp + 1;
4718 if (LOOKING_AT (p, "defvar"))
4720 p = skip_name (p); /* past var name */
4721 p = skip_spaces (p);
4722 if (*p == ')')
4723 continue;
4727 if (strneq (dbp + 1, "cl-", 3) || strneq (dbp + 1, "CL-", 3))
4728 dbp += 3;
4730 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
4732 dbp = skip_non_spaces (dbp);
4733 dbp = skip_spaces (dbp);
4734 L_getit ();
4736 else
4738 /* Check for (foo::defmumble name-defined ... */
4740 dbp++;
4741 while (!notinname (*dbp) && *dbp != ':');
4742 if (*dbp == ':')
4745 dbp++;
4746 while (*dbp == ':');
4748 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
4750 dbp = skip_non_spaces (dbp);
4751 dbp = skip_spaces (dbp);
4752 L_getit ();
4761 * Lua script language parsing
4762 * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
4764 * "function" and "local function" are tags if they start at column 1.
4766 static void
4767 Lua_functions (FILE *inf)
4769 register char *bp;
4771 LOOP_ON_INPUT_LINES (inf, lb, bp)
4773 if (bp[0] != 'f' && bp[0] != 'l')
4774 continue;
4776 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
4778 if (LOOKING_AT (bp, "function"))
4779 get_tag (bp, NULL);
4785 * PostScript tags
4786 * Just look for lines where the first character is '/'
4787 * Also look at "defineps" for PSWrap
4788 * Ideas by:
4789 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
4790 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
4792 static void
4793 PS_functions (FILE *inf)
4795 register char *bp, *ep;
4797 LOOP_ON_INPUT_LINES (inf, lb, bp)
4799 if (bp[0] == '/')
4801 for (ep = bp+1;
4802 *ep != '\0' && *ep != ' ' && *ep != '{';
4803 ep++)
4804 continue;
4805 make_tag (bp, ep - bp, true,
4806 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4808 else if (LOOKING_AT (bp, "defineps"))
4809 get_tag (bp, NULL);
4815 * Forth tags
4816 * Ignore anything after \ followed by space or in ( )
4817 * Look for words defined by :
4818 * Look for constant, code, create, defer, value, and variable
4819 * OBP extensions: Look for buffer:, field,
4820 * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
4822 static void
4823 Forth_words (FILE *inf)
4825 register char *bp;
4827 LOOP_ON_INPUT_LINES (inf, lb, bp)
4828 while ((bp = skip_spaces (bp))[0] != '\0')
4829 if (bp[0] == '\\' && iswhite (bp[1]))
4830 break; /* read next line */
4831 else if (bp[0] == '(' && iswhite (bp[1]))
4832 do /* skip to ) or eol */
4833 bp++;
4834 while (*bp != ')' && *bp != '\0');
4835 else if ((bp[0] == ':' && iswhite (bp[1]) && bp++)
4836 || LOOKING_AT_NOCASE (bp, "constant")
4837 || LOOKING_AT_NOCASE (bp, "code")
4838 || LOOKING_AT_NOCASE (bp, "create")
4839 || LOOKING_AT_NOCASE (bp, "defer")
4840 || LOOKING_AT_NOCASE (bp, "value")
4841 || LOOKING_AT_NOCASE (bp, "variable")
4842 || LOOKING_AT_NOCASE (bp, "buffer:")
4843 || LOOKING_AT_NOCASE (bp, "field"))
4844 get_tag (skip_spaces (bp), NULL); /* Yay! A definition! */
4845 else
4846 bp = skip_non_spaces (bp);
4851 * Scheme tag functions
4852 * look for (def... xyzzy
4853 * (def... (xyzzy
4854 * (def ... ((...(xyzzy ....
4855 * (set! xyzzy
4856 * Original code by Ken Haase (1985?)
4858 static void
4859 Scheme_functions (FILE *inf)
4861 register char *bp;
4863 LOOP_ON_INPUT_LINES (inf, lb, bp)
4865 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
4867 bp = skip_non_spaces (bp+4);
4868 /* Skip over open parens and white space. Don't continue past
4869 '\0'. */
4870 while (*bp && notinname (*bp))
4871 bp++;
4872 get_tag (bp, NULL);
4874 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
4875 get_tag (bp, NULL);
4880 /* Find tags in TeX and LaTeX input files. */
4882 /* TEX_toktab is a table of TeX control sequences that define tags.
4883 * Each entry records one such control sequence.
4885 * Original code from who knows whom.
4886 * Ideas by:
4887 * Stefan Monnier (2002)
4890 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
4892 /* Default set of control sequences to put into TEX_toktab.
4893 The value of environment var TEXTAGS is prepended to this. */
4894 static const char *TEX_defenv = "\
4895 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
4896 :part:appendix:entry:index:def\
4897 :newcommand:renewcommand:newenvironment:renewenvironment";
4899 static void TEX_mode (FILE *);
4900 static void TEX_decode_env (const char *, const char *);
4902 static char TEX_esc = '\\';
4903 static char TEX_opgrp = '{';
4904 static char TEX_clgrp = '}';
4907 * TeX/LaTeX scanning loop.
4909 static void
4910 TeX_commands (FILE *inf)
4912 char *cp;
4913 linebuffer *key;
4915 /* Select either \ or ! as escape character. */
4916 TEX_mode (inf);
4918 /* Initialize token table once from environment. */
4919 if (TEX_toktab == NULL)
4920 TEX_decode_env ("TEXTAGS", TEX_defenv);
4922 LOOP_ON_INPUT_LINES (inf, lb, cp)
4924 /* Look at each TEX keyword in line. */
4925 for (;;)
4927 /* Look for a TEX escape. */
4928 while (*cp++ != TEX_esc)
4929 if (cp[-1] == '\0' || cp[-1] == '%')
4930 goto tex_next_line;
4932 for (key = TEX_toktab; key->buffer != NULL; key++)
4933 if (strneq (cp, key->buffer, key->len))
4935 char *p;
4936 int namelen, linelen;
4937 bool opgrp = false;
4939 cp = skip_spaces (cp + key->len);
4940 if (*cp == TEX_opgrp)
4942 opgrp = true;
4943 cp++;
4945 for (p = cp;
4946 (!iswhite (*p) && *p != '#' &&
4947 *p != TEX_opgrp && *p != TEX_clgrp);
4948 p++)
4949 continue;
4950 namelen = p - cp;
4951 linelen = lb.len;
4952 if (!opgrp || *p == TEX_clgrp)
4954 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
4955 p++;
4956 linelen = p - lb.buffer + 1;
4958 make_tag (cp, namelen, true,
4959 lb.buffer, linelen, lineno, linecharno);
4960 goto tex_next_line; /* We only tag a line once */
4963 tex_next_line:
4968 #define TEX_LESC '\\'
4969 #define TEX_SESC '!'
4971 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
4972 chars accordingly. */
4973 static void
4974 TEX_mode (FILE *inf)
4976 int c;
4978 while ((c = getc (inf)) != EOF)
4980 /* Skip to next line if we hit the TeX comment char. */
4981 if (c == '%')
4982 while (c != '\n' && c != EOF)
4983 c = getc (inf);
4984 else if (c == TEX_LESC || c == TEX_SESC )
4985 break;
4988 if (c == TEX_LESC)
4990 TEX_esc = TEX_LESC;
4991 TEX_opgrp = '{';
4992 TEX_clgrp = '}';
4994 else
4996 TEX_esc = TEX_SESC;
4997 TEX_opgrp = '<';
4998 TEX_clgrp = '>';
5000 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5001 No attempt is made to correct the situation. */
5002 rewind (inf);
5005 /* Read environment and prepend it to the default string.
5006 Build token table. */
5007 static void
5008 TEX_decode_env (const char *evarname, const char *defenv)
5010 register const char *env, *p;
5011 int i, len;
5013 /* Append default string to environment. */
5014 env = getenv (evarname);
5015 if (!env)
5016 env = defenv;
5017 else
5018 env = concat (env, defenv, "");
5020 /* Allocate a token table */
5021 for (len = 1, p = env; p;)
5022 if ((p = strchr (p, ':')) && *++p != '\0')
5023 len++;
5024 TEX_toktab = xnew (len, linebuffer);
5026 /* Unpack environment string into token table. Be careful about */
5027 /* zero-length strings (leading ':', "::" and trailing ':') */
5028 for (i = 0; *env != '\0';)
5030 p = strchr (env, ':');
5031 if (!p) /* End of environment string. */
5032 p = env + strlen (env);
5033 if (p - env > 0)
5034 { /* Only non-zero strings. */
5035 TEX_toktab[i].buffer = savenstr (env, p - env);
5036 TEX_toktab[i].len = p - env;
5037 i++;
5039 if (*p)
5040 env = p + 1;
5041 else
5043 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5044 TEX_toktab[i].len = 0;
5045 break;
5051 /* Texinfo support. Dave Love, Mar. 2000. */
5052 static void
5053 Texinfo_nodes (FILE *inf)
5055 char *cp, *start;
5056 LOOP_ON_INPUT_LINES (inf, lb, cp)
5057 if (LOOKING_AT (cp, "@node"))
5059 start = cp;
5060 while (*cp != '\0' && *cp != ',')
5061 cp++;
5062 make_tag (start, cp - start, true,
5063 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5069 * HTML support.
5070 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5071 * Contents of <a name=xxx> are tags with name xxx.
5073 * Francesco Potortì, 2002.
5075 static void
5076 HTML_labels (FILE *inf)
5078 bool getnext = false; /* next text outside of HTML tags is a tag */
5079 bool skiptag = false; /* skip to the end of the current HTML tag */
5080 bool intag = false; /* inside an html tag, looking for ID= */
5081 bool inanchor = false; /* when INTAG, is an anchor, look for NAME= */
5082 char *end;
5085 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5087 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5088 for (;;) /* loop on the same line */
5090 if (skiptag) /* skip HTML tag */
5092 while (*dbp != '\0' && *dbp != '>')
5093 dbp++;
5094 if (*dbp == '>')
5096 dbp += 1;
5097 skiptag = false;
5098 continue; /* look on the same line */
5100 break; /* go to next line */
5103 else if (intag) /* look for "name=" or "id=" */
5105 while (*dbp != '\0' && *dbp != '>'
5106 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5107 dbp++;
5108 if (*dbp == '\0')
5109 break; /* go to next line */
5110 if (*dbp == '>')
5112 dbp += 1;
5113 intag = false;
5114 continue; /* look on the same line */
5116 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5117 || LOOKING_AT_NOCASE (dbp, "id="))
5119 bool quoted = (dbp[0] == '"');
5121 if (quoted)
5122 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5123 continue;
5124 else
5125 for (end = dbp; *end != '\0' && intoken (*end); end++)
5126 continue;
5127 linebuffer_setlen (&token_name, end - dbp);
5128 memcpy (token_name.buffer, dbp, end - dbp);
5129 token_name.buffer[end - dbp] = '\0';
5131 dbp = end;
5132 intag = false; /* we found what we looked for */
5133 skiptag = true; /* skip to the end of the tag */
5134 getnext = true; /* then grab the text */
5135 continue; /* look on the same line */
5137 dbp += 1;
5140 else if (getnext) /* grab next tokens and tag them */
5142 dbp = skip_spaces (dbp);
5143 if (*dbp == '\0')
5144 break; /* go to next line */
5145 if (*dbp == '<')
5147 intag = true;
5148 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5149 continue; /* look on the same line */
5152 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5153 continue;
5154 make_tag (token_name.buffer, token_name.len, true,
5155 dbp, end - dbp, lineno, linecharno);
5156 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5157 getnext = false;
5158 break; /* go to next line */
5161 else /* look for an interesting HTML tag */
5163 while (*dbp != '\0' && *dbp != '<')
5164 dbp++;
5165 if (*dbp == '\0')
5166 break; /* go to next line */
5167 intag = true;
5168 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5170 inanchor = true;
5171 continue; /* look on the same line */
5173 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5174 || LOOKING_AT_NOCASE (dbp, "<h1>")
5175 || LOOKING_AT_NOCASE (dbp, "<h2>")
5176 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5178 intag = false;
5179 getnext = true;
5180 continue; /* look on the same line */
5182 dbp += 1;
5189 * Prolog support
5191 * Assumes that the predicate or rule starts at column 0.
5192 * Only the first clause of a predicate or rule is added.
5193 * Original code by Sunichirou Sugou (1989)
5194 * Rewritten by Anders Lindgren (1996)
5196 static size_t prolog_pr (char *, char *);
5197 static void prolog_skip_comment (linebuffer *, FILE *);
5198 static size_t prolog_atom (char *, size_t);
5200 static void
5201 Prolog_functions (FILE *inf)
5203 char *cp, *last;
5204 size_t len;
5205 size_t allocated;
5207 allocated = 0;
5208 len = 0;
5209 last = NULL;
5211 LOOP_ON_INPUT_LINES (inf, lb, cp)
5213 if (cp[0] == '\0') /* Empty line */
5214 continue;
5215 else if (iswhite (cp[0])) /* Not a predicate */
5216 continue;
5217 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5218 prolog_skip_comment (&lb, inf);
5219 else if ((len = prolog_pr (cp, last)) > 0)
5221 /* Predicate or rule. Store the function name so that we
5222 only generate a tag for the first clause. */
5223 if (last == NULL)
5224 last = xnew (len + 1, char);
5225 else if (len + 1 > allocated)
5226 xrnew (last, len + 1, char);
5227 allocated = len + 1;
5228 memcpy (last, cp, len);
5229 last[len] = '\0';
5232 free (last);
5236 static void
5237 prolog_skip_comment (linebuffer *plb, FILE *inf)
5239 char *cp;
5243 for (cp = plb->buffer; *cp != '\0'; cp++)
5244 if (cp[0] == '*' && cp[1] == '/')
5245 return;
5246 readline (plb, inf);
5248 while (!feof (inf));
5252 * A predicate or rule definition is added if it matches:
5253 * <beginning of line><Prolog Atom><whitespace>(
5254 * or <beginning of line><Prolog Atom><whitespace>:-
5256 * It is added to the tags database if it doesn't match the
5257 * name of the previous clause header.
5259 * Return the size of the name of the predicate or rule, or 0 if no
5260 * header was found.
5262 static size_t
5263 prolog_pr (char *s, char *last)
5265 /* Name of last clause. */
5267 size_t pos;
5268 size_t len;
5270 pos = prolog_atom (s, 0);
5271 if (! pos)
5272 return 0;
5274 len = pos;
5275 pos = skip_spaces (s + pos) - s;
5277 if ((s[pos] == '.'
5278 || (s[pos] == '(' && (pos += 1))
5279 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5280 && (last == NULL /* save only the first clause */
5281 || len != strlen (last)
5282 || !strneq (s, last, len)))
5284 make_tag (s, len, true, s, pos, lineno, linecharno);
5285 return len;
5287 else
5288 return 0;
5292 * Consume a Prolog atom.
5293 * Return the number of bytes consumed, or 0 if there was an error.
5295 * A prolog atom, in this context, could be one of:
5296 * - An alphanumeric sequence, starting with a lower case letter.
5297 * - A quoted arbitrary string. Single quotes can escape themselves.
5298 * Backslash quotes everything.
5300 static size_t
5301 prolog_atom (char *s, size_t pos)
5303 size_t origpos;
5305 origpos = pos;
5307 if (ISLOWER (s[pos]) || (s[pos] == '_'))
5309 /* The atom is unquoted. */
5310 pos++;
5311 while (ISALNUM (s[pos]) || (s[pos] == '_'))
5313 pos++;
5315 return pos - origpos;
5317 else if (s[pos] == '\'')
5319 pos++;
5321 for (;;)
5323 if (s[pos] == '\'')
5325 pos++;
5326 if (s[pos] != '\'')
5327 break;
5328 pos++; /* A double quote */
5330 else if (s[pos] == '\0')
5331 /* Multiline quoted atoms are ignored. */
5332 return 0;
5333 else if (s[pos] == '\\')
5335 if (s[pos+1] == '\0')
5336 return 0;
5337 pos += 2;
5339 else
5340 pos++;
5342 return pos - origpos;
5344 else
5345 return 0;
5350 * Support for Erlang
5352 * Generates tags for functions, defines, and records.
5353 * Assumes that Erlang functions start at column 0.
5354 * Original code by Anders Lindgren (1996)
5356 static int erlang_func (char *, char *);
5357 static void erlang_attribute (char *);
5358 static int erlang_atom (char *);
5360 static void
5361 Erlang_functions (FILE *inf)
5363 char *cp, *last;
5364 int len;
5365 int allocated;
5367 allocated = 0;
5368 len = 0;
5369 last = NULL;
5371 LOOP_ON_INPUT_LINES (inf, lb, cp)
5373 if (cp[0] == '\0') /* Empty line */
5374 continue;
5375 else if (iswhite (cp[0])) /* Not function nor attribute */
5376 continue;
5377 else if (cp[0] == '%') /* comment */
5378 continue;
5379 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5380 continue;
5381 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5383 erlang_attribute (cp);
5384 if (last != NULL)
5386 free (last);
5387 last = NULL;
5390 else if ((len = erlang_func (cp, last)) > 0)
5393 * Function. Store the function name so that we only
5394 * generates a tag for the first clause.
5396 if (last == NULL)
5397 last = xnew (len + 1, char);
5398 else if (len + 1 > allocated)
5399 xrnew (last, len + 1, char);
5400 allocated = len + 1;
5401 memcpy (last, cp, len);
5402 last[len] = '\0';
5405 free (last);
5410 * A function definition is added if it matches:
5411 * <beginning of line><Erlang Atom><whitespace>(
5413 * It is added to the tags database if it doesn't match the
5414 * name of the previous clause header.
5416 * Return the size of the name of the function, or 0 if no function
5417 * was found.
5419 static int
5420 erlang_func (char *s, char *last)
5422 /* Name of last clause. */
5424 int pos;
5425 int len;
5427 pos = erlang_atom (s);
5428 if (pos < 1)
5429 return 0;
5431 len = pos;
5432 pos = skip_spaces (s + pos) - s;
5434 /* Save only the first clause. */
5435 if (s[pos++] == '('
5436 && (last == NULL
5437 || len != (int)strlen (last)
5438 || !strneq (s, last, len)))
5440 make_tag (s, len, true, s, pos, lineno, linecharno);
5441 return len;
5444 return 0;
5449 * Handle attributes. Currently, tags are generated for defines
5450 * and records.
5452 * They are on the form:
5453 * -define(foo, bar).
5454 * -define(Foo(M, N), M+N).
5455 * -record(graph, {vtab = notable, cyclic = true}).
5457 static void
5458 erlang_attribute (char *s)
5460 char *cp = s;
5462 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5463 && *cp++ == '(')
5465 int len = erlang_atom (skip_spaces (cp));
5466 if (len > 0)
5467 make_tag (cp, len, true, s, cp + len - s, lineno, linecharno);
5469 return;
5474 * Consume an Erlang atom (or variable).
5475 * Return the number of bytes consumed, or -1 if there was an error.
5477 static int
5478 erlang_atom (char *s)
5480 int pos = 0;
5482 if (ISALPHA (s[pos]) || s[pos] == '_')
5484 /* The atom is unquoted. */
5486 pos++;
5487 while (ISALNUM (s[pos]) || s[pos] == '_');
5489 else if (s[pos] == '\'')
5491 for (pos++; s[pos] != '\''; pos++)
5492 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5493 || (s[pos] == '\\' && s[++pos] == '\0'))
5494 return 0;
5495 pos++;
5498 return pos;
5502 static char *scan_separators (char *);
5503 static void add_regex (char *, language *);
5504 static char *substitute (char *, char *, struct re_registers *);
5507 * Take a string like "/blah/" and turn it into "blah", verifying
5508 * that the first and last characters are the same, and handling
5509 * quoted separator characters. Actually, stops on the occurrence of
5510 * an unquoted separator. Also process \t, \n, etc. and turn into
5511 * appropriate characters. Works in place. Null terminates name string.
5512 * Returns pointer to terminating separator, or NULL for
5513 * unterminated regexps.
5515 static char *
5516 scan_separators (char *name)
5518 char sep = name[0];
5519 char *copyto = name;
5520 bool quoted = false;
5522 for (++name; *name != '\0'; ++name)
5524 if (quoted)
5526 switch (*name)
5528 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
5529 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
5530 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
5531 case 'e': *copyto++ = 033; break; /* ESC (delete) */
5532 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
5533 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
5534 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
5535 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
5536 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
5537 default:
5538 if (*name == sep)
5539 *copyto++ = sep;
5540 else
5542 /* Something else is quoted, so preserve the quote. */
5543 *copyto++ = '\\';
5544 *copyto++ = *name;
5546 break;
5548 quoted = false;
5550 else if (*name == '\\')
5551 quoted = true;
5552 else if (*name == sep)
5553 break;
5554 else
5555 *copyto++ = *name;
5557 if (*name != sep)
5558 name = NULL; /* signal unterminated regexp */
5560 /* Terminate copied string. */
5561 *copyto = '\0';
5562 return name;
5565 /* Look at the argument of --regex or --no-regex and do the right
5566 thing. Same for each line of a regexp file. */
5567 static void
5568 analyze_regex (char *regex_arg)
5570 if (regex_arg == NULL)
5572 free_regexps (); /* --no-regex: remove existing regexps */
5573 return;
5576 /* A real --regexp option or a line in a regexp file. */
5577 switch (regex_arg[0])
5579 /* Comments in regexp file or null arg to --regex. */
5580 case '\0':
5581 case ' ':
5582 case '\t':
5583 break;
5585 /* Read a regex file. This is recursive and may result in a
5586 loop, which will stop when the file descriptors are exhausted. */
5587 case '@':
5589 FILE *regexfp;
5590 linebuffer regexbuf;
5591 char *regexfile = regex_arg + 1;
5593 /* regexfile is a file containing regexps, one per line. */
5594 regexfp = fopen (regexfile, "r" FOPEN_BINARY);
5595 if (regexfp == NULL)
5596 pfatal (regexfile);
5597 linebuffer_init (&regexbuf);
5598 while (readline_internal (&regexbuf, regexfp) > 0)
5599 analyze_regex (regexbuf.buffer);
5600 free (regexbuf.buffer);
5601 fclose (regexfp);
5603 break;
5605 /* Regexp to be used for a specific language only. */
5606 case '{':
5608 language *lang;
5609 char *lang_name = regex_arg + 1;
5610 char *cp;
5612 for (cp = lang_name; *cp != '}'; cp++)
5613 if (*cp == '\0')
5615 error ("unterminated language name in regex: %s", regex_arg);
5616 return;
5618 *cp++ = '\0';
5619 lang = get_language_from_langname (lang_name);
5620 if (lang == NULL)
5621 return;
5622 add_regex (cp, lang);
5624 break;
5626 /* Regexp to be used for any language. */
5627 default:
5628 add_regex (regex_arg, NULL);
5629 break;
5633 /* Separate the regexp pattern, compile it,
5634 and care for optional name and modifiers. */
5635 static void
5636 add_regex (char *regexp_pattern, language *lang)
5638 static struct re_pattern_buffer zeropattern;
5639 char sep, *pat, *name, *modifiers;
5640 char empty = '\0';
5641 const char *err;
5642 struct re_pattern_buffer *patbuf;
5643 regexp *rp;
5644 bool
5645 force_explicit_name = true, /* do not use implicit tag names */
5646 ignore_case = false, /* case is significant */
5647 multi_line = false, /* matches are done one line at a time */
5648 single_line = false; /* dot does not match newline */
5651 if (strlen (regexp_pattern) < 3)
5653 error ("null regexp");
5654 return;
5656 sep = regexp_pattern[0];
5657 name = scan_separators (regexp_pattern);
5658 if (name == NULL)
5660 error ("%s: unterminated regexp", regexp_pattern);
5661 return;
5663 if (name[1] == sep)
5665 error ("null name for regexp \"%s\"", regexp_pattern);
5666 return;
5668 modifiers = scan_separators (name);
5669 if (modifiers == NULL) /* no terminating separator --> no name */
5671 modifiers = name;
5672 name = &empty;
5674 else
5675 modifiers += 1; /* skip separator */
5677 /* Parse regex modifiers. */
5678 for (; modifiers[0] != '\0'; modifiers++)
5679 switch (modifiers[0])
5681 case 'N':
5682 if (modifiers == name)
5683 error ("forcing explicit tag name but no name, ignoring");
5684 force_explicit_name = true;
5685 break;
5686 case 'i':
5687 ignore_case = true;
5688 break;
5689 case 's':
5690 single_line = true;
5691 /* FALLTHRU */
5692 case 'm':
5693 multi_line = true;
5694 need_filebuf = true;
5695 break;
5696 default:
5697 error ("invalid regexp modifier `%c', ignoring", modifiers[0]);
5698 break;
5701 patbuf = xnew (1, struct re_pattern_buffer);
5702 *patbuf = zeropattern;
5703 if (ignore_case)
5705 static char lc_trans[CHARS];
5706 int i;
5707 for (i = 0; i < CHARS; i++)
5708 lc_trans[i] = lowcase (i);
5709 patbuf->translate = lc_trans; /* translation table to fold case */
5712 if (multi_line)
5713 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
5714 else
5715 pat = regexp_pattern;
5717 if (single_line)
5718 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
5719 else
5720 re_set_syntax (RE_SYNTAX_EMACS);
5722 err = re_compile_pattern (pat, strlen (pat), patbuf);
5723 if (multi_line)
5724 free (pat);
5725 if (err != NULL)
5727 error ("%s while compiling pattern", err);
5728 return;
5731 rp = p_head;
5732 p_head = xnew (1, regexp);
5733 p_head->pattern = savestr (regexp_pattern);
5734 p_head->p_next = rp;
5735 p_head->lang = lang;
5736 p_head->pat = patbuf;
5737 p_head->name = savestr (name);
5738 p_head->error_signaled = false;
5739 p_head->force_explicit_name = force_explicit_name;
5740 p_head->ignore_case = ignore_case;
5741 p_head->multi_line = multi_line;
5745 * Do the substitutions indicated by the regular expression and
5746 * arguments.
5748 static char *
5749 substitute (char *in, char *out, struct re_registers *regs)
5751 char *result, *t;
5752 int size, dig, diglen;
5754 result = NULL;
5755 size = strlen (out);
5757 /* Pass 1: figure out how much to allocate by finding all \N strings. */
5758 if (out[size - 1] == '\\')
5759 fatal ("pattern error in \"%s\"", out);
5760 for (t = strchr (out, '\\');
5761 t != NULL;
5762 t = strchr (t + 2, '\\'))
5763 if (ISDIGIT (t[1]))
5765 dig = t[1] - '0';
5766 diglen = regs->end[dig] - regs->start[dig];
5767 size += diglen - 2;
5769 else
5770 size -= 1;
5772 /* Allocate space and do the substitutions. */
5773 assert (size >= 0);
5774 result = xnew (size + 1, char);
5776 for (t = result; *out != '\0'; out++)
5777 if (*out == '\\' && ISDIGIT (*++out))
5779 dig = *out - '0';
5780 diglen = regs->end[dig] - regs->start[dig];
5781 memcpy (t, in + regs->start[dig], diglen);
5782 t += diglen;
5784 else
5785 *t++ = *out;
5786 *t = '\0';
5788 assert (t <= result + size);
5789 assert (t - result == (int)strlen (result));
5791 return result;
5794 /* Deallocate all regexps. */
5795 static void
5796 free_regexps (void)
5798 regexp *rp;
5799 while (p_head != NULL)
5801 rp = p_head->p_next;
5802 free (p_head->pattern);
5803 free (p_head->name);
5804 free (p_head);
5805 p_head = rp;
5807 return;
5811 * Reads the whole file as a single string from `filebuf' and looks for
5812 * multi-line regular expressions, creating tags on matches.
5813 * readline already dealt with normal regexps.
5815 * Idea by Ben Wing <ben@666.com> (2002).
5817 static void
5818 regex_tag_multiline (void)
5820 char *buffer = filebuf.buffer;
5821 regexp *rp;
5822 char *name;
5824 for (rp = p_head; rp != NULL; rp = rp->p_next)
5826 int match = 0;
5828 if (!rp->multi_line)
5829 continue; /* skip normal regexps */
5831 /* Generic initializations before parsing file from memory. */
5832 lineno = 1; /* reset global line number */
5833 charno = 0; /* reset global char number */
5834 linecharno = 0; /* reset global char number of line start */
5836 /* Only use generic regexps or those for the current language. */
5837 if (rp->lang != NULL && rp->lang != curfdp->lang)
5838 continue;
5840 while (match >= 0 && match < filebuf.len)
5842 match = re_search (rp->pat, buffer, filebuf.len, charno,
5843 filebuf.len - match, &rp->regs);
5844 switch (match)
5846 case -2:
5847 /* Some error. */
5848 if (!rp->error_signaled)
5850 error ("regexp stack overflow while matching \"%s\"",
5851 rp->pattern);
5852 rp->error_signaled = true;
5854 break;
5855 case -1:
5856 /* No match. */
5857 break;
5858 default:
5859 if (match == rp->regs.end[0])
5861 if (!rp->error_signaled)
5863 error ("regexp matches the empty string: \"%s\"",
5864 rp->pattern);
5865 rp->error_signaled = true;
5867 match = -3; /* exit from while loop */
5868 break;
5871 /* Match occurred. Construct a tag. */
5872 while (charno < rp->regs.end[0])
5873 if (buffer[charno++] == '\n')
5874 lineno++, linecharno = charno;
5875 name = rp->name;
5876 if (name[0] == '\0')
5877 name = NULL;
5878 else /* make a named tag */
5879 name = substitute (buffer, rp->name, &rp->regs);
5880 if (rp->force_explicit_name)
5881 /* Force explicit tag name, if a name is there. */
5882 pfnote (name, true, buffer + linecharno,
5883 charno - linecharno + 1, lineno, linecharno);
5884 else
5885 make_tag (name, strlen (name), true, buffer + linecharno,
5886 charno - linecharno + 1, lineno, linecharno);
5887 break;
5894 static bool
5895 nocase_tail (const char *cp)
5897 register int len = 0;
5899 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
5900 cp++, len++;
5901 if (*cp == '\0' && !intoken (dbp[len]))
5903 dbp += len;
5904 return true;
5906 return false;
5909 static void
5910 get_tag (register char *bp, char **namepp)
5912 register char *cp = bp;
5914 if (*bp != '\0')
5916 /* Go till you get to white space or a syntactic break */
5917 for (cp = bp + 1; !notinname (*cp); cp++)
5918 continue;
5919 make_tag (bp, cp - bp, true,
5920 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5923 if (namepp != NULL)
5924 *namepp = savenstr (bp, cp - bp);
5928 * Read a line of text from `stream' into `lbp', excluding the
5929 * newline or CR-NL, if any. Return the number of characters read from
5930 * `stream', which is the length of the line including the newline.
5932 * On DOS or Windows we do not count the CR character, if any before the
5933 * NL, in the returned length; this mirrors the behavior of Emacs on those
5934 * platforms (for text files, it translates CR-NL to NL as it reads in the
5935 * file).
5937 * If multi-line regular expressions are requested, each line read is
5938 * appended to `filebuf'.
5940 static long
5941 readline_internal (linebuffer *lbp, register FILE *stream)
5943 char *buffer = lbp->buffer;
5944 register char *p = lbp->buffer;
5945 register char *pend;
5946 int chars_deleted;
5948 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
5950 for (;;)
5952 register int c = getc (stream);
5953 if (p == pend)
5955 /* We're at the end of linebuffer: expand it. */
5956 lbp->size *= 2;
5957 xrnew (buffer, lbp->size, char);
5958 p += buffer - lbp->buffer;
5959 pend = buffer + lbp->size;
5960 lbp->buffer = buffer;
5962 if (c == EOF)
5964 *p = '\0';
5965 chars_deleted = 0;
5966 break;
5968 if (c == '\n')
5970 if (p > buffer && p[-1] == '\r')
5972 p -= 1;
5973 #ifdef DOS_NT
5974 /* Assume CRLF->LF translation will be performed by Emacs
5975 when loading this file, so CRs won't appear in the buffer.
5976 It would be cleaner to compensate within Emacs;
5977 however, Emacs does not know how many CRs were deleted
5978 before any given point in the file. */
5979 chars_deleted = 1;
5980 #else
5981 chars_deleted = 2;
5982 #endif
5984 else
5986 chars_deleted = 1;
5988 *p = '\0';
5989 break;
5991 *p++ = c;
5993 lbp->len = p - buffer;
5995 if (need_filebuf /* we need filebuf for multi-line regexps */
5996 && chars_deleted > 0) /* not at EOF */
5998 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6000 /* Expand filebuf. */
6001 filebuf.size *= 2;
6002 xrnew (filebuf.buffer, filebuf.size, char);
6004 memcpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6005 filebuf.len += lbp->len;
6006 filebuf.buffer[filebuf.len++] = '\n';
6007 filebuf.buffer[filebuf.len] = '\0';
6010 return lbp->len + chars_deleted;
6014 * Like readline_internal, above, but in addition try to match the
6015 * input line against relevant regular expressions and manage #line
6016 * directives.
6018 static void
6019 readline (linebuffer *lbp, FILE *stream)
6021 long result;
6023 linecharno = charno; /* update global char number of line start */
6024 result = readline_internal (lbp, stream); /* read line */
6025 lineno += 1; /* increment global line number */
6026 charno += result; /* increment global char number */
6028 /* Honor #line directives. */
6029 if (!no_line_directive)
6031 static bool discard_until_line_directive;
6033 /* Check whether this is a #line directive. */
6034 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6036 unsigned int lno;
6037 int start = 0;
6039 if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6040 && start > 0) /* double quote character found */
6042 char *endp = lbp->buffer + start;
6044 while ((endp = strchr (endp, '"')) != NULL
6045 && endp[-1] == '\\')
6046 endp++;
6047 if (endp != NULL)
6048 /* Ok, this is a real #line directive. Let's deal with it. */
6050 char *taggedabsname; /* absolute name of original file */
6051 char *taggedfname; /* name of original file as given */
6052 char *name; /* temp var */
6054 discard_until_line_directive = false; /* found it */
6055 name = lbp->buffer + start;
6056 *endp = '\0';
6057 canonicalize_filename (name);
6058 taggedabsname = absolute_filename (name, tagfiledir);
6059 if (filename_is_absolute (name)
6060 || filename_is_absolute (curfdp->infname))
6061 taggedfname = savestr (taggedabsname);
6062 else
6063 taggedfname = relative_filename (taggedabsname,tagfiledir);
6065 if (streq (curfdp->taggedfname, taggedfname))
6066 /* The #line directive is only a line number change. We
6067 deal with this afterwards. */
6068 free (taggedfname);
6069 else
6070 /* The tags following this #line directive should be
6071 attributed to taggedfname. In order to do this, set
6072 curfdp accordingly. */
6074 fdesc *fdp; /* file description pointer */
6076 /* Go look for a file description already set up for the
6077 file indicated in the #line directive. If there is
6078 one, use it from now until the next #line
6079 directive. */
6080 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6081 if (streq (fdp->infname, curfdp->infname)
6082 && streq (fdp->taggedfname, taggedfname))
6083 /* If we remove the second test above (after the &&)
6084 then all entries pertaining to the same file are
6085 coalesced in the tags file. If we use it, then
6086 entries pertaining to the same file but generated
6087 from different files (via #line directives) will
6088 go into separate sections in the tags file. These
6089 alternatives look equivalent. The first one
6090 destroys some apparently useless information. */
6092 curfdp = fdp;
6093 free (taggedfname);
6094 break;
6096 /* Else, if we already tagged the real file, skip all
6097 input lines until the next #line directive. */
6098 if (fdp == NULL) /* not found */
6099 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6100 if (streq (fdp->infabsname, taggedabsname))
6102 discard_until_line_directive = true;
6103 free (taggedfname);
6104 break;
6106 /* Else create a new file description and use that from
6107 now on, until the next #line directive. */
6108 if (fdp == NULL) /* not found */
6110 fdp = fdhead;
6111 fdhead = xnew (1, fdesc);
6112 *fdhead = *curfdp; /* copy curr. file description */
6113 fdhead->next = fdp;
6114 fdhead->infname = savestr (curfdp->infname);
6115 fdhead->infabsname = savestr (curfdp->infabsname);
6116 fdhead->infabsdir = savestr (curfdp->infabsdir);
6117 fdhead->taggedfname = taggedfname;
6118 fdhead->usecharno = false;
6119 fdhead->prop = NULL;
6120 fdhead->written = false;
6121 curfdp = fdhead;
6124 free (taggedabsname);
6125 lineno = lno - 1;
6126 readline (lbp, stream);
6127 return;
6128 } /* if a real #line directive */
6129 } /* if #line is followed by a number */
6130 } /* if line begins with "#line " */
6132 /* If we are here, no #line directive was found. */
6133 if (discard_until_line_directive)
6135 if (result > 0)
6137 /* Do a tail recursion on ourselves, thus discarding the contents
6138 of the line buffer. */
6139 readline (lbp, stream);
6140 return;
6142 /* End of file. */
6143 discard_until_line_directive = false;
6144 return;
6146 } /* if #line directives should be considered */
6149 int match;
6150 regexp *rp;
6151 char *name;
6153 /* Match against relevant regexps. */
6154 if (lbp->len > 0)
6155 for (rp = p_head; rp != NULL; rp = rp->p_next)
6157 /* Only use generic regexps or those for the current language.
6158 Also do not use multiline regexps, which is the job of
6159 regex_tag_multiline. */
6160 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6161 || rp->multi_line)
6162 continue;
6164 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6165 switch (match)
6167 case -2:
6168 /* Some error. */
6169 if (!rp->error_signaled)
6171 error ("regexp stack overflow while matching \"%s\"",
6172 rp->pattern);
6173 rp->error_signaled = true;
6175 break;
6176 case -1:
6177 /* No match. */
6178 break;
6179 case 0:
6180 /* Empty string matched. */
6181 if (!rp->error_signaled)
6183 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6184 rp->error_signaled = true;
6186 break;
6187 default:
6188 /* Match occurred. Construct a tag. */
6189 name = rp->name;
6190 if (name[0] == '\0')
6191 name = NULL;
6192 else /* make a named tag */
6193 name = substitute (lbp->buffer, rp->name, &rp->regs);
6194 if (rp->force_explicit_name)
6195 /* Force explicit tag name, if a name is there. */
6196 pfnote (name, true, lbp->buffer, match, lineno, linecharno);
6197 else
6198 make_tag (name, strlen (name), true,
6199 lbp->buffer, match, lineno, linecharno);
6200 break;
6208 * Return a pointer to a space of size strlen(cp)+1 allocated
6209 * with xnew where the string CP has been copied.
6211 static char *
6212 savestr (const char *cp)
6214 return savenstr (cp, strlen (cp));
6218 * Return a pointer to a space of size LEN+1 allocated with xnew where
6219 * the string CP has been copied for at most the first LEN characters.
6221 static char *
6222 savenstr (const char *cp, int len)
6224 char *dp = xnew (len + 1, char);
6225 dp[len] = '\0';
6226 return memcpy (dp, cp, len);
6229 /* Skip spaces (end of string is not space), return new pointer. */
6230 static char *
6231 skip_spaces (char *cp)
6233 while (iswhite (*cp))
6234 cp++;
6235 return cp;
6238 /* Skip non spaces, except end of string, return new pointer. */
6239 static char *
6240 skip_non_spaces (char *cp)
6242 while (*cp != '\0' && !iswhite (*cp))
6243 cp++;
6244 return cp;
6247 /* Skip any chars in the "name" class.*/
6248 static char *
6249 skip_name (char *cp)
6251 /* '\0' is a notinname() so loop stops there too */
6252 while (! notinname (*cp))
6253 cp++;
6254 return cp;
6257 /* Print error message and exit. */
6258 void
6259 fatal (const char *s1, const char *s2)
6261 error (s1, s2);
6262 exit (EXIT_FAILURE);
6265 static void
6266 pfatal (const char *s1)
6268 perror (s1);
6269 exit (EXIT_FAILURE);
6272 static void
6273 suggest_asking_for_help (void)
6275 fprintf (stderr, "\tTry `%s --help' for a complete list of options.\n",
6276 progname);
6277 exit (EXIT_FAILURE);
6280 /* Output a diagnostic with printf-style FORMAT and args. */
6281 static void
6282 error (const char *format, ...)
6284 va_list ap;
6285 va_start (ap, format);
6286 fprintf (stderr, "%s: ", progname);
6287 vfprintf (stderr, format, ap);
6288 fprintf (stderr, "\n");
6289 va_end (ap);
6292 /* Return a newly-allocated string whose contents
6293 concatenate those of s1, s2, s3. */
6294 static char *
6295 concat (const char *s1, const char *s2, const char *s3)
6297 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6298 char *result = xnew (len1 + len2 + len3 + 1, char);
6300 strcpy (result, s1);
6301 strcpy (result + len1, s2);
6302 strcpy (result + len1 + len2, s3);
6304 return result;
6308 /* Does the same work as the system V getcwd, but does not need to
6309 guess the buffer size in advance. */
6310 static char *
6311 etags_getcwd (void)
6313 int bufsize = 200;
6314 char *path = xnew (bufsize, char);
6316 while (getcwd (path, bufsize) == NULL)
6318 if (errno != ERANGE)
6319 pfatal ("getcwd");
6320 bufsize *= 2;
6321 free (path);
6322 path = xnew (bufsize, char);
6325 canonicalize_filename (path);
6326 return path;
6329 /* Return a newly allocated string containing the file name of FILE
6330 relative to the absolute directory DIR (which should end with a slash). */
6331 static char *
6332 relative_filename (char *file, char *dir)
6334 char *fp, *dp, *afn, *res;
6335 int i;
6337 /* Find the common root of file and dir (with a trailing slash). */
6338 afn = absolute_filename (file, cwd);
6339 fp = afn;
6340 dp = dir;
6341 while (*fp++ == *dp++)
6342 continue;
6343 fp--, dp--; /* back to the first differing char */
6344 #ifdef DOS_NT
6345 if (fp == afn && afn[0] != '/') /* cannot build a relative name */
6346 return afn;
6347 #endif
6348 do /* look at the equal chars until '/' */
6349 fp--, dp--;
6350 while (*fp != '/');
6352 /* Build a sequence of "../" strings for the resulting relative file name. */
6353 i = 0;
6354 while ((dp = strchr (dp + 1, '/')) != NULL)
6355 i += 1;
6356 res = xnew (3*i + strlen (fp + 1) + 1, char);
6357 char *z = res;
6358 while (i-- > 0)
6359 z = stpcpy (z, "../");
6361 /* Add the file name relative to the common root of file and dir. */
6362 strcpy (z, fp + 1);
6363 free (afn);
6365 return res;
6368 /* Return a newly allocated string containing the absolute file name
6369 of FILE given DIR (which should end with a slash). */
6370 static char *
6371 absolute_filename (char *file, char *dir)
6373 char *slashp, *cp, *res;
6375 if (filename_is_absolute (file))
6376 res = savestr (file);
6377 #ifdef DOS_NT
6378 /* We don't support non-absolute file names with a drive
6379 letter, like `d:NAME' (it's too much hassle). */
6380 else if (file[1] == ':')
6381 fatal ("%s: relative file names with drive letters not supported", file);
6382 #endif
6383 else
6384 res = concat (dir, file, "");
6386 /* Delete the "/dirname/.." and "/." substrings. */
6387 slashp = strchr (res, '/');
6388 while (slashp != NULL && slashp[0] != '\0')
6390 if (slashp[1] == '.')
6392 if (slashp[2] == '.'
6393 && (slashp[3] == '/' || slashp[3] == '\0'))
6395 cp = slashp;
6397 cp--;
6398 while (cp >= res && !filename_is_absolute (cp));
6399 if (cp < res)
6400 cp = slashp; /* the absolute name begins with "/.." */
6401 #ifdef DOS_NT
6402 /* Under MSDOS and NT we get `d:/NAME' as absolute
6403 file name, so the luser could say `d:/../NAME'.
6404 We silently treat this as `d:/NAME'. */
6405 else if (cp[0] != '/')
6406 cp = slashp;
6407 #endif
6408 memmove (cp, slashp + 3, strlen (slashp + 2));
6409 slashp = cp;
6410 continue;
6412 else if (slashp[2] == '/' || slashp[2] == '\0')
6414 memmove (slashp, slashp + 2, strlen (slashp + 1));
6415 continue;
6419 slashp = strchr (slashp + 1, '/');
6422 if (res[0] == '\0') /* just a safety net: should never happen */
6424 free (res);
6425 return savestr ("/");
6427 else
6428 return res;
6431 /* Return a newly allocated string containing the absolute
6432 file name of dir where FILE resides given DIR (which should
6433 end with a slash). */
6434 static char *
6435 absolute_dirname (char *file, char *dir)
6437 char *slashp, *res;
6438 char save;
6440 slashp = strrchr (file, '/');
6441 if (slashp == NULL)
6442 return savestr (dir);
6443 save = slashp[1];
6444 slashp[1] = '\0';
6445 res = absolute_filename (file, dir);
6446 slashp[1] = save;
6448 return res;
6451 /* Whether the argument string is an absolute file name. The argument
6452 string must have been canonicalized with canonicalize_filename. */
6453 static bool
6454 filename_is_absolute (char *fn)
6456 return (fn[0] == '/'
6457 #ifdef DOS_NT
6458 || (ISALPHA (fn[0]) && fn[1] == ':' && fn[2] == '/')
6459 #endif
6463 /* Downcase DOS drive letter and collapse separators into single slashes.
6464 Works in place. */
6465 static void
6466 canonicalize_filename (register char *fn)
6468 register char* cp;
6469 char sep = '/';
6471 #ifdef DOS_NT
6472 /* Canonicalize drive letter case. */
6473 # define ISUPPER(c) isupper (CHAR (c))
6474 if (fn[0] != '\0' && fn[1] == ':' && ISUPPER (fn[0]))
6475 fn[0] = lowcase (fn[0]);
6477 sep = '\\';
6478 #endif
6480 /* Collapse multiple separators into a single slash. */
6481 for (cp = fn; *cp != '\0'; cp++, fn++)
6482 if (*cp == sep)
6484 *fn = '/';
6485 while (cp[1] == sep)
6486 cp++;
6488 else
6489 *fn = *cp;
6490 *fn = '\0';
6494 /* Initialize a linebuffer for use. */
6495 static void
6496 linebuffer_init (linebuffer *lbp)
6498 lbp->size = (DEBUG) ? 3 : 200;
6499 lbp->buffer = xnew (lbp->size, char);
6500 lbp->buffer[0] = '\0';
6501 lbp->len = 0;
6504 /* Set the minimum size of a string contained in a linebuffer. */
6505 static void
6506 linebuffer_setlen (linebuffer *lbp, int toksize)
6508 while (lbp->size <= toksize)
6510 lbp->size *= 2;
6511 xrnew (lbp->buffer, lbp->size, char);
6513 lbp->len = toksize;
6516 /* Like malloc but get fatal error if memory is exhausted. */
6517 static void *
6518 xmalloc (size_t size)
6520 void *result = malloc (size);
6521 if (result == NULL)
6522 fatal ("virtual memory exhausted", (char *)NULL);
6523 return result;
6526 static void *
6527 xrealloc (void *ptr, size_t size)
6529 void *result = realloc (ptr, size);
6530 if (result == NULL)
6531 fatal ("virtual memory exhausted", (char *)NULL);
6532 return result;
6536 * Local Variables:
6537 * indent-tabs-mode: t
6538 * tab-width: 8
6539 * fill-column: 79
6540 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
6541 * c-file-style: "gnu"
6542 * End:
6545 /* etags.c ends here */