* subr.el (add-to-history): Fix delete usage.
[emacs.git] / lib-src / etags.c
blobe65082de5343a16b0c92372c590a533ead2f080e
1 /* Tags file maker to go with GNU Emacs -*- coding: latin-1 -*-
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-2012
32 Free Software 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 #define TRUE 1
84 #define FALSE 0
86 #ifdef DEBUG
87 # undef DEBUG
88 # define DEBUG TRUE
89 #else
90 # define DEBUG FALSE
91 # define NDEBUG /* disable assert */
92 #endif
94 #include <config.h>
96 #ifndef _GNU_SOURCE
97 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
98 #endif
100 /* WIN32_NATIVE is for XEmacs.
101 MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
102 #ifdef WIN32_NATIVE
103 # undef MSDOS
104 # undef WINDOWSNT
105 # define WINDOWSNT
106 #endif /* WIN32_NATIVE */
108 #ifdef MSDOS
109 # undef MSDOS
110 # define MSDOS TRUE
111 # include <fcntl.h>
112 # include <sys/param.h>
113 # include <io.h>
114 #else
115 # define MSDOS FALSE
116 #endif /* MSDOS */
118 #ifdef WINDOWSNT
119 # include <fcntl.h>
120 # include <direct.h>
121 # include <io.h>
122 # define MAXPATHLEN _MAX_PATH
123 # undef HAVE_NTGUI
124 # undef DOS_NT
125 # define DOS_NT
126 # ifndef HAVE_GETCWD
127 # define HAVE_GETCWD
128 # endif /* undef HAVE_GETCWD */
129 #else /* not WINDOWSNT */
130 #endif /* !WINDOWSNT */
132 #include <unistd.h>
133 #ifndef HAVE_UNISTD_H
134 # if defined (HAVE_GETCWD) && !defined (WINDOWSNT)
135 extern char *getcwd (char *buf, size_t size);
136 # endif
137 #endif /* HAVE_UNISTD_H */
139 #include <stdarg.h>
140 #include <stdlib.h>
141 #include <string.h>
142 #include <stdio.h>
143 #include <ctype.h>
144 #include <errno.h>
145 #include <sys/types.h>
146 #include <sys/stat.h>
147 #include <c-strcase.h>
149 #include <assert.h>
150 #ifdef NDEBUG
151 # undef assert /* some systems have a buggy assert.h */
152 # define assert(x) ((void) 0)
153 #endif
155 #ifdef NO_LONG_OPTIONS /* define this if you don't have GNU getopt */
156 # define NO_LONG_OPTIONS TRUE
157 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
158 extern char *optarg;
159 extern int optind, opterr;
160 #else
161 # define NO_LONG_OPTIONS FALSE
162 # include <getopt.h>
163 #endif /* NO_LONG_OPTIONS */
165 #include <regex.h>
167 /* Define CTAGS to make the program "ctags" compatible with the usual one.
168 Leave it undefined to make the program "etags", which makes emacs-style
169 tag tables and tags typedefs, #defines and struct/union/enum by default. */
170 #ifdef CTAGS
171 # undef CTAGS
172 # define CTAGS TRUE
173 #else
174 # define CTAGS FALSE
175 #endif
177 #define streq(s,t) (assert ((s)!=NULL || (t)!=NULL), !strcmp (s, t))
178 #define strcaseeq(s,t) (assert ((s)!=NULL && (t)!=NULL), !c_strcasecmp (s, t))
179 #define strneq(s,t,n) (assert ((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
180 #define strncaseeq(s,t,n) (assert ((s)!=NULL && (t)!=NULL), !c_strncasecmp (s, t, n))
182 #define CHARS 256 /* 2^sizeof(char) */
183 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
184 #define iswhite(c) (_wht[CHAR (c)]) /* c is white (see white) */
185 #define notinname(c) (_nin[CHAR (c)]) /* c is not in a name (see nonam) */
186 #define begtoken(c) (_btk[CHAR (c)]) /* c can start token (see begtk) */
187 #define intoken(c) (_itk[CHAR (c)]) /* c can be in token (see midtk) */
188 #define endtoken(c) (_etk[CHAR (c)]) /* c ends tokens (see endtk) */
190 #define ISALNUM(c) isalnum (CHAR (c))
191 #define ISALPHA(c) isalpha (CHAR (c))
192 #define ISDIGIT(c) isdigit (CHAR (c))
193 #define ISLOWER(c) islower (CHAR (c))
195 #define lowcase(c) tolower (CHAR (c))
199 * xnew, xrnew -- allocate, reallocate storage
201 * SYNOPSIS: Type *xnew (int n, Type);
202 * void xrnew (OldPointer, int n, Type);
204 #if DEBUG
205 # include "chkmalloc.h"
206 # define xnew(n,Type) ((Type *) trace_malloc (__FILE__, __LINE__, \
207 (n) * sizeof (Type)))
208 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
209 (char *) (op), (n) * sizeof (Type)))
210 #else
211 # define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
212 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
213 (char *) (op), (n) * sizeof (Type)))
214 #endif
216 #define bool int
218 typedef void Lang_function (FILE *);
220 typedef struct
222 const char *suffix; /* file name suffix for this compressor */
223 const char *command; /* takes one arg and decompresses to stdout */
224 } compressor;
226 typedef struct
228 const char *name; /* language name */
229 const char *help; /* detailed help for the language */
230 Lang_function *function; /* parse function */
231 const char **suffixes; /* name suffixes of this language's files */
232 const char **filenames; /* names of this language's files */
233 const char **interpreters; /* interpreters for this language */
234 bool metasource; /* source used to generate other sources */
235 } language;
237 typedef struct fdesc
239 struct fdesc *next; /* for the linked list */
240 char *infname; /* uncompressed input file name */
241 char *infabsname; /* absolute uncompressed input file name */
242 char *infabsdir; /* absolute dir of input file */
243 char *taggedfname; /* file name to write in tagfile */
244 language *lang; /* language of file */
245 char *prop; /* file properties to write in tagfile */
246 bool usecharno; /* etags tags shall contain char number */
247 bool written; /* entry written in the tags file */
248 } fdesc;
250 typedef struct node_st
251 { /* sorting structure */
252 struct node_st *left, *right; /* left and right sons */
253 fdesc *fdp; /* description of file to whom tag belongs */
254 char *name; /* tag name */
255 char *regex; /* search regexp */
256 bool valid; /* write this tag on the tag file */
257 bool is_func; /* function tag: use regexp in CTAGS mode */
258 bool been_warned; /* warning already given for duplicated tag */
259 int lno; /* line number tag is on */
260 long cno; /* character number line starts on */
261 } node;
264 * A `linebuffer' is a structure which holds a line of text.
265 * `readline_internal' reads a line from a stream into a linebuffer
266 * and works regardless of the length of the line.
267 * SIZE is the size of BUFFER, LEN is the length of the string in
268 * BUFFER after readline reads it.
270 typedef struct
272 long size;
273 int len;
274 char *buffer;
275 } linebuffer;
277 /* Used to support mixing of --lang and file names. */
278 typedef struct
280 enum {
281 at_language, /* a language specification */
282 at_regexp, /* a regular expression */
283 at_filename, /* a file name */
284 at_stdin, /* read from stdin here */
285 at_end /* stop parsing the list */
286 } arg_type; /* argument type */
287 language *lang; /* language associated with the argument */
288 char *what; /* the argument itself */
289 } argument;
291 /* Structure defining a regular expression. */
292 typedef struct regexp
294 struct regexp *p_next; /* pointer to next in list */
295 language *lang; /* if set, use only for this language */
296 char *pattern; /* the regexp pattern */
297 char *name; /* tag name */
298 struct re_pattern_buffer *pat; /* the compiled pattern */
299 struct re_registers regs; /* re registers */
300 bool error_signaled; /* already signaled for this regexp */
301 bool force_explicit_name; /* do not allow implicit tag name */
302 bool ignore_case; /* ignore case when matching */
303 bool multi_line; /* do a multi-line match on the whole file */
304 } regexp;
307 /* Many compilers barf on this:
308 Lang_function Ada_funcs;
309 so let's write it this way */
310 static void Ada_funcs (FILE *);
311 static void Asm_labels (FILE *);
312 static void C_entries (int c_ext, FILE *);
313 static void default_C_entries (FILE *);
314 static void plain_C_entries (FILE *);
315 static void Cjava_entries (FILE *);
316 static void Cobol_paragraphs (FILE *);
317 static void Cplusplus_entries (FILE *);
318 static void Cstar_entries (FILE *);
319 static void Erlang_functions (FILE *);
320 static void Forth_words (FILE *);
321 static void Fortran_functions (FILE *);
322 static void HTML_labels (FILE *);
323 static void Lisp_functions (FILE *);
324 static void Lua_functions (FILE *);
325 static void Makefile_targets (FILE *);
326 static void Pascal_functions (FILE *);
327 static void Perl_functions (FILE *);
328 static void PHP_functions (FILE *);
329 static void PS_functions (FILE *);
330 static void Prolog_functions (FILE *);
331 static void Python_functions (FILE *);
332 static void Scheme_functions (FILE *);
333 static void TeX_commands (FILE *);
334 static void Texinfo_nodes (FILE *);
335 static void Yacc_entries (FILE *);
336 static void just_read_file (FILE *);
338 static void print_language_names (void);
339 static void print_version (void);
340 static void print_help (argument *);
341 int main (int, char **);
343 static compressor *get_compressor_from_suffix (char *, char **);
344 static language *get_language_from_langname (const char *);
345 static language *get_language_from_interpreter (char *);
346 static language *get_language_from_filename (char *, bool);
347 static void readline (linebuffer *, FILE *);
348 static long readline_internal (linebuffer *, FILE *);
349 static bool nocase_tail (const char *);
350 static void get_tag (char *, char **);
352 static void analyse_regex (char *);
353 static void free_regexps (void);
354 static void regex_tag_multiline (void);
355 static void error (const char *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2);
356 static _Noreturn void suggest_asking_for_help (void);
357 _Noreturn void fatal (const char *, const char *);
358 static _Noreturn void pfatal (const char *);
359 static void add_node (node *, node **);
361 static void init (void);
362 static void process_file_name (char *, language *);
363 static void process_file (FILE *, char *, language *);
364 static void find_entries (FILE *);
365 static void free_tree (node *);
366 static void free_fdesc (fdesc *);
367 static void pfnote (char *, bool, char *, int, int, long);
368 static void make_tag (const char *, int, bool, char *, int, int, long);
369 static void invalidate_nodes (fdesc *, node **);
370 static void put_entries (node *);
372 static char *concat (const char *, const char *, const char *);
373 static char *skip_spaces (char *);
374 static char *skip_non_spaces (char *);
375 static char *savenstr (const char *, int);
376 static char *savestr (const char *);
377 static char *etags_strchr (const char *, int);
378 static char *etags_strrchr (const char *, int);
379 static char *etags_getcwd (void);
380 static char *relative_filename (char *, char *);
381 static char *absolute_filename (char *, char *);
382 static char *absolute_dirname (char *, char *);
383 static bool filename_is_absolute (char *f);
384 static void canonicalize_filename (char *);
385 static void linebuffer_init (linebuffer *);
386 static void linebuffer_setlen (linebuffer *, int);
387 static void *xmalloc (size_t);
388 static void *xrealloc (char *, size_t);
391 static char searchar = '/'; /* use /.../ searches */
393 static char *tagfile; /* output file */
394 static char *progname; /* name this program was invoked with */
395 static char *cwd; /* current working directory */
396 static char *tagfiledir; /* directory of tagfile */
397 static FILE *tagf; /* ioptr for tags file */
398 static ptrdiff_t whatlen_max; /* maximum length of any 'what' member */
400 static fdesc *fdhead; /* head of file description list */
401 static fdesc *curfdp; /* current file description */
402 static int lineno; /* line number of current line */
403 static long charno; /* current character number */
404 static long linecharno; /* charno of start of current line */
405 static char *dbp; /* pointer to start of current tag */
407 static const int invalidcharno = -1;
409 static node *nodehead; /* the head of the binary tree of tags */
410 static node *last_node; /* the last node created */
412 static linebuffer lb; /* the current line */
413 static linebuffer filebuf; /* a buffer containing the whole file */
414 static linebuffer token_name; /* a buffer containing a tag name */
416 /* boolean "functions" (see init) */
417 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
418 static const char
419 /* white chars */
420 *white = " \f\t\n\r\v",
421 /* not in a name */
422 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
423 /* token ending chars */
424 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
425 /* token starting chars */
426 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
427 /* valid in-token chars */
428 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
430 static bool append_to_tagfile; /* -a: append to tags */
431 /* The next five default to TRUE in C and derived languages. */
432 static bool typedefs; /* -t: create tags for C and Ada typedefs */
433 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
434 /* 0 struct/enum/union decls, and C++ */
435 /* member functions. */
436 static bool constantypedefs; /* -d: create tags for C #define, enum */
437 /* constants and variables. */
438 /* -D: opposite of -d. Default under ctags. */
439 static bool globals; /* create tags for global variables */
440 static bool members; /* create tags for C member variables */
441 static bool declarations; /* --declarations: tag them and extern in C&Co*/
442 static bool no_line_directive; /* ignore #line directives (undocumented) */
443 static bool no_duplicates; /* no duplicate tags for ctags (undocumented) */
444 static bool update; /* -u: update tags */
445 static bool vgrind_style; /* -v: create vgrind style index output */
446 static bool no_warnings; /* -w: suppress warnings (undocumented) */
447 static bool cxref_style; /* -x: create cxref style output */
448 static bool cplusplus; /* .[hc] means C++, not C (undocumented) */
449 static bool ignoreindent; /* -I: ignore indentation in C */
450 static bool packages_only; /* --packages-only: in Ada, only tag packages*/
452 /* STDIN is defined in LynxOS system headers */
453 #ifdef STDIN
454 # undef STDIN
455 #endif
457 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
458 static bool parsing_stdin; /* --parse-stdin used */
460 static regexp *p_head; /* list of all regexps */
461 static bool need_filebuf; /* some regexes are multi-line */
463 static struct option longopts[] =
465 { "append", no_argument, NULL, 'a' },
466 { "packages-only", no_argument, &packages_only, TRUE },
467 { "c++", no_argument, NULL, 'C' },
468 { "declarations", no_argument, &declarations, TRUE },
469 { "no-line-directive", no_argument, &no_line_directive, TRUE },
470 { "no-duplicates", no_argument, &no_duplicates, TRUE },
471 { "help", no_argument, NULL, 'h' },
472 { "help", no_argument, NULL, 'H' },
473 { "ignore-indentation", no_argument, NULL, 'I' },
474 { "language", required_argument, NULL, 'l' },
475 { "members", no_argument, &members, TRUE },
476 { "no-members", no_argument, &members, FALSE },
477 { "output", required_argument, NULL, 'o' },
478 { "regex", required_argument, NULL, 'r' },
479 { "no-regex", no_argument, NULL, 'R' },
480 { "ignore-case-regex", required_argument, NULL, 'c' },
481 { "parse-stdin", required_argument, NULL, STDIN },
482 { "version", no_argument, NULL, 'V' },
484 #if CTAGS /* Ctags options */
485 { "backward-search", no_argument, NULL, 'B' },
486 { "cxref", no_argument, NULL, 'x' },
487 { "defines", no_argument, NULL, 'd' },
488 { "globals", no_argument, &globals, TRUE },
489 { "typedefs", no_argument, NULL, 't' },
490 { "typedefs-and-c++", no_argument, NULL, 'T' },
491 { "update", no_argument, NULL, 'u' },
492 { "vgrind", no_argument, NULL, 'v' },
493 { "no-warn", no_argument, NULL, 'w' },
495 #else /* Etags options */
496 { "no-defines", no_argument, NULL, 'D' },
497 { "no-globals", no_argument, &globals, FALSE },
498 { "include", required_argument, NULL, 'i' },
499 #endif
500 { NULL }
503 static compressor compressors[] =
505 { "z", "gzip -d -c"},
506 { "Z", "gzip -d -c"},
507 { "gz", "gzip -d -c"},
508 { "GZ", "gzip -d -c"},
509 { "bz2", "bzip2 -d -c" },
510 { "xz", "xz -d -c" },
511 { NULL }
515 * Language stuff.
518 /* Ada code */
519 static const char *Ada_suffixes [] =
520 { "ads", "adb", "ada", NULL };
521 static const char Ada_help [] =
522 "In Ada code, functions, procedures, packages, tasks and types are\n\
523 tags. Use the `--packages-only' option to create tags for\n\
524 packages only.\n\
525 Ada tag names have suffixes indicating the type of entity:\n\
526 Entity type: Qualifier:\n\
527 ------------ ----------\n\
528 function /f\n\
529 procedure /p\n\
530 package spec /s\n\
531 package body /b\n\
532 type /t\n\
533 task /k\n\
534 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
535 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
536 will just search for any tag `bidule'.";
538 /* Assembly code */
539 static const char *Asm_suffixes [] =
540 { "a", /* Unix assembler */
541 "asm", /* Microcontroller assembly */
542 "def", /* BSO/Tasking definition includes */
543 "inc", /* Microcontroller include files */
544 "ins", /* Microcontroller include files */
545 "s", "sa", /* Unix assembler */
546 "S", /* cpp-processed Unix assembler */
547 "src", /* BSO/Tasking C compiler output */
548 NULL
550 static const char Asm_help [] =
551 "In assembler code, labels appearing at the beginning of a line,\n\
552 followed by a colon, are tags.";
555 /* Note that .c and .h can be considered C++, if the --c++ flag was
556 given, or if the `class' or `template' keywords are met inside the file.
557 That is why default_C_entries is called for these. */
558 static const char *default_C_suffixes [] =
559 { "c", "h", NULL };
560 #if CTAGS /* C help for Ctags */
561 static const char default_C_help [] =
562 "In C code, any C function is a tag. Use -t to tag typedefs.\n\
563 Use -T to tag definitions of `struct', `union' and `enum'.\n\
564 Use -d to tag `#define' macro definitions and `enum' constants.\n\
565 Use --globals to tag global variables.\n\
566 You can tag function declarations and external variables by\n\
567 using `--declarations', and struct members by using `--members'.";
568 #else /* C help for Etags */
569 static const char default_C_help [] =
570 "In C code, any C function or typedef is a tag, and so are\n\
571 definitions of `struct', `union' and `enum'. `#define' macro\n\
572 definitions and `enum' constants are tags unless you specify\n\
573 `--no-defines'. Global variables are tags unless you specify\n\
574 `--no-globals' and so are struct members unless you specify\n\
575 `--no-members'. Use of `--no-globals', `--no-defines' and\n\
576 `--no-members' can make the tags table file much smaller.\n\
577 You can tag function declarations and external variables by\n\
578 using `--declarations'.";
579 #endif /* C help for Ctags and Etags */
581 static const char *Cplusplus_suffixes [] =
582 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
583 "M", /* Objective C++ */
584 "pdb", /* PostScript with C syntax */
585 NULL };
586 static const char Cplusplus_help [] =
587 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
588 --help --lang=c --lang=c++ for full help.)\n\
589 In addition to C tags, member functions are also recognized. Member\n\
590 variables are recognized unless you use the `--no-members' option.\n\
591 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
592 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
593 `operator+'.";
595 static const char *Cjava_suffixes [] =
596 { "java", NULL };
597 static char Cjava_help [] =
598 "In Java code, all the tags constructs of C and C++ code are\n\
599 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
602 static const char *Cobol_suffixes [] =
603 { "COB", "cob", NULL };
604 static char Cobol_help [] =
605 "In Cobol code, tags are paragraph names; that is, any word\n\
606 starting in column 8 and followed by a period.";
608 static const char *Cstar_suffixes [] =
609 { "cs", "hs", NULL };
611 static const char *Erlang_suffixes [] =
612 { "erl", "hrl", NULL };
613 static const char Erlang_help [] =
614 "In Erlang code, the tags are the functions, records and macros\n\
615 defined in the file.";
617 const char *Forth_suffixes [] =
618 { "fth", "tok", NULL };
619 static const char Forth_help [] =
620 "In Forth code, tags are words defined by `:',\n\
621 constant, code, create, defer, value, variable, buffer:, field.";
623 static const char *Fortran_suffixes [] =
624 { "F", "f", "f90", "for", NULL };
625 static const char Fortran_help [] =
626 "In Fortran code, functions, subroutines and block data are tags.";
628 static const char *HTML_suffixes [] =
629 { "htm", "html", "shtml", NULL };
630 static const char HTML_help [] =
631 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
632 `h3' headers. Also, tags are `name=' in anchors and all\n\
633 occurrences of `id='.";
635 static const char *Lisp_suffixes [] =
636 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
637 static const char Lisp_help [] =
638 "In Lisp code, any function defined with `defun', any variable\n\
639 defined with `defvar' or `defconst', and in general the first\n\
640 argument of any expression that starts with `(def' in column zero\n\
641 is a tag.";
643 static const char *Lua_suffixes [] =
644 { "lua", "LUA", NULL };
645 static const char Lua_help [] =
646 "In Lua scripts, all functions are tags.";
648 static const char *Makefile_filenames [] =
649 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
650 static const char Makefile_help [] =
651 "In makefiles, targets are tags; additionally, variables are tags\n\
652 unless you specify `--no-globals'.";
654 static const char *Objc_suffixes [] =
655 { "lm", /* Objective lex file */
656 "m", /* Objective C file */
657 NULL };
658 static const char Objc_help [] =
659 "In Objective C code, tags include Objective C definitions for classes,\n\
660 class categories, methods and protocols. Tags for variables and\n\
661 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
662 (Use --help --lang=c --lang=objc --lang=java for full help.)";
664 static const char *Pascal_suffixes [] =
665 { "p", "pas", NULL };
666 static const char Pascal_help [] =
667 "In Pascal code, the tags are the functions and procedures defined\n\
668 in the file.";
669 /* " // this is for working around an Emacs highlighting bug... */
671 static const char *Perl_suffixes [] =
672 { "pl", "pm", NULL };
673 static const char *Perl_interpreters [] =
674 { "perl", "@PERL@", NULL };
675 static const char Perl_help [] =
676 "In Perl code, the tags are the packages, subroutines and variables\n\
677 defined by the `package', `sub', `my' and `local' keywords. Use\n\
678 `--globals' if you want to tag global variables. Tags for\n\
679 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
680 defined in the default package is `main::SUB'.";
682 static const char *PHP_suffixes [] =
683 { "php", "php3", "php4", NULL };
684 static const char PHP_help [] =
685 "In PHP code, tags are functions, classes and defines. Unless you use\n\
686 the `--no-members' option, vars are tags too.";
688 static const char *plain_C_suffixes [] =
689 { "pc", /* Pro*C file */
690 NULL };
692 static const char *PS_suffixes [] =
693 { "ps", "psw", NULL }; /* .psw is for PSWrap */
694 static const char PS_help [] =
695 "In PostScript code, the tags are the functions.";
697 static const char *Prolog_suffixes [] =
698 { "prolog", NULL };
699 static const char Prolog_help [] =
700 "In Prolog code, tags are predicates and rules at the beginning of\n\
701 line.";
703 static const char *Python_suffixes [] =
704 { "py", NULL };
705 static const char Python_help [] =
706 "In Python code, `def' or `class' at the beginning of a line\n\
707 generate a tag.";
709 /* Can't do the `SCM' or `scm' prefix with a version number. */
710 static const char *Scheme_suffixes [] =
711 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
712 static const char Scheme_help [] =
713 "In Scheme code, tags include anything defined with `def' or with a\n\
714 construct whose name starts with `def'. They also include\n\
715 variables set with `set!' at top level in the file.";
717 static const char *TeX_suffixes [] =
718 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
719 static const char TeX_help [] =
720 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
721 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
722 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
723 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
724 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
726 Other commands can be specified by setting the environment variable\n\
727 `TEXTAGS' to a colon-separated list like, for example,\n\
728 TEXTAGS=\"mycommand:myothercommand\".";
731 static const char *Texinfo_suffixes [] =
732 { "texi", "texinfo", "txi", NULL };
733 static const char Texinfo_help [] =
734 "for texinfo files, lines starting with @node are tagged.";
736 static const char *Yacc_suffixes [] =
737 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
738 static const char Yacc_help [] =
739 "In Bison or Yacc input files, each rule defines as a tag the\n\
740 nonterminal it constructs. The portions of the file that contain\n\
741 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
742 for full help).";
744 static const char auto_help [] =
745 "`auto' is not a real language, it indicates to use\n\
746 a default language for files base on file name suffix and file contents.";
748 static const char none_help [] =
749 "`none' is not a real language, it indicates to only do\n\
750 regexp processing on files.";
752 static const char no_lang_help [] =
753 "No detailed help available for this language.";
757 * Table of languages.
759 * It is ok for a given function to be listed under more than one
760 * name. I just didn't.
763 static language lang_names [] =
765 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
766 { "asm", Asm_help, Asm_labels, Asm_suffixes },
767 { "c", default_C_help, default_C_entries, default_C_suffixes },
768 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
769 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
770 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
771 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
772 { "forth", Forth_help, Forth_words, Forth_suffixes },
773 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
774 { "html", HTML_help, HTML_labels, HTML_suffixes },
775 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
776 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
777 { "lua", Lua_help, Lua_functions, Lua_suffixes },
778 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
779 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
780 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
781 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
782 { "php", PHP_help, PHP_functions, PHP_suffixes },
783 { "postscript",PS_help, PS_functions, PS_suffixes },
784 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
785 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
786 { "python", Python_help, Python_functions, Python_suffixes },
787 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
788 { "tex", TeX_help, TeX_commands, TeX_suffixes },
789 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
790 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
791 { "auto", auto_help }, /* default guessing scheme */
792 { "none", none_help, just_read_file }, /* regexp matching only */
793 { NULL } /* end of list */
797 static void
798 print_language_names (void)
800 language *lang;
801 const char **name, **ext;
803 puts ("\nThese are the currently supported languages, along with the\n\
804 default file names and dot suffixes:");
805 for (lang = lang_names; lang->name != NULL; lang++)
807 printf (" %-*s", 10, lang->name);
808 if (lang->filenames != NULL)
809 for (name = lang->filenames; *name != NULL; name++)
810 printf (" %s", *name);
811 if (lang->suffixes != NULL)
812 for (ext = lang->suffixes; *ext != NULL; ext++)
813 printf (" .%s", *ext);
814 puts ("");
816 puts ("where `auto' means use default language for files based on file\n\
817 name suffix, and `none' means only do regexp processing on files.\n\
818 If no language is specified and no matching suffix is found,\n\
819 the first line of the file is read for a sharp-bang (#!) sequence\n\
820 followed by the name of an interpreter. If no such sequence is found,\n\
821 Fortran is tried first; if no tags are found, C is tried next.\n\
822 When parsing any C file, a \"class\" or \"template\" keyword\n\
823 switches to C++.");
824 puts ("Compressed files are supported using gzip, bzip2, and xz.\n\
826 For detailed help on a given language use, for example,\n\
827 etags --help --lang=ada.");
830 #ifndef EMACS_NAME
831 # define EMACS_NAME "standalone"
832 #endif
833 #ifndef VERSION
834 # define VERSION "17.38.1.4"
835 #endif
836 static void
837 print_version (void)
839 /* Makes it easier to update automatically. */
840 char emacs_copyright[] = "Copyright (C) 2012 Free Software Foundation, Inc.";
842 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
843 puts (emacs_copyright);
844 puts ("This program is distributed under the terms in ETAGS.README");
846 exit (EXIT_SUCCESS);
849 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
850 # define PRINT_UNDOCUMENTED_OPTIONS_HELP FALSE
851 #endif
853 static void
854 print_help (argument *argbuffer)
856 bool help_for_lang = FALSE;
858 for (; argbuffer->arg_type != at_end; argbuffer++)
859 if (argbuffer->arg_type == at_language)
861 if (help_for_lang)
862 puts ("");
863 puts (argbuffer->lang->help);
864 help_for_lang = TRUE;
867 if (help_for_lang)
868 exit (EXIT_SUCCESS);
870 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
872 These are the options accepted by %s.\n", progname, progname);
873 if (NO_LONG_OPTIONS)
874 puts ("WARNING: long option names do not work with this executable,\n\
875 as it is not linked with GNU getopt.");
876 else
877 puts ("You may use unambiguous abbreviations for the long option names.");
878 puts (" A - as file name means read names from stdin (one per line).\n\
879 Absolute names are stored in the output file as they are.\n\
880 Relative ones are stored relative to the output file's directory.\n");
882 puts ("-a, --append\n\
883 Append tag entries to existing tags file.");
885 puts ("--packages-only\n\
886 For Ada files, only generate tags for packages.");
888 if (CTAGS)
889 puts ("-B, --backward-search\n\
890 Write the search commands for the tag entries using '?', the\n\
891 backward-search command instead of '/', the forward-search command.");
893 /* This option is mostly obsolete, because etags can now automatically
894 detect C++. Retained for backward compatibility and for debugging and
895 experimentation. In principle, we could want to tag as C++ even
896 before any "class" or "template" keyword.
897 puts ("-C, --c++\n\
898 Treat files whose name suffix defaults to C language as C++ files.");
901 puts ("--declarations\n\
902 In C and derived languages, create tags for function declarations,");
903 if (CTAGS)
904 puts ("\tand create tags for extern variables if --globals is used.");
905 else
906 puts
907 ("\tand create tags for extern variables unless --no-globals is used.");
909 if (CTAGS)
910 puts ("-d, --defines\n\
911 Create tag entries for C #define constants and enum constants, too.");
912 else
913 puts ("-D, --no-defines\n\
914 Don't create tag entries for C #define constants and enum constants.\n\
915 This makes the tags file smaller.");
917 if (!CTAGS)
918 puts ("-i FILE, --include=FILE\n\
919 Include a note in tag file indicating that, when searching for\n\
920 a tag, one should also consult the tags file FILE after\n\
921 checking the current file.");
923 puts ("-l LANG, --language=LANG\n\
924 Force the following files to be considered as written in the\n\
925 named language up to the next --language=LANG option.");
927 if (CTAGS)
928 puts ("--globals\n\
929 Create tag entries for global variables in some languages.");
930 else
931 puts ("--no-globals\n\
932 Do not create tag entries for global variables in some\n\
933 languages. This makes the tags file smaller.");
935 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
936 puts ("--no-line-directive\n\
937 Ignore #line preprocessor directives in C and derived languages.");
939 if (CTAGS)
940 puts ("--members\n\
941 Create tag entries for members of structures in some languages.");
942 else
943 puts ("--no-members\n\
944 Do not create tag entries for members of structures\n\
945 in some languages.");
947 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
948 Make a tag for each line matching a regular expression pattern\n\
949 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
950 files only. REGEXFILE is a file containing one REGEXP per line.\n\
951 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
952 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
953 puts (" If TAGNAME/ is present, the tags created are named.\n\
954 For example Tcl named tags can be created with:\n\
955 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
956 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
957 `m' means to allow multi-line matches, `s' implies `m' and\n\
958 causes dot to match any character, including newline.");
960 puts ("-R, --no-regex\n\
961 Don't create tags from regexps for the following files.");
963 puts ("-I, --ignore-indentation\n\
964 In C and C++ do not assume that a closing brace in the first\n\
965 column is the final brace of a function or structure definition.");
967 puts ("-o FILE, --output=FILE\n\
968 Write the tags to FILE.");
970 puts ("--parse-stdin=NAME\n\
971 Read from standard input and record tags as belonging to file NAME.");
973 if (CTAGS)
975 puts ("-t, --typedefs\n\
976 Generate tag entries for C and Ada typedefs.");
977 puts ("-T, --typedefs-and-c++\n\
978 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
979 and C++ member functions.");
982 if (CTAGS)
983 puts ("-u, --update\n\
984 Update the tag entries for the given files, leaving tag\n\
985 entries for other files in place. Currently, this is\n\
986 implemented by deleting the existing entries for the given\n\
987 files and then rewriting the new entries at the end of the\n\
988 tags file. It is often faster to simply rebuild the entire\n\
989 tag file than to use this.");
991 if (CTAGS)
993 puts ("-v, --vgrind\n\
994 Print on the standard output an index of items intended for\n\
995 human consumption, similar to the output of vgrind. The index\n\
996 is sorted, and gives the page number of each item.");
998 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
999 puts ("-w, --no-duplicates\n\
1000 Do not create duplicate tag entries, for compatibility with\n\
1001 traditional ctags.");
1003 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1004 puts ("-w, --no-warn\n\
1005 Suppress warning messages about duplicate tag entries.");
1007 puts ("-x, --cxref\n\
1008 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
1009 The output uses line numbers instead of page numbers, but\n\
1010 beyond that the differences are cosmetic; try both to see\n\
1011 which you like.");
1014 puts ("-V, --version\n\
1015 Print the version of the program.\n\
1016 -h, --help\n\
1017 Print this help message.\n\
1018 Followed by one or more `--language' options prints detailed\n\
1019 help about tag generation for the specified languages.");
1021 print_language_names ();
1023 puts ("");
1024 puts ("Report bugs to bug-gnu-emacs@gnu.org");
1026 exit (EXIT_SUCCESS);
1031 main (int argc, char **argv)
1033 int i;
1034 unsigned int nincluded_files;
1035 char **included_files;
1036 argument *argbuffer;
1037 int current_arg, file_count;
1038 linebuffer filename_lb;
1039 bool help_asked = FALSE;
1040 ptrdiff_t len;
1041 char *optstring;
1042 int opt;
1045 #ifdef DOS_NT
1046 _fmode = O_BINARY; /* all of files are treated as binary files */
1047 #endif /* DOS_NT */
1049 progname = argv[0];
1050 nincluded_files = 0;
1051 included_files = xnew (argc, char *);
1052 current_arg = 0;
1053 file_count = 0;
1055 /* Allocate enough no matter what happens. Overkill, but each one
1056 is small. */
1057 argbuffer = xnew (argc, argument);
1060 * Always find typedefs and structure tags.
1061 * Also default to find macro constants, enum constants, struct
1062 * members and global variables. Do it for both etags and ctags.
1064 typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1065 globals = members = TRUE;
1067 /* When the optstring begins with a '-' getopt_long does not rearrange the
1068 non-options arguments to be at the end, but leaves them alone. */
1069 optstring = concat (NO_LONG_OPTIONS ? "" : "-",
1070 "ac:Cf:Il:o:r:RSVhH",
1071 (CTAGS) ? "BxdtTuvw" : "Di:");
1073 while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1074 switch (opt)
1076 case 0:
1077 /* If getopt returns 0, then it has already processed a
1078 long-named option. We should do nothing. */
1079 break;
1081 case 1:
1082 /* This means that a file name has been seen. Record it. */
1083 argbuffer[current_arg].arg_type = at_filename;
1084 argbuffer[current_arg].what = optarg;
1085 len = strlen (optarg);
1086 if (whatlen_max < len)
1087 whatlen_max = len;
1088 ++current_arg;
1089 ++file_count;
1090 break;
1092 case STDIN:
1093 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1094 argbuffer[current_arg].arg_type = at_stdin;
1095 argbuffer[current_arg].what = optarg;
1096 len = strlen (optarg);
1097 if (whatlen_max < len)
1098 whatlen_max = len;
1099 ++current_arg;
1100 ++file_count;
1101 if (parsing_stdin)
1102 fatal ("cannot parse standard input more than once", (char *)NULL);
1103 parsing_stdin = TRUE;
1104 break;
1106 /* Common options. */
1107 case 'a': append_to_tagfile = TRUE; break;
1108 case 'C': cplusplus = TRUE; break;
1109 case 'f': /* for compatibility with old makefiles */
1110 case 'o':
1111 if (tagfile)
1113 error ("-o option may only be given once.");
1114 suggest_asking_for_help ();
1115 /* NOTREACHED */
1117 tagfile = optarg;
1118 break;
1119 case 'I':
1120 case 'S': /* for backward compatibility */
1121 ignoreindent = TRUE;
1122 break;
1123 case 'l':
1125 language *lang = get_language_from_langname (optarg);
1126 if (lang != NULL)
1128 argbuffer[current_arg].lang = lang;
1129 argbuffer[current_arg].arg_type = at_language;
1130 ++current_arg;
1133 break;
1134 case 'c':
1135 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1136 optarg = concat (optarg, "i", ""); /* memory leak here */
1137 /* FALLTHRU */
1138 case 'r':
1139 argbuffer[current_arg].arg_type = at_regexp;
1140 argbuffer[current_arg].what = optarg;
1141 len = strlen (optarg);
1142 if (whatlen_max < len)
1143 whatlen_max = len;
1144 ++current_arg;
1145 break;
1146 case 'R':
1147 argbuffer[current_arg].arg_type = at_regexp;
1148 argbuffer[current_arg].what = NULL;
1149 ++current_arg;
1150 break;
1151 case 'V':
1152 print_version ();
1153 break;
1154 case 'h':
1155 case 'H':
1156 help_asked = TRUE;
1157 break;
1159 /* Etags options */
1160 case 'D': constantypedefs = FALSE; break;
1161 case 'i': included_files[nincluded_files++] = optarg; break;
1163 /* Ctags options. */
1164 case 'B': searchar = '?'; break;
1165 case 'd': constantypedefs = TRUE; break;
1166 case 't': typedefs = TRUE; break;
1167 case 'T': typedefs = typedefs_or_cplusplus = TRUE; break;
1168 case 'u': update = TRUE; break;
1169 case 'v': vgrind_style = TRUE; /*FALLTHRU*/
1170 case 'x': cxref_style = TRUE; break;
1171 case 'w': no_warnings = TRUE; break;
1172 default:
1173 suggest_asking_for_help ();
1174 /* NOTREACHED */
1177 /* No more options. Store the rest of arguments. */
1178 for (; optind < argc; optind++)
1180 argbuffer[current_arg].arg_type = at_filename;
1181 argbuffer[current_arg].what = argv[optind];
1182 len = strlen (argv[optind]);
1183 if (whatlen_max < len)
1184 whatlen_max = len;
1185 ++current_arg;
1186 ++file_count;
1189 argbuffer[current_arg].arg_type = at_end;
1191 if (help_asked)
1192 print_help (argbuffer);
1193 /* NOTREACHED */
1195 if (nincluded_files == 0 && file_count == 0)
1197 error ("no input files specified.");
1198 suggest_asking_for_help ();
1199 /* NOTREACHED */
1202 if (tagfile == NULL)
1203 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1204 cwd = etags_getcwd (); /* the current working directory */
1205 if (cwd[strlen (cwd) - 1] != '/')
1207 char *oldcwd = cwd;
1208 cwd = concat (oldcwd, "/", "");
1209 free (oldcwd);
1212 /* Compute base directory for relative file names. */
1213 if (streq (tagfile, "-")
1214 || strneq (tagfile, "/dev/", 5))
1215 tagfiledir = cwd; /* relative file names are relative to cwd */
1216 else
1218 canonicalize_filename (tagfile);
1219 tagfiledir = absolute_dirname (tagfile, cwd);
1222 init (); /* set up boolean "functions" */
1224 linebuffer_init (&lb);
1225 linebuffer_init (&filename_lb);
1226 linebuffer_init (&filebuf);
1227 linebuffer_init (&token_name);
1229 if (!CTAGS)
1231 if (streq (tagfile, "-"))
1233 tagf = stdout;
1234 #ifdef DOS_NT
1235 /* Switch redirected `stdout' to binary mode (setting `_fmode'
1236 doesn't take effect until after `stdout' is already open). */
1237 if (!isatty (fileno (stdout)))
1238 setmode (fileno (stdout), O_BINARY);
1239 #endif /* DOS_NT */
1241 else
1242 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1243 if (tagf == NULL)
1244 pfatal (tagfile);
1248 * Loop through files finding functions.
1250 for (i = 0; i < current_arg; i++)
1252 static language *lang; /* non-NULL if language is forced */
1253 char *this_file;
1255 switch (argbuffer[i].arg_type)
1257 case at_language:
1258 lang = argbuffer[i].lang;
1259 break;
1260 case at_regexp:
1261 analyse_regex (argbuffer[i].what);
1262 break;
1263 case at_filename:
1264 this_file = argbuffer[i].what;
1265 /* Input file named "-" means read file names from stdin
1266 (one per line) and use them. */
1267 if (streq (this_file, "-"))
1269 if (parsing_stdin)
1270 fatal ("cannot parse standard input AND read file names from it",
1271 (char *)NULL);
1272 while (readline_internal (&filename_lb, stdin) > 0)
1273 process_file_name (filename_lb.buffer, lang);
1275 else
1276 process_file_name (this_file, lang);
1277 break;
1278 case at_stdin:
1279 this_file = argbuffer[i].what;
1280 process_file (stdin, this_file, lang);
1281 break;
1285 free_regexps ();
1286 free (lb.buffer);
1287 free (filebuf.buffer);
1288 free (token_name.buffer);
1290 if (!CTAGS || cxref_style)
1292 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1293 put_entries (nodehead);
1294 free_tree (nodehead);
1295 nodehead = NULL;
1296 if (!CTAGS)
1298 fdesc *fdp;
1300 /* Output file entries that have no tags. */
1301 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1302 if (!fdp->written)
1303 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1305 while (nincluded_files-- > 0)
1306 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1308 if (fclose (tagf) == EOF)
1309 pfatal (tagfile);
1312 exit (EXIT_SUCCESS);
1315 /* From here on, we are in (CTAGS && !cxref_style) */
1316 if (update)
1318 char *cmd =
1319 xmalloc (strlen (tagfile) + whatlen_max +
1320 sizeof "mv..OTAGS;fgrep -v '\t\t' OTAGS >;rm OTAGS");
1321 for (i = 0; i < current_arg; ++i)
1323 switch (argbuffer[i].arg_type)
1325 case at_filename:
1326 case at_stdin:
1327 break;
1328 default:
1329 continue; /* the for loop */
1331 strcpy (cmd, "mv ");
1332 strcat (cmd, tagfile);
1333 strcat (cmd, " OTAGS;fgrep -v '\t");
1334 strcat (cmd, argbuffer[i].what);
1335 strcat (cmd, "\t' OTAGS >");
1336 strcat (cmd, tagfile);
1337 strcat (cmd, ";rm OTAGS");
1338 if (system (cmd) != EXIT_SUCCESS)
1339 fatal ("failed to execute shell command", (char *)NULL);
1341 free (cmd);
1342 append_to_tagfile = TRUE;
1345 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1346 if (tagf == NULL)
1347 pfatal (tagfile);
1348 put_entries (nodehead); /* write all the tags (CTAGS) */
1349 free_tree (nodehead);
1350 nodehead = NULL;
1351 if (fclose (tagf) == EOF)
1352 pfatal (tagfile);
1354 if (CTAGS)
1355 if (append_to_tagfile || update)
1357 char *cmd = xmalloc (2 * strlen (tagfile) + sizeof "sort -u -o..");
1358 /* Maybe these should be used:
1359 setenv ("LC_COLLATE", "C", 1);
1360 setenv ("LC_ALL", "C", 1); */
1361 strcpy (cmd, "sort -u -o ");
1362 strcat (cmd, tagfile);
1363 strcat (cmd, " ");
1364 strcat (cmd, tagfile);
1365 exit (system (cmd));
1367 return EXIT_SUCCESS;
1372 * Return a compressor given the file name. If EXTPTR is non-zero,
1373 * return a pointer into FILE where the compressor-specific
1374 * extension begins. If no compressor is found, NULL is returned
1375 * and EXTPTR is not significant.
1376 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1378 static compressor *
1379 get_compressor_from_suffix (char *file, char **extptr)
1381 compressor *compr;
1382 char *slash, *suffix;
1384 /* File has been processed by canonicalize_filename,
1385 so we don't need to consider backslashes on DOS_NT. */
1386 slash = etags_strrchr (file, '/');
1387 suffix = etags_strrchr (file, '.');
1388 if (suffix == NULL || suffix < slash)
1389 return NULL;
1390 if (extptr != NULL)
1391 *extptr = suffix;
1392 suffix += 1;
1393 /* Let those poor souls who live with DOS 8+3 file name limits get
1394 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1395 Only the first do loop is run if not MSDOS */
1398 for (compr = compressors; compr->suffix != NULL; compr++)
1399 if (streq (compr->suffix, suffix))
1400 return compr;
1401 if (!MSDOS)
1402 break; /* do it only once: not really a loop */
1403 if (extptr != NULL)
1404 *extptr = ++suffix;
1405 } while (*suffix != '\0');
1406 return NULL;
1412 * Return a language given the name.
1414 static language *
1415 get_language_from_langname (const char *name)
1417 language *lang;
1419 if (name == NULL)
1420 error ("empty language name");
1421 else
1423 for (lang = lang_names; lang->name != NULL; lang++)
1424 if (streq (name, lang->name))
1425 return lang;
1426 error ("unknown language \"%s\"", name);
1429 return NULL;
1434 * Return a language given the interpreter name.
1436 static language *
1437 get_language_from_interpreter (char *interpreter)
1439 language *lang;
1440 const char **iname;
1442 if (interpreter == NULL)
1443 return NULL;
1444 for (lang = lang_names; lang->name != NULL; lang++)
1445 if (lang->interpreters != NULL)
1446 for (iname = lang->interpreters; *iname != NULL; iname++)
1447 if (streq (*iname, interpreter))
1448 return lang;
1450 return NULL;
1456 * Return a language given the file name.
1458 static language *
1459 get_language_from_filename (char *file, int case_sensitive)
1461 language *lang;
1462 const char **name, **ext, *suffix;
1464 /* Try whole file name first. */
1465 for (lang = lang_names; lang->name != NULL; lang++)
1466 if (lang->filenames != NULL)
1467 for (name = lang->filenames; *name != NULL; name++)
1468 if ((case_sensitive)
1469 ? streq (*name, file)
1470 : strcaseeq (*name, file))
1471 return lang;
1473 /* If not found, try suffix after last dot. */
1474 suffix = etags_strrchr (file, '.');
1475 if (suffix == NULL)
1476 return NULL;
1477 suffix += 1;
1478 for (lang = lang_names; lang->name != NULL; lang++)
1479 if (lang->suffixes != NULL)
1480 for (ext = lang->suffixes; *ext != NULL; ext++)
1481 if ((case_sensitive)
1482 ? streq (*ext, suffix)
1483 : strcaseeq (*ext, suffix))
1484 return lang;
1485 return NULL;
1490 * This routine is called on each file argument.
1492 static void
1493 process_file_name (char *file, language *lang)
1495 struct stat stat_buf;
1496 FILE *inf;
1497 fdesc *fdp;
1498 compressor *compr;
1499 char *compressed_name, *uncompressed_name;
1500 char *ext, *real_name;
1501 int retval;
1503 canonicalize_filename (file);
1504 if (streq (file, tagfile) && !streq (tagfile, "-"))
1506 error ("skipping inclusion of %s in self.", file);
1507 return;
1509 if ((compr = get_compressor_from_suffix (file, &ext)) == NULL)
1511 compressed_name = NULL;
1512 real_name = uncompressed_name = savestr (file);
1514 else
1516 real_name = compressed_name = savestr (file);
1517 uncompressed_name = savenstr (file, ext - file);
1520 /* If the canonicalized uncompressed name
1521 has already been dealt with, skip it silently. */
1522 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1524 assert (fdp->infname != NULL);
1525 if (streq (uncompressed_name, fdp->infname))
1526 goto cleanup;
1529 if (stat (real_name, &stat_buf) != 0)
1531 /* Reset real_name and try with a different name. */
1532 real_name = NULL;
1533 if (compressed_name != NULL) /* try with the given suffix */
1535 if (stat (uncompressed_name, &stat_buf) == 0)
1536 real_name = uncompressed_name;
1538 else /* try all possible suffixes */
1540 for (compr = compressors; compr->suffix != NULL; compr++)
1542 compressed_name = concat (file, ".", compr->suffix);
1543 if (stat (compressed_name, &stat_buf) != 0)
1545 if (MSDOS)
1547 char *suf = compressed_name + strlen (file);
1548 size_t suflen = strlen (compr->suffix) + 1;
1549 for ( ; suf[1]; suf++, suflen--)
1551 memmove (suf, suf + 1, suflen);
1552 if (stat (compressed_name, &stat_buf) == 0)
1554 real_name = compressed_name;
1555 break;
1558 if (real_name != NULL)
1559 break;
1560 } /* MSDOS */
1561 free (compressed_name);
1562 compressed_name = NULL;
1564 else
1566 real_name = compressed_name;
1567 break;
1571 if (real_name == NULL)
1573 perror (file);
1574 goto cleanup;
1576 } /* try with a different name */
1578 if (!S_ISREG (stat_buf.st_mode))
1580 error ("skipping %s: it is not a regular file.", real_name);
1581 goto cleanup;
1583 if (real_name == compressed_name)
1585 char *cmd = concat (compr->command, " ", real_name);
1586 inf = (FILE *) popen (cmd, "r");
1587 free (cmd);
1589 else
1590 inf = fopen (real_name, "r");
1591 if (inf == NULL)
1593 perror (real_name);
1594 goto cleanup;
1597 process_file (inf, uncompressed_name, lang);
1599 if (real_name == compressed_name)
1600 retval = pclose (inf);
1601 else
1602 retval = fclose (inf);
1603 if (retval < 0)
1604 pfatal (file);
1606 cleanup:
1607 free (compressed_name);
1608 free (uncompressed_name);
1609 last_node = NULL;
1610 curfdp = NULL;
1611 return;
1614 static void
1615 process_file (FILE *fh, char *fn, language *lang)
1617 static const fdesc emptyfdesc;
1618 fdesc *fdp;
1620 /* Create a new input file description entry. */
1621 fdp = xnew (1, fdesc);
1622 *fdp = emptyfdesc;
1623 fdp->next = fdhead;
1624 fdp->infname = savestr (fn);
1625 fdp->lang = lang;
1626 fdp->infabsname = absolute_filename (fn, cwd);
1627 fdp->infabsdir = absolute_dirname (fn, cwd);
1628 if (filename_is_absolute (fn))
1630 /* An absolute file name. Canonicalize it. */
1631 fdp->taggedfname = absolute_filename (fn, NULL);
1633 else
1635 /* A file name relative to cwd. Make it relative
1636 to the directory of the tags file. */
1637 fdp->taggedfname = relative_filename (fn, tagfiledir);
1639 fdp->usecharno = TRUE; /* use char position when making tags */
1640 fdp->prop = NULL;
1641 fdp->written = FALSE; /* not written on tags file yet */
1643 fdhead = fdp;
1644 curfdp = fdhead; /* the current file description */
1646 find_entries (fh);
1648 /* If not Ctags, and if this is not metasource and if it contained no #line
1649 directives, we can write the tags and free all nodes pointing to
1650 curfdp. */
1651 if (!CTAGS
1652 && curfdp->usecharno /* no #line directives in this file */
1653 && !curfdp->lang->metasource)
1655 node *np, *prev;
1657 /* Look for the head of the sublist relative to this file. See add_node
1658 for the structure of the node tree. */
1659 prev = NULL;
1660 for (np = nodehead; np != NULL; prev = np, np = np->left)
1661 if (np->fdp == curfdp)
1662 break;
1664 /* If we generated tags for this file, write and delete them. */
1665 if (np != NULL)
1667 /* This is the head of the last sublist, if any. The following
1668 instructions depend on this being true. */
1669 assert (np->left == NULL);
1671 assert (fdhead == curfdp);
1672 assert (last_node->fdp == curfdp);
1673 put_entries (np); /* write tags for file curfdp->taggedfname */
1674 free_tree (np); /* remove the written nodes */
1675 if (prev == NULL)
1676 nodehead = NULL; /* no nodes left */
1677 else
1678 prev->left = NULL; /* delete the pointer to the sublist */
1684 * This routine sets up the boolean pseudo-functions which work
1685 * by setting boolean flags dependent upon the corresponding character.
1686 * Every char which is NOT in that string is not a white char. Therefore,
1687 * all of the array "_wht" is set to FALSE, and then the elements
1688 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1689 * of a char is TRUE if it is the string "white", else FALSE.
1691 static void
1692 init (void)
1694 register const char *sp;
1695 register int i;
1697 for (i = 0; i < CHARS; i++)
1698 iswhite (i) = notinname (i) = begtoken (i) = intoken (i) = endtoken (i) = FALSE;
1699 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1700 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1701 notinname ('\0') = notinname ('\n');
1702 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1703 begtoken ('\0') = begtoken ('\n');
1704 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1705 intoken ('\0') = intoken ('\n');
1706 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1707 endtoken ('\0') = endtoken ('\n');
1711 * This routine opens the specified file and calls the function
1712 * which finds the function and type definitions.
1714 static void
1715 find_entries (FILE *inf)
1717 char *cp;
1718 language *lang = curfdp->lang;
1719 Lang_function *parser = NULL;
1721 /* If user specified a language, use it. */
1722 if (lang != NULL && lang->function != NULL)
1724 parser = lang->function;
1727 /* Else try to guess the language given the file name. */
1728 if (parser == NULL)
1730 lang = get_language_from_filename (curfdp->infname, TRUE);
1731 if (lang != NULL && lang->function != NULL)
1733 curfdp->lang = lang;
1734 parser = lang->function;
1738 /* Else look for sharp-bang as the first two characters. */
1739 if (parser == NULL
1740 && readline_internal (&lb, inf) > 0
1741 && lb.len >= 2
1742 && lb.buffer[0] == '#'
1743 && lb.buffer[1] == '!')
1745 char *lp;
1747 /* Set lp to point at the first char after the last slash in the
1748 line or, if no slashes, at the first nonblank. Then set cp to
1749 the first successive blank and terminate the string. */
1750 lp = etags_strrchr (lb.buffer+2, '/');
1751 if (lp != NULL)
1752 lp += 1;
1753 else
1754 lp = skip_spaces (lb.buffer + 2);
1755 cp = skip_non_spaces (lp);
1756 *cp = '\0';
1758 if (strlen (lp) > 0)
1760 lang = get_language_from_interpreter (lp);
1761 if (lang != NULL && lang->function != NULL)
1763 curfdp->lang = lang;
1764 parser = lang->function;
1769 /* We rewind here, even if inf may be a pipe. We fail if the
1770 length of the first line is longer than the pipe block size,
1771 which is unlikely. */
1772 rewind (inf);
1774 /* Else try to guess the language given the case insensitive file name. */
1775 if (parser == NULL)
1777 lang = get_language_from_filename (curfdp->infname, FALSE);
1778 if (lang != NULL && lang->function != NULL)
1780 curfdp->lang = lang;
1781 parser = lang->function;
1785 /* Else try Fortran or C. */
1786 if (parser == NULL)
1788 node *old_last_node = last_node;
1790 curfdp->lang = get_language_from_langname ("fortran");
1791 find_entries (inf);
1793 if (old_last_node == last_node)
1794 /* No Fortran entries found. Try C. */
1796 /* We do not tag if rewind fails.
1797 Only the file name will be recorded in the tags file. */
1798 rewind (inf);
1799 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1800 find_entries (inf);
1802 return;
1805 if (!no_line_directive
1806 && curfdp->lang != NULL && curfdp->lang->metasource)
1807 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1808 file, or anyway we parsed a file that is automatically generated from
1809 this one. If this is the case, the bingo.c file contained #line
1810 directives that generated tags pointing to this file. Let's delete
1811 them all before parsing this file, which is the real source. */
1813 fdesc **fdpp = &fdhead;
1814 while (*fdpp != NULL)
1815 if (*fdpp != curfdp
1816 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1817 /* We found one of those! We must delete both the file description
1818 and all tags referring to it. */
1820 fdesc *badfdp = *fdpp;
1822 /* Delete the tags referring to badfdp->taggedfname
1823 that were obtained from badfdp->infname. */
1824 invalidate_nodes (badfdp, &nodehead);
1826 *fdpp = badfdp->next; /* remove the bad description from the list */
1827 free_fdesc (badfdp);
1829 else
1830 fdpp = &(*fdpp)->next; /* advance the list pointer */
1833 assert (parser != NULL);
1835 /* Generic initializations before reading from file. */
1836 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1838 /* Generic initializations before parsing file with readline. */
1839 lineno = 0; /* reset global line number */
1840 charno = 0; /* reset global char number */
1841 linecharno = 0; /* reset global char number of line start */
1843 parser (inf);
1845 regex_tag_multiline ();
1850 * Check whether an implicitly named tag should be created,
1851 * then call `pfnote'.
1852 * NAME is a string that is internally copied by this function.
1854 * TAGS format specification
1855 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1856 * The following is explained in some more detail in etc/ETAGS.EBNF.
1858 * make_tag creates tags with "implicit tag names" (unnamed tags)
1859 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1860 * 1. NAME does not contain any of the characters in NONAM;
1861 * 2. LINESTART contains name as either a rightmost, or rightmost but
1862 * one character, substring;
1863 * 3. the character, if any, immediately before NAME in LINESTART must
1864 * be a character in NONAM;
1865 * 4. the character, if any, immediately after NAME in LINESTART must
1866 * also be a character in NONAM.
1868 * The implementation uses the notinname() macro, which recognizes the
1869 * characters stored in the string `nonam'.
1870 * etags.el needs to use the same characters that are in NONAM.
1872 static void
1873 make_tag (const char *name, /* tag name, or NULL if unnamed */
1874 int namelen, /* tag length */
1875 int is_func, /* tag is a function */
1876 char *linestart, /* start of the line where tag is */
1877 int linelen, /* length of the line where tag is */
1878 int lno, /* line number */
1879 long int cno) /* character number */
1881 bool named = (name != NULL && namelen > 0);
1882 char *nname = NULL;
1884 if (!CTAGS && named) /* maybe set named to false */
1885 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1886 such that etags.el can guess a name from it. */
1888 int i;
1889 register const char *cp = name;
1891 for (i = 0; i < namelen; i++)
1892 if (notinname (*cp++))
1893 break;
1894 if (i == namelen) /* rule #1 */
1896 cp = linestart + linelen - namelen;
1897 if (notinname (linestart[linelen-1]))
1898 cp -= 1; /* rule #4 */
1899 if (cp >= linestart /* rule #2 */
1900 && (cp == linestart
1901 || notinname (cp[-1])) /* rule #3 */
1902 && strneq (name, cp, namelen)) /* rule #2 */
1903 named = FALSE; /* use implicit tag name */
1907 if (named)
1908 nname = savenstr (name, namelen);
1910 pfnote (nname, is_func, linestart, linelen, lno, cno);
1913 /* Record a tag. */
1914 static void
1915 pfnote (char *name, int is_func, char *linestart, int linelen, int lno, long int cno)
1916 /* tag name, or NULL if unnamed */
1917 /* tag is a function */
1918 /* start of the line where tag is */
1919 /* length of the line where tag is */
1920 /* line number */
1921 /* character number */
1923 register node *np;
1925 assert (name == NULL || name[0] != '\0');
1926 if (CTAGS && name == NULL)
1927 return;
1929 np = xnew (1, node);
1931 /* If ctags mode, change name "main" to M<thisfilename>. */
1932 if (CTAGS && !cxref_style && streq (name, "main"))
1934 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
1935 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
1936 fp = etags_strrchr (np->name, '.');
1937 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
1938 fp[0] = '\0';
1940 else
1941 np->name = name;
1942 np->valid = TRUE;
1943 np->been_warned = FALSE;
1944 np->fdp = curfdp;
1945 np->is_func = is_func;
1946 np->lno = lno;
1947 if (np->fdp->usecharno)
1948 /* Our char numbers are 0-base, because of C language tradition?
1949 ctags compatibility? old versions compatibility? I don't know.
1950 Anyway, since emacs's are 1-base we expect etags.el to take care
1951 of the difference. If we wanted to have 1-based numbers, we would
1952 uncomment the +1 below. */
1953 np->cno = cno /* + 1 */ ;
1954 else
1955 np->cno = invalidcharno;
1956 np->left = np->right = NULL;
1957 if (CTAGS && !cxref_style)
1959 if (strlen (linestart) < 50)
1960 np->regex = concat (linestart, "$", "");
1961 else
1962 np->regex = savenstr (linestart, 50);
1964 else
1965 np->regex = savenstr (linestart, linelen);
1967 add_node (np, &nodehead);
1971 * free_tree ()
1972 * recurse on left children, iterate on right children.
1974 static void
1975 free_tree (register node *np)
1977 while (np)
1979 register node *node_right = np->right;
1980 free_tree (np->left);
1981 free (np->name);
1982 free (np->regex);
1983 free (np);
1984 np = node_right;
1989 * free_fdesc ()
1990 * delete a file description
1992 static void
1993 free_fdesc (register fdesc *fdp)
1995 free (fdp->infname);
1996 free (fdp->infabsname);
1997 free (fdp->infabsdir);
1998 free (fdp->taggedfname);
1999 free (fdp->prop);
2000 free (fdp);
2004 * add_node ()
2005 * Adds a node to the tree of nodes. In etags mode, sort by file
2006 * name. In ctags mode, sort by tag name. Make no attempt at
2007 * balancing.
2009 * add_node is the only function allowed to add nodes, so it can
2010 * maintain state.
2012 static void
2013 add_node (node *np, node **cur_node_p)
2015 register int dif;
2016 register node *cur_node = *cur_node_p;
2018 if (cur_node == NULL)
2020 *cur_node_p = np;
2021 last_node = np;
2022 return;
2025 if (!CTAGS)
2026 /* Etags Mode */
2028 /* For each file name, tags are in a linked sublist on the right
2029 pointer. The first tags of different files are a linked list
2030 on the left pointer. last_node points to the end of the last
2031 used sublist. */
2032 if (last_node != NULL && last_node->fdp == np->fdp)
2034 /* Let's use the same sublist as the last added node. */
2035 assert (last_node->right == NULL);
2036 last_node->right = np;
2037 last_node = np;
2039 else if (cur_node->fdp == np->fdp)
2041 /* Scanning the list we found the head of a sublist which is
2042 good for us. Let's scan this sublist. */
2043 add_node (np, &cur_node->right);
2045 else
2046 /* The head of this sublist is not good for us. Let's try the
2047 next one. */
2048 add_node (np, &cur_node->left);
2049 } /* if ETAGS mode */
2051 else
2053 /* Ctags Mode */
2054 dif = strcmp (np->name, cur_node->name);
2057 * If this tag name matches an existing one, then
2058 * do not add the node, but maybe print a warning.
2060 if (no_duplicates && !dif)
2062 if (np->fdp == cur_node->fdp)
2064 if (!no_warnings)
2066 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2067 np->fdp->infname, lineno, np->name);
2068 fprintf (stderr, "Second entry ignored\n");
2071 else if (!cur_node->been_warned && !no_warnings)
2073 fprintf
2074 (stderr,
2075 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2076 np->fdp->infname, cur_node->fdp->infname, np->name);
2077 cur_node->been_warned = TRUE;
2079 return;
2082 /* Actually add the node */
2083 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2084 } /* if CTAGS mode */
2088 * invalidate_nodes ()
2089 * Scan the node tree and invalidate all nodes pointing to the
2090 * given file description (CTAGS case) or free them (ETAGS case).
2092 static void
2093 invalidate_nodes (fdesc *badfdp, node **npp)
2095 node *np = *npp;
2097 if (np == NULL)
2098 return;
2100 if (CTAGS)
2102 if (np->left != NULL)
2103 invalidate_nodes (badfdp, &np->left);
2104 if (np->fdp == badfdp)
2105 np->valid = FALSE;
2106 if (np->right != NULL)
2107 invalidate_nodes (badfdp, &np->right);
2109 else
2111 assert (np->fdp != NULL);
2112 if (np->fdp == badfdp)
2114 *npp = np->left; /* detach the sublist from the list */
2115 np->left = NULL; /* isolate it */
2116 free_tree (np); /* free it */
2117 invalidate_nodes (badfdp, npp);
2119 else
2120 invalidate_nodes (badfdp, &np->left);
2125 static int total_size_of_entries (node *);
2126 static int number_len (long) ATTRIBUTE_CONST;
2128 /* Length of a non-negative number's decimal representation. */
2129 static int
2130 number_len (long int num)
2132 int len = 1;
2133 while ((num /= 10) > 0)
2134 len += 1;
2135 return len;
2139 * Return total number of characters that put_entries will output for
2140 * the nodes in the linked list at the right of the specified node.
2141 * This count is irrelevant with etags.el since emacs 19.34 at least,
2142 * but is still supplied for backward compatibility.
2144 static int
2145 total_size_of_entries (register node *np)
2147 register int total = 0;
2149 for (; np != NULL; np = np->right)
2150 if (np->valid)
2152 total += strlen (np->regex) + 1; /* pat\177 */
2153 if (np->name != NULL)
2154 total += strlen (np->name) + 1; /* name\001 */
2155 total += number_len ((long) np->lno) + 1; /* lno, */
2156 if (np->cno != invalidcharno) /* cno */
2157 total += number_len (np->cno);
2158 total += 1; /* newline */
2161 return total;
2164 static void
2165 put_entries (register node *np)
2167 register char *sp;
2168 static fdesc *fdp = NULL;
2170 if (np == NULL)
2171 return;
2173 /* Output subentries that precede this one */
2174 if (CTAGS)
2175 put_entries (np->left);
2177 /* Output this entry */
2178 if (np->valid)
2180 if (!CTAGS)
2182 /* Etags mode */
2183 if (fdp != np->fdp)
2185 fdp = np->fdp;
2186 fprintf (tagf, "\f\n%s,%d\n",
2187 fdp->taggedfname, total_size_of_entries (np));
2188 fdp->written = TRUE;
2190 fputs (np->regex, tagf);
2191 fputc ('\177', tagf);
2192 if (np->name != NULL)
2194 fputs (np->name, tagf);
2195 fputc ('\001', tagf);
2197 fprintf (tagf, "%d,", np->lno);
2198 if (np->cno != invalidcharno)
2199 fprintf (tagf, "%ld", np->cno);
2200 fputs ("\n", tagf);
2202 else
2204 /* Ctags mode */
2205 if (np->name == NULL)
2206 error ("internal error: NULL name in ctags mode.");
2208 if (cxref_style)
2210 if (vgrind_style)
2211 fprintf (stdout, "%s %s %d\n",
2212 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2213 else
2214 fprintf (stdout, "%-16s %3d %-16s %s\n",
2215 np->name, np->lno, np->fdp->taggedfname, np->regex);
2217 else
2219 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2221 if (np->is_func)
2222 { /* function or #define macro with args */
2223 putc (searchar, tagf);
2224 putc ('^', tagf);
2226 for (sp = np->regex; *sp; sp++)
2228 if (*sp == '\\' || *sp == searchar)
2229 putc ('\\', tagf);
2230 putc (*sp, tagf);
2232 putc (searchar, tagf);
2234 else
2235 { /* anything else; text pattern inadequate */
2236 fprintf (tagf, "%d", np->lno);
2238 putc ('\n', tagf);
2241 } /* if this node contains a valid tag */
2243 /* Output subentries that follow this one */
2244 put_entries (np->right);
2245 if (!CTAGS)
2246 put_entries (np->left);
2250 /* C extensions. */
2251 #define C_EXT 0x00fff /* C extensions */
2252 #define C_PLAIN 0x00000 /* C */
2253 #define C_PLPL 0x00001 /* C++ */
2254 #define C_STAR 0x00003 /* C* */
2255 #define C_JAVA 0x00005 /* JAVA */
2256 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2257 #define YACC 0x10000 /* yacc file */
2260 * The C symbol tables.
2262 enum sym_type
2264 st_none,
2265 st_C_objprot, st_C_objimpl, st_C_objend,
2266 st_C_gnumacro,
2267 st_C_ignore, st_C_attribute,
2268 st_C_javastruct,
2269 st_C_operator,
2270 st_C_class, st_C_template,
2271 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2274 static unsigned int hash (const char *, unsigned int);
2275 static struct C_stab_entry * in_word_set (const char *, unsigned int);
2276 static enum sym_type C_symtype (char *, int, int);
2278 /* Feed stuff between (but not including) %[ and %] lines to:
2279 gperf -m 5
2281 %compare-strncmp
2282 %enum
2283 %struct-type
2284 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2286 if, 0, st_C_ignore
2287 for, 0, st_C_ignore
2288 while, 0, st_C_ignore
2289 switch, 0, st_C_ignore
2290 return, 0, st_C_ignore
2291 __attribute__, 0, st_C_attribute
2292 GTY, 0, st_C_attribute
2293 @interface, 0, st_C_objprot
2294 @protocol, 0, st_C_objprot
2295 @implementation,0, st_C_objimpl
2296 @end, 0, st_C_objend
2297 import, (C_JAVA & ~C_PLPL), st_C_ignore
2298 package, (C_JAVA & ~C_PLPL), st_C_ignore
2299 friend, C_PLPL, st_C_ignore
2300 extends, (C_JAVA & ~C_PLPL), st_C_javastruct
2301 implements, (C_JAVA & ~C_PLPL), st_C_javastruct
2302 interface, (C_JAVA & ~C_PLPL), st_C_struct
2303 class, 0, st_C_class
2304 namespace, C_PLPL, st_C_struct
2305 domain, C_STAR, st_C_struct
2306 union, 0, st_C_struct
2307 struct, 0, st_C_struct
2308 extern, 0, st_C_extern
2309 enum, 0, st_C_enum
2310 typedef, 0, st_C_typedef
2311 define, 0, st_C_define
2312 undef, 0, st_C_define
2313 operator, C_PLPL, st_C_operator
2314 template, 0, st_C_template
2315 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2316 DEFUN, 0, st_C_gnumacro
2317 SYSCALL, 0, st_C_gnumacro
2318 ENTRY, 0, st_C_gnumacro
2319 PSEUDO, 0, st_C_gnumacro
2320 # These are defined inside C functions, so currently they are not met.
2321 # EXFUN used in glibc, DEFVAR_* in emacs.
2322 #EXFUN, 0, st_C_gnumacro
2323 #DEFVAR_, 0, st_C_gnumacro
2325 and replace lines between %< and %> with its output, then:
2326 - remove the #if characterset check
2327 - make in_word_set static and not inline. */
2328 /*%<*/
2329 /* C code produced by gperf version 3.0.1 */
2330 /* Command-line: gperf -m 5 */
2331 /* Computed positions: -k'2-3' */
2333 struct C_stab_entry { const char *name; int c_ext; enum sym_type type; };
2334 /* maximum key range = 33, duplicates = 0 */
2336 static inline unsigned int
2337 hash (register const char *str, register unsigned int len)
2339 static unsigned char asso_values[] =
2341 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2342 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2343 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2344 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2345 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2346 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2347 35, 35, 35, 35, 35, 35, 35, 35, 35, 3,
2348 26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2349 35, 35, 35, 24, 0, 35, 35, 35, 35, 0,
2350 35, 35, 35, 35, 35, 1, 35, 16, 35, 6,
2351 23, 0, 0, 35, 22, 0, 35, 35, 5, 0,
2352 0, 15, 1, 35, 6, 35, 8, 19, 35, 16,
2353 4, 5, 35, 35, 35, 35, 35, 35, 35, 35,
2354 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2355 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2356 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2357 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2358 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2359 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2360 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2361 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2362 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2363 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2364 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2365 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2366 35, 35, 35, 35, 35, 35
2368 register int hval = len;
2370 switch (hval)
2372 default:
2373 hval += asso_values[(unsigned char)str[2]];
2374 /*FALLTHROUGH*/
2375 case 2:
2376 hval += asso_values[(unsigned char)str[1]];
2377 break;
2379 return hval;
2382 static struct C_stab_entry *
2383 in_word_set (register const char *str, register unsigned int len)
2385 enum
2387 TOTAL_KEYWORDS = 33,
2388 MIN_WORD_LENGTH = 2,
2389 MAX_WORD_LENGTH = 15,
2390 MIN_HASH_VALUE = 2,
2391 MAX_HASH_VALUE = 34
2394 static struct C_stab_entry wordlist[] =
2396 {""}, {""},
2397 {"if", 0, st_C_ignore},
2398 {"GTY", 0, st_C_attribute},
2399 {"@end", 0, st_C_objend},
2400 {"union", 0, st_C_struct},
2401 {"define", 0, st_C_define},
2402 {"import", (C_JAVA & ~C_PLPL), st_C_ignore},
2403 {"template", 0, st_C_template},
2404 {"operator", C_PLPL, st_C_operator},
2405 {"@interface", 0, st_C_objprot},
2406 {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct},
2407 {"friend", C_PLPL, st_C_ignore},
2408 {"typedef", 0, st_C_typedef},
2409 {"return", 0, st_C_ignore},
2410 {"@implementation",0, st_C_objimpl},
2411 {"@protocol", 0, st_C_objprot},
2412 {"interface", (C_JAVA & ~C_PLPL), st_C_struct},
2413 {"extern", 0, st_C_extern},
2414 {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct},
2415 {"struct", 0, st_C_struct},
2416 {"domain", C_STAR, st_C_struct},
2417 {"switch", 0, st_C_ignore},
2418 {"enum", 0, st_C_enum},
2419 {"for", 0, st_C_ignore},
2420 {"namespace", C_PLPL, st_C_struct},
2421 {"class", 0, st_C_class},
2422 {"while", 0, st_C_ignore},
2423 {"undef", 0, st_C_define},
2424 {"package", (C_JAVA & ~C_PLPL), st_C_ignore},
2425 {"__attribute__", 0, st_C_attribute},
2426 {"SYSCALL", 0, st_C_gnumacro},
2427 {"ENTRY", 0, st_C_gnumacro},
2428 {"PSEUDO", 0, st_C_gnumacro},
2429 {"DEFUN", 0, st_C_gnumacro}
2432 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2434 register int key = hash (str, len);
2436 if (key <= MAX_HASH_VALUE && key >= 0)
2438 register const char *s = wordlist[key].name;
2440 if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2441 return &wordlist[key];
2444 return 0;
2446 /*%>*/
2448 static enum sym_type
2449 C_symtype (char *str, int len, int c_ext)
2451 register struct C_stab_entry *se = in_word_set (str, len);
2453 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2454 return st_none;
2455 return se->type;
2460 * Ignoring __attribute__ ((list))
2462 static bool inattribute; /* looking at an __attribute__ construct */
2465 * C functions and variables are recognized using a simple
2466 * finite automaton. fvdef is its state variable.
2468 static enum
2470 fvnone, /* nothing seen */
2471 fdefunkey, /* Emacs DEFUN keyword seen */
2472 fdefunname, /* Emacs DEFUN name seen */
2473 foperator, /* func: operator keyword seen (cplpl) */
2474 fvnameseen, /* function or variable name seen */
2475 fstartlist, /* func: just after open parenthesis */
2476 finlist, /* func: in parameter list */
2477 flistseen, /* func: after parameter list */
2478 fignore, /* func: before open brace */
2479 vignore /* var-like: ignore until ';' */
2480 } fvdef;
2482 static bool fvextern; /* func or var: extern keyword seen; */
2485 * typedefs are recognized using a simple finite automaton.
2486 * typdef is its state variable.
2488 static enum
2490 tnone, /* nothing seen */
2491 tkeyseen, /* typedef keyword seen */
2492 ttypeseen, /* defined type seen */
2493 tinbody, /* inside typedef body */
2494 tend, /* just before typedef tag */
2495 tignore /* junk after typedef tag */
2496 } typdef;
2499 * struct-like structures (enum, struct and union) are recognized
2500 * using another simple finite automaton. `structdef' is its state
2501 * variable.
2503 static enum
2505 snone, /* nothing seen yet,
2506 or in struct body if bracelev > 0 */
2507 skeyseen, /* struct-like keyword seen */
2508 stagseen, /* struct-like tag seen */
2509 scolonseen /* colon seen after struct-like tag */
2510 } structdef;
2513 * When objdef is different from onone, objtag is the name of the class.
2515 static const char *objtag = "<uninited>";
2518 * Yet another little state machine to deal with preprocessor lines.
2520 static enum
2522 dnone, /* nothing seen */
2523 dsharpseen, /* '#' seen as first char on line */
2524 ddefineseen, /* '#' and 'define' seen */
2525 dignorerest /* ignore rest of line */
2526 } definedef;
2529 * State machine for Objective C protocols and implementations.
2530 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2532 static enum
2534 onone, /* nothing seen */
2535 oprotocol, /* @interface or @protocol seen */
2536 oimplementation, /* @implementations seen */
2537 otagseen, /* class name seen */
2538 oparenseen, /* parenthesis before category seen */
2539 ocatseen, /* category name seen */
2540 oinbody, /* in @implementation body */
2541 omethodsign, /* in @implementation body, after +/- */
2542 omethodtag, /* after method name */
2543 omethodcolon, /* after method colon */
2544 omethodparm, /* after method parameter */
2545 oignore /* wait for @end */
2546 } objdef;
2550 * Use this structure to keep info about the token read, and how it
2551 * should be tagged. Used by the make_C_tag function to build a tag.
2553 static struct tok
2555 char *line; /* string containing the token */
2556 int offset; /* where the token starts in LINE */
2557 int length; /* token length */
2559 The previous members can be used to pass strings around for generic
2560 purposes. The following ones specifically refer to creating tags. In this
2561 case the token contained here is the pattern that will be used to create a
2562 tag.
2564 bool valid; /* do not create a tag; the token should be
2565 invalidated whenever a state machine is
2566 reset prematurely */
2567 bool named; /* create a named tag */
2568 int lineno; /* source line number of tag */
2569 long linepos; /* source char number of tag */
2570 } token; /* latest token read */
2573 * Variables and functions for dealing with nested structures.
2574 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2576 static void pushclass_above (int, char *, int);
2577 static void popclass_above (int);
2578 static void write_classname (linebuffer *, const char *qualifier);
2580 static struct {
2581 char **cname; /* nested class names */
2582 int *bracelev; /* nested class brace level */
2583 int nl; /* class nesting level (elements used) */
2584 int size; /* length of the array */
2585 } cstack; /* stack for nested declaration tags */
2586 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2587 #define nestlev (cstack.nl)
2588 /* After struct keyword or in struct body, not inside a nested function. */
2589 #define instruct (structdef == snone && nestlev > 0 \
2590 && bracelev == cstack.bracelev[nestlev-1] + 1)
2592 static void
2593 pushclass_above (int bracelev, char *str, int len)
2595 int nl;
2597 popclass_above (bracelev);
2598 nl = cstack.nl;
2599 if (nl >= cstack.size)
2601 int size = cstack.size *= 2;
2602 xrnew (cstack.cname, size, char *);
2603 xrnew (cstack.bracelev, size, int);
2605 assert (nl == 0 || cstack.bracelev[nl-1] < bracelev);
2606 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2607 cstack.bracelev[nl] = bracelev;
2608 cstack.nl = nl + 1;
2611 static void
2612 popclass_above (int bracelev)
2614 int nl;
2616 for (nl = cstack.nl - 1;
2617 nl >= 0 && cstack.bracelev[nl] >= bracelev;
2618 nl--)
2620 free (cstack.cname[nl]);
2621 cstack.nl = nl;
2625 static void
2626 write_classname (linebuffer *cn, const char *qualifier)
2628 int i, len;
2629 int qlen = strlen (qualifier);
2631 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2633 len = 0;
2634 cn->len = 0;
2635 cn->buffer[0] = '\0';
2637 else
2639 len = strlen (cstack.cname[0]);
2640 linebuffer_setlen (cn, len);
2641 strcpy (cn->buffer, cstack.cname[0]);
2643 for (i = 1; i < cstack.nl; i++)
2645 char *s = cstack.cname[i];
2646 if (s == NULL)
2647 continue;
2648 linebuffer_setlen (cn, len + qlen + strlen (s));
2649 len += sprintf (cn->buffer + len, "%s%s", qualifier, s);
2654 static bool consider_token (char *, int, int, int *, int, int, bool *);
2655 static void make_C_tag (bool);
2658 * consider_token ()
2659 * checks to see if the current token is at the start of a
2660 * function or variable, or corresponds to a typedef, or
2661 * is a struct/union/enum tag, or #define, or an enum constant.
2663 * *IS_FUNC gets TRUE if the token is a function or #define macro
2664 * with args. C_EXTP points to which language we are looking at.
2666 * Globals
2667 * fvdef IN OUT
2668 * structdef IN OUT
2669 * definedef IN OUT
2670 * typdef IN OUT
2671 * objdef IN OUT
2674 static bool
2675 consider_token (register char *str, register int len, register int c, int *c_extp, int bracelev, int parlev, int *is_func_or_var)
2676 /* IN: token pointer */
2677 /* IN: token length */
2678 /* IN: first char after the token */
2679 /* IN, OUT: C extensions mask */
2680 /* IN: brace level */
2681 /* IN: parenthesis level */
2682 /* OUT: function or variable found */
2684 /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2685 structtype is the type of the preceding struct-like keyword, and
2686 structbracelev is the brace level where it has been seen. */
2687 static enum sym_type structtype;
2688 static int structbracelev;
2689 static enum sym_type toktype;
2692 toktype = C_symtype (str, len, *c_extp);
2695 * Skip __attribute__
2697 if (toktype == st_C_attribute)
2699 inattribute = TRUE;
2700 return FALSE;
2704 * Advance the definedef state machine.
2706 switch (definedef)
2708 case dnone:
2709 /* We're not on a preprocessor line. */
2710 if (toktype == st_C_gnumacro)
2712 fvdef = fdefunkey;
2713 return FALSE;
2715 break;
2716 case dsharpseen:
2717 if (toktype == st_C_define)
2719 definedef = ddefineseen;
2721 else
2723 definedef = dignorerest;
2725 return FALSE;
2726 case ddefineseen:
2728 * Make a tag for any macro, unless it is a constant
2729 * and constantypedefs is FALSE.
2731 definedef = dignorerest;
2732 *is_func_or_var = (c == '(');
2733 if (!*is_func_or_var && !constantypedefs)
2734 return FALSE;
2735 else
2736 return TRUE;
2737 case dignorerest:
2738 return FALSE;
2739 default:
2740 error ("internal error: definedef value.");
2744 * Now typedefs
2746 switch (typdef)
2748 case tnone:
2749 if (toktype == st_C_typedef)
2751 if (typedefs)
2752 typdef = tkeyseen;
2753 fvextern = FALSE;
2754 fvdef = fvnone;
2755 return FALSE;
2757 break;
2758 case tkeyseen:
2759 switch (toktype)
2761 case st_none:
2762 case st_C_class:
2763 case st_C_struct:
2764 case st_C_enum:
2765 typdef = ttypeseen;
2767 break;
2768 case ttypeseen:
2769 if (structdef == snone && fvdef == fvnone)
2771 fvdef = fvnameseen;
2772 return TRUE;
2774 break;
2775 case tend:
2776 switch (toktype)
2778 case st_C_class:
2779 case st_C_struct:
2780 case st_C_enum:
2781 return FALSE;
2783 return TRUE;
2786 switch (toktype)
2788 case st_C_javastruct:
2789 if (structdef == stagseen)
2790 structdef = scolonseen;
2791 return FALSE;
2792 case st_C_template:
2793 case st_C_class:
2794 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2795 && bracelev == 0
2796 && definedef == dnone && structdef == snone
2797 && typdef == tnone && fvdef == fvnone)
2798 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2799 if (toktype == st_C_template)
2800 break;
2801 /* FALLTHRU */
2802 case st_C_struct:
2803 case st_C_enum:
2804 if (parlev == 0
2805 && fvdef != vignore
2806 && (typdef == tkeyseen
2807 || (typedefs_or_cplusplus && structdef == snone)))
2809 structdef = skeyseen;
2810 structtype = toktype;
2811 structbracelev = bracelev;
2812 if (fvdef == fvnameseen)
2813 fvdef = fvnone;
2815 return FALSE;
2818 if (structdef == skeyseen)
2820 structdef = stagseen;
2821 return TRUE;
2824 if (typdef != tnone)
2825 definedef = dnone;
2827 /* Detect Objective C constructs. */
2828 switch (objdef)
2830 case onone:
2831 switch (toktype)
2833 case st_C_objprot:
2834 objdef = oprotocol;
2835 return FALSE;
2836 case st_C_objimpl:
2837 objdef = oimplementation;
2838 return FALSE;
2840 break;
2841 case oimplementation:
2842 /* Save the class tag for functions or variables defined inside. */
2843 objtag = savenstr (str, len);
2844 objdef = oinbody;
2845 return FALSE;
2846 case oprotocol:
2847 /* Save the class tag for categories. */
2848 objtag = savenstr (str, len);
2849 objdef = otagseen;
2850 *is_func_or_var = TRUE;
2851 return TRUE;
2852 case oparenseen:
2853 objdef = ocatseen;
2854 *is_func_or_var = TRUE;
2855 return TRUE;
2856 case oinbody:
2857 break;
2858 case omethodsign:
2859 if (parlev == 0)
2861 fvdef = fvnone;
2862 objdef = omethodtag;
2863 linebuffer_setlen (&token_name, len);
2864 memcpy (token_name.buffer, str, len);
2865 token_name.buffer[len] = '\0';
2866 return TRUE;
2868 return FALSE;
2869 case omethodcolon:
2870 if (parlev == 0)
2871 objdef = omethodparm;
2872 return FALSE;
2873 case omethodparm:
2874 if (parlev == 0)
2876 int oldlen = token_name.len;
2877 fvdef = fvnone;
2878 objdef = omethodtag;
2879 linebuffer_setlen (&token_name, oldlen + len);
2880 memcpy (token_name.buffer + oldlen, str, len);
2881 token_name.buffer[oldlen + len] = '\0';
2882 return TRUE;
2884 return FALSE;
2885 case oignore:
2886 if (toktype == st_C_objend)
2888 /* Memory leakage here: the string pointed by objtag is
2889 never released, because many tests would be needed to
2890 avoid breaking on incorrect input code. The amount of
2891 memory leaked here is the sum of the lengths of the
2892 class tags.
2893 free (objtag); */
2894 objdef = onone;
2896 return FALSE;
2899 /* A function, variable or enum constant? */
2900 switch (toktype)
2902 case st_C_extern:
2903 fvextern = TRUE;
2904 switch (fvdef)
2906 case finlist:
2907 case flistseen:
2908 case fignore:
2909 case vignore:
2910 break;
2911 default:
2912 fvdef = fvnone;
2914 return FALSE;
2915 case st_C_ignore:
2916 fvextern = FALSE;
2917 fvdef = vignore;
2918 return FALSE;
2919 case st_C_operator:
2920 fvdef = foperator;
2921 *is_func_or_var = TRUE;
2922 return TRUE;
2923 case st_none:
2924 if (constantypedefs
2925 && structdef == snone
2926 && structtype == st_C_enum && bracelev > structbracelev)
2927 return TRUE; /* enum constant */
2928 switch (fvdef)
2930 case fdefunkey:
2931 if (bracelev > 0)
2932 break;
2933 fvdef = fdefunname; /* GNU macro */
2934 *is_func_or_var = TRUE;
2935 return TRUE;
2936 case fvnone:
2937 switch (typdef)
2939 case ttypeseen:
2940 return FALSE;
2941 case tnone:
2942 if ((strneq (str, "asm", 3) && endtoken (str[3]))
2943 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
2945 fvdef = vignore;
2946 return FALSE;
2948 break;
2950 /* FALLTHRU */
2951 case fvnameseen:
2952 if (len >= 10 && strneq (str+len-10, "::operator", 10))
2954 if (*c_extp & C_AUTO) /* automatic detection of C++ */
2955 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2956 fvdef = foperator;
2957 *is_func_or_var = TRUE;
2958 return TRUE;
2960 if (bracelev > 0 && !instruct)
2961 break;
2962 fvdef = fvnameseen; /* function or variable */
2963 *is_func_or_var = TRUE;
2964 return TRUE;
2966 break;
2969 return FALSE;
2974 * C_entries often keeps pointers to tokens or lines which are older than
2975 * the line currently read. By keeping two line buffers, and switching
2976 * them at end of line, it is possible to use those pointers.
2978 static struct
2980 long linepos;
2981 linebuffer lb;
2982 } lbs[2];
2984 #define current_lb_is_new (newndx == curndx)
2985 #define switch_line_buffers() (curndx = 1 - curndx)
2987 #define curlb (lbs[curndx].lb)
2988 #define newlb (lbs[newndx].lb)
2989 #define curlinepos (lbs[curndx].linepos)
2990 #define newlinepos (lbs[newndx].linepos)
2992 #define plainc ((c_ext & C_EXT) == C_PLAIN)
2993 #define cplpl (c_ext & C_PLPL)
2994 #define cjava ((c_ext & C_JAVA) == C_JAVA)
2996 #define CNL_SAVE_DEFINEDEF() \
2997 do { \
2998 curlinepos = charno; \
2999 readline (&curlb, inf); \
3000 lp = curlb.buffer; \
3001 quotednl = FALSE; \
3002 newndx = curndx; \
3003 } while (0)
3005 #define CNL() \
3006 do { \
3007 CNL_SAVE_DEFINEDEF(); \
3008 if (savetoken.valid) \
3010 token = savetoken; \
3011 savetoken.valid = FALSE; \
3013 definedef = dnone; \
3014 } while (0)
3017 static void
3018 make_C_tag (int isfun)
3020 /* This function is never called when token.valid is FALSE, but
3021 we must protect against invalid input or internal errors. */
3022 if (token.valid)
3023 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3024 token.offset+token.length+1, token.lineno, token.linepos);
3025 else if (DEBUG)
3026 { /* this branch is optimized away if !DEBUG */
3027 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3028 token_name.len + 17, isfun, token.line,
3029 token.offset+token.length+1, token.lineno, token.linepos);
3030 error ("INVALID TOKEN");
3033 token.valid = FALSE;
3038 * C_entries ()
3039 * This routine finds functions, variables, typedefs,
3040 * #define's, enum constants and struct/union/enum definitions in
3041 * C syntax and adds them to the list.
3043 static void
3044 C_entries (int c_ext, FILE *inf)
3045 /* extension of C */
3046 /* input file */
3048 register char c; /* latest char read; '\0' for end of line */
3049 register char *lp; /* pointer one beyond the character `c' */
3050 int curndx, newndx; /* indices for current and new lb */
3051 register int tokoff; /* offset in line of start of current token */
3052 register int toklen; /* length of current token */
3053 const char *qualifier; /* string used to qualify names */
3054 int qlen; /* length of qualifier */
3055 int bracelev; /* current brace level */
3056 int bracketlev; /* current bracket level */
3057 int parlev; /* current parenthesis level */
3058 int attrparlev; /* __attribute__ parenthesis level */
3059 int templatelev; /* current template level */
3060 int typdefbracelev; /* bracelev where a typedef struct body begun */
3061 bool incomm, inquote, inchar, quotednl, midtoken;
3062 bool yacc_rules; /* in the rules part of a yacc file */
3063 struct tok savetoken = {0}; /* token saved during preprocessor handling */
3066 linebuffer_init (&lbs[0].lb);
3067 linebuffer_init (&lbs[1].lb);
3068 if (cstack.size == 0)
3070 cstack.size = (DEBUG) ? 1 : 4;
3071 cstack.nl = 0;
3072 cstack.cname = xnew (cstack.size, char *);
3073 cstack.bracelev = xnew (cstack.size, int);
3076 tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3077 curndx = newndx = 0;
3078 lp = curlb.buffer;
3079 *lp = 0;
3081 fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3082 structdef = snone; definedef = dnone; objdef = onone;
3083 yacc_rules = FALSE;
3084 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3085 token.valid = savetoken.valid = FALSE;
3086 bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3087 if (cjava)
3088 { qualifier = "."; qlen = 1; }
3089 else
3090 { qualifier = "::"; qlen = 2; }
3093 while (!feof (inf))
3095 c = *lp++;
3096 if (c == '\\')
3098 /* If we are at the end of the line, the next character is a
3099 '\0'; do not skip it, because it is what tells us
3100 to read the next line. */
3101 if (*lp == '\0')
3103 quotednl = TRUE;
3104 continue;
3106 lp++;
3107 c = ' ';
3109 else if (incomm)
3111 switch (c)
3113 case '*':
3114 if (*lp == '/')
3116 c = *lp++;
3117 incomm = FALSE;
3119 break;
3120 case '\0':
3121 /* Newlines inside comments do not end macro definitions in
3122 traditional cpp. */
3123 CNL_SAVE_DEFINEDEF ();
3124 break;
3126 continue;
3128 else if (inquote)
3130 switch (c)
3132 case '"':
3133 inquote = FALSE;
3134 break;
3135 case '\0':
3136 /* Newlines inside strings do not end macro definitions
3137 in traditional cpp, even though compilers don't
3138 usually accept them. */
3139 CNL_SAVE_DEFINEDEF ();
3140 break;
3142 continue;
3144 else if (inchar)
3146 switch (c)
3148 case '\0':
3149 /* Hmmm, something went wrong. */
3150 CNL ();
3151 /* FALLTHRU */
3152 case '\'':
3153 inchar = FALSE;
3154 break;
3156 continue;
3158 else switch (c)
3160 case '"':
3161 inquote = TRUE;
3162 if (bracketlev > 0)
3163 continue;
3164 if (inattribute)
3165 break;
3166 switch (fvdef)
3168 case fdefunkey:
3169 case fstartlist:
3170 case finlist:
3171 case fignore:
3172 case vignore:
3173 break;
3174 default:
3175 fvextern = FALSE;
3176 fvdef = fvnone;
3178 continue;
3179 case '\'':
3180 inchar = TRUE;
3181 if (bracketlev > 0)
3182 continue;
3183 if (inattribute)
3184 break;
3185 if (fvdef != finlist && fvdef != fignore && fvdef != vignore)
3187 fvextern = FALSE;
3188 fvdef = fvnone;
3190 continue;
3191 case '/':
3192 if (*lp == '*')
3194 incomm = TRUE;
3195 lp++;
3196 c = ' ';
3197 if (bracketlev > 0)
3198 continue;
3200 else if (/* cplpl && */ *lp == '/')
3202 c = '\0';
3204 break;
3205 case '%':
3206 if ((c_ext & YACC) && *lp == '%')
3208 /* Entering or exiting rules section in yacc file. */
3209 lp++;
3210 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3211 typdef = tnone; structdef = snone;
3212 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3213 bracelev = 0;
3214 yacc_rules = !yacc_rules;
3215 continue;
3217 else
3218 break;
3219 case '#':
3220 if (definedef == dnone)
3222 char *cp;
3223 bool cpptoken = TRUE;
3225 /* Look back on this line. If all blanks, or nonblanks
3226 followed by an end of comment, this is a preprocessor
3227 token. */
3228 for (cp = newlb.buffer; cp < lp-1; cp++)
3229 if (!iswhite (*cp))
3231 if (*cp == '*' && cp[1] == '/')
3233 cp++;
3234 cpptoken = TRUE;
3236 else
3237 cpptoken = FALSE;
3239 if (cpptoken)
3240 definedef = dsharpseen;
3241 } /* if (definedef == dnone) */
3242 continue;
3243 case '[':
3244 bracketlev++;
3245 continue;
3246 default:
3247 if (bracketlev > 0)
3249 if (c == ']')
3250 --bracketlev;
3251 else if (c == '\0')
3252 CNL_SAVE_DEFINEDEF ();
3253 continue;
3255 break;
3256 } /* switch (c) */
3259 /* Consider token only if some involved conditions are satisfied. */
3260 if (typdef != tignore
3261 && definedef != dignorerest
3262 && fvdef != finlist
3263 && templatelev == 0
3264 && (definedef != dnone
3265 || structdef != scolonseen)
3266 && !inattribute)
3268 if (midtoken)
3270 if (endtoken (c))
3272 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3273 /* This handles :: in the middle,
3274 but not at the beginning of an identifier.
3275 Also, space-separated :: is not recognized. */
3277 if (c_ext & C_AUTO) /* automatic detection of C++ */
3278 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3279 lp += 2;
3280 toklen += 2;
3281 c = lp[-1];
3282 goto still_in_token;
3284 else
3286 bool funorvar = FALSE;
3288 if (yacc_rules
3289 || consider_token (newlb.buffer + tokoff, toklen, c,
3290 &c_ext, bracelev, parlev,
3291 &funorvar))
3293 if (fvdef == foperator)
3295 char *oldlp = lp;
3296 lp = skip_spaces (lp-1);
3297 if (*lp != '\0')
3298 lp += 1;
3299 while (*lp != '\0'
3300 && !iswhite (*lp) && *lp != '(')
3301 lp += 1;
3302 c = *lp++;
3303 toklen += lp - oldlp;
3305 token.named = FALSE;
3306 if (!plainc
3307 && nestlev > 0 && definedef == dnone)
3308 /* in struct body */
3310 int len;
3311 write_classname (&token_name, qualifier);
3312 len = token_name.len;
3313 linebuffer_setlen (&token_name, len+qlen+toklen);
3314 sprintf (token_name.buffer + len, "%s%.*s",
3315 qualifier, toklen, newlb.buffer + tokoff);
3316 token.named = TRUE;
3318 else if (objdef == ocatseen)
3319 /* Objective C category */
3321 int len = strlen (objtag) + 2 + toklen;
3322 linebuffer_setlen (&token_name, len);
3323 sprintf (token_name.buffer, "%s(%.*s)",
3324 objtag, toklen, newlb.buffer + tokoff);
3325 token.named = TRUE;
3327 else if (objdef == omethodtag
3328 || objdef == omethodparm)
3329 /* Objective C method */
3331 token.named = TRUE;
3333 else if (fvdef == fdefunname)
3334 /* GNU DEFUN and similar macros */
3336 bool defun = (newlb.buffer[tokoff] == 'F');
3337 int off = tokoff;
3338 int len = toklen;
3340 /* Rewrite the tag so that emacs lisp DEFUNs
3341 can be found by their elisp name */
3342 if (defun)
3344 off += 1;
3345 len -= 1;
3347 linebuffer_setlen (&token_name, len);
3348 memcpy (token_name.buffer,
3349 newlb.buffer + off, len);
3350 token_name.buffer[len] = '\0';
3351 if (defun)
3352 while (--len >= 0)
3353 if (token_name.buffer[len] == '_')
3354 token_name.buffer[len] = '-';
3355 token.named = defun;
3357 else
3359 linebuffer_setlen (&token_name, toklen);
3360 memcpy (token_name.buffer,
3361 newlb.buffer + tokoff, toklen);
3362 token_name.buffer[toklen] = '\0';
3363 /* Name macros and members. */
3364 token.named = (structdef == stagseen
3365 || typdef == ttypeseen
3366 || typdef == tend
3367 || (funorvar
3368 && definedef == dignorerest)
3369 || (funorvar
3370 && definedef == dnone
3371 && structdef == snone
3372 && bracelev > 0));
3374 token.lineno = lineno;
3375 token.offset = tokoff;
3376 token.length = toklen;
3377 token.line = newlb.buffer;
3378 token.linepos = newlinepos;
3379 token.valid = TRUE;
3381 if (definedef == dnone
3382 && (fvdef == fvnameseen
3383 || fvdef == foperator
3384 || structdef == stagseen
3385 || typdef == tend
3386 || typdef == ttypeseen
3387 || objdef != onone))
3389 if (current_lb_is_new)
3390 switch_line_buffers ();
3392 else if (definedef != dnone
3393 || fvdef == fdefunname
3394 || instruct)
3395 make_C_tag (funorvar);
3397 else /* not yacc and consider_token failed */
3399 if (inattribute && fvdef == fignore)
3401 /* We have just met __attribute__ after a
3402 function parameter list: do not tag the
3403 function again. */
3404 fvdef = fvnone;
3407 midtoken = FALSE;
3409 } /* if (endtoken (c)) */
3410 else if (intoken (c))
3411 still_in_token:
3413 toklen++;
3414 continue;
3416 } /* if (midtoken) */
3417 else if (begtoken (c))
3419 switch (definedef)
3421 case dnone:
3422 switch (fvdef)
3424 case fstartlist:
3425 /* This prevents tagging fb in
3426 void (__attribute__((noreturn)) *fb) (void);
3427 Fixing this is not easy and not very important. */
3428 fvdef = finlist;
3429 continue;
3430 case flistseen:
3431 if (plainc || declarations)
3433 make_C_tag (TRUE); /* a function */
3434 fvdef = fignore;
3436 break;
3438 if (structdef == stagseen && !cjava)
3440 popclass_above (bracelev);
3441 structdef = snone;
3443 break;
3444 case dsharpseen:
3445 savetoken = token;
3446 break;
3448 if (!yacc_rules || lp == newlb.buffer + 1)
3450 tokoff = lp - 1 - newlb.buffer;
3451 toklen = 1;
3452 midtoken = TRUE;
3454 continue;
3455 } /* if (begtoken) */
3456 } /* if must look at token */
3459 /* Detect end of line, colon, comma, semicolon and various braces
3460 after having handled a token.*/
3461 switch (c)
3463 case ':':
3464 if (inattribute)
3465 break;
3466 if (yacc_rules && token.offset == 0 && token.valid)
3468 make_C_tag (FALSE); /* a yacc function */
3469 break;
3471 if (definedef != dnone)
3472 break;
3473 switch (objdef)
3475 case otagseen:
3476 objdef = oignore;
3477 make_C_tag (TRUE); /* an Objective C class */
3478 break;
3479 case omethodtag:
3480 case omethodparm:
3481 objdef = omethodcolon;
3482 linebuffer_setlen (&token_name, token_name.len + 1);
3483 strcat (token_name.buffer, ":");
3484 break;
3486 if (structdef == stagseen)
3488 structdef = scolonseen;
3489 break;
3491 /* Should be useless, but may be work as a safety net. */
3492 if (cplpl && fvdef == flistseen)
3494 make_C_tag (TRUE); /* a function */
3495 fvdef = fignore;
3496 break;
3498 break;
3499 case ';':
3500 if (definedef != dnone || inattribute)
3501 break;
3502 switch (typdef)
3504 case tend:
3505 case ttypeseen:
3506 make_C_tag (FALSE); /* a typedef */
3507 typdef = tnone;
3508 fvdef = fvnone;
3509 break;
3510 case tnone:
3511 case tinbody:
3512 case tignore:
3513 switch (fvdef)
3515 case fignore:
3516 if (typdef == tignore || cplpl)
3517 fvdef = fvnone;
3518 break;
3519 case fvnameseen:
3520 if ((globals && bracelev == 0 && (!fvextern || declarations))
3521 || (members && instruct))
3522 make_C_tag (FALSE); /* a variable */
3523 fvextern = FALSE;
3524 fvdef = fvnone;
3525 token.valid = FALSE;
3526 break;
3527 case flistseen:
3528 if ((declarations
3529 && (cplpl || !instruct)
3530 && (typdef == tnone || (typdef != tignore && instruct)))
3531 || (members
3532 && plainc && instruct))
3533 make_C_tag (TRUE); /* a function */
3534 /* FALLTHRU */
3535 default:
3536 fvextern = FALSE;
3537 fvdef = fvnone;
3538 if (declarations
3539 && cplpl && structdef == stagseen)
3540 make_C_tag (FALSE); /* forward declaration */
3541 else
3542 token.valid = FALSE;
3543 } /* switch (fvdef) */
3544 /* FALLTHRU */
3545 default:
3546 if (!instruct)
3547 typdef = tnone;
3549 if (structdef == stagseen)
3550 structdef = snone;
3551 break;
3552 case ',':
3553 if (definedef != dnone || inattribute)
3554 break;
3555 switch (objdef)
3557 case omethodtag:
3558 case omethodparm:
3559 make_C_tag (TRUE); /* an Objective C method */
3560 objdef = oinbody;
3561 break;
3563 switch (fvdef)
3565 case fdefunkey:
3566 case foperator:
3567 case fstartlist:
3568 case finlist:
3569 case fignore:
3570 case vignore:
3571 break;
3572 case fdefunname:
3573 fvdef = fignore;
3574 break;
3575 case fvnameseen:
3576 if (parlev == 0
3577 && ((globals
3578 && bracelev == 0
3579 && templatelev == 0
3580 && (!fvextern || declarations))
3581 || (members && instruct)))
3582 make_C_tag (FALSE); /* a variable */
3583 break;
3584 case flistseen:
3585 if ((declarations && typdef == tnone && !instruct)
3586 || (members && typdef != tignore && instruct))
3588 make_C_tag (TRUE); /* a function */
3589 fvdef = fvnameseen;
3591 else if (!declarations)
3592 fvdef = fvnone;
3593 token.valid = FALSE;
3594 break;
3595 default:
3596 fvdef = fvnone;
3598 if (structdef == stagseen)
3599 structdef = snone;
3600 break;
3601 case ']':
3602 if (definedef != dnone || inattribute)
3603 break;
3604 if (structdef == stagseen)
3605 structdef = snone;
3606 switch (typdef)
3608 case ttypeseen:
3609 case tend:
3610 typdef = tignore;
3611 make_C_tag (FALSE); /* a typedef */
3612 break;
3613 case tnone:
3614 case tinbody:
3615 switch (fvdef)
3617 case foperator:
3618 case finlist:
3619 case fignore:
3620 case vignore:
3621 break;
3622 case fvnameseen:
3623 if ((members && bracelev == 1)
3624 || (globals && bracelev == 0
3625 && (!fvextern || declarations)))
3626 make_C_tag (FALSE); /* a variable */
3627 /* FALLTHRU */
3628 default:
3629 fvdef = fvnone;
3631 break;
3633 break;
3634 case '(':
3635 if (inattribute)
3637 attrparlev++;
3638 break;
3640 if (definedef != dnone)
3641 break;
3642 if (objdef == otagseen && parlev == 0)
3643 objdef = oparenseen;
3644 switch (fvdef)
3646 case fvnameseen:
3647 if (typdef == ttypeseen
3648 && *lp != '*'
3649 && !instruct)
3651 /* This handles constructs like:
3652 typedef void OperatorFun (int fun); */
3653 make_C_tag (FALSE);
3654 typdef = tignore;
3655 fvdef = fignore;
3656 break;
3658 /* FALLTHRU */
3659 case foperator:
3660 fvdef = fstartlist;
3661 break;
3662 case flistseen:
3663 fvdef = finlist;
3664 break;
3666 parlev++;
3667 break;
3668 case ')':
3669 if (inattribute)
3671 if (--attrparlev == 0)
3672 inattribute = FALSE;
3673 break;
3675 if (definedef != dnone)
3676 break;
3677 if (objdef == ocatseen && parlev == 1)
3679 make_C_tag (TRUE); /* an Objective C category */
3680 objdef = oignore;
3682 if (--parlev == 0)
3684 switch (fvdef)
3686 case fstartlist:
3687 case finlist:
3688 fvdef = flistseen;
3689 break;
3691 if (!instruct
3692 && (typdef == tend
3693 || typdef == ttypeseen))
3695 typdef = tignore;
3696 make_C_tag (FALSE); /* a typedef */
3699 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
3700 parlev = 0;
3701 break;
3702 case '{':
3703 if (definedef != dnone)
3704 break;
3705 if (typdef == ttypeseen)
3707 /* Whenever typdef is set to tinbody (currently only
3708 here), typdefbracelev should be set to bracelev. */
3709 typdef = tinbody;
3710 typdefbracelev = bracelev;
3712 switch (fvdef)
3714 case flistseen:
3715 make_C_tag (TRUE); /* a function */
3716 /* FALLTHRU */
3717 case fignore:
3718 fvdef = fvnone;
3719 break;
3720 case fvnone:
3721 switch (objdef)
3723 case otagseen:
3724 make_C_tag (TRUE); /* an Objective C class */
3725 objdef = oignore;
3726 break;
3727 case omethodtag:
3728 case omethodparm:
3729 make_C_tag (TRUE); /* an Objective C method */
3730 objdef = oinbody;
3731 break;
3732 default:
3733 /* Neutralize `extern "C" {' grot. */
3734 if (bracelev == 0 && structdef == snone && nestlev == 0
3735 && typdef == tnone)
3736 bracelev = -1;
3738 break;
3740 switch (structdef)
3742 case skeyseen: /* unnamed struct */
3743 pushclass_above (bracelev, NULL, 0);
3744 structdef = snone;
3745 break;
3746 case stagseen: /* named struct or enum */
3747 case scolonseen: /* a class */
3748 pushclass_above (bracelev,token.line+token.offset, token.length);
3749 structdef = snone;
3750 make_C_tag (FALSE); /* a struct or enum */
3751 break;
3753 bracelev += 1;
3754 break;
3755 case '*':
3756 if (definedef != dnone)
3757 break;
3758 if (fvdef == fstartlist)
3760 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
3761 token.valid = FALSE;
3763 break;
3764 case '}':
3765 if (definedef != dnone)
3766 break;
3767 bracelev -= 1;
3768 if (!ignoreindent && lp == newlb.buffer + 1)
3770 if (bracelev != 0)
3771 token.valid = FALSE; /* unexpected value, token unreliable */
3772 bracelev = 0; /* reset brace level if first column */
3773 parlev = 0; /* also reset paren level, just in case... */
3775 else if (bracelev < 0)
3777 token.valid = FALSE; /* something gone amiss, token unreliable */
3778 bracelev = 0;
3780 if (bracelev == 0 && fvdef == vignore)
3781 fvdef = fvnone; /* end of function */
3782 popclass_above (bracelev);
3783 structdef = snone;
3784 /* Only if typdef == tinbody is typdefbracelev significant. */
3785 if (typdef == tinbody && bracelev <= typdefbracelev)
3787 assert (bracelev == typdefbracelev);
3788 typdef = tend;
3790 break;
3791 case '=':
3792 if (definedef != dnone)
3793 break;
3794 switch (fvdef)
3796 case foperator:
3797 case finlist:
3798 case fignore:
3799 case vignore:
3800 break;
3801 case fvnameseen:
3802 if ((members && bracelev == 1)
3803 || (globals && bracelev == 0 && (!fvextern || declarations)))
3804 make_C_tag (FALSE); /* a variable */
3805 /* FALLTHRU */
3806 default:
3807 fvdef = vignore;
3809 break;
3810 case '<':
3811 if (cplpl
3812 && (structdef == stagseen || fvdef == fvnameseen))
3814 templatelev++;
3815 break;
3817 goto resetfvdef;
3818 case '>':
3819 if (templatelev > 0)
3821 templatelev--;
3822 break;
3824 goto resetfvdef;
3825 case '+':
3826 case '-':
3827 if (objdef == oinbody && bracelev == 0)
3829 objdef = omethodsign;
3830 break;
3832 /* FALLTHRU */
3833 resetfvdef:
3834 case '#': case '~': case '&': case '%': case '/':
3835 case '|': case '^': case '!': case '.': case '?':
3836 if (definedef != dnone)
3837 break;
3838 /* These surely cannot follow a function tag in C. */
3839 switch (fvdef)
3841 case foperator:
3842 case finlist:
3843 case fignore:
3844 case vignore:
3845 break;
3846 default:
3847 fvdef = fvnone;
3849 break;
3850 case '\0':
3851 if (objdef == otagseen)
3853 make_C_tag (TRUE); /* an Objective C class */
3854 objdef = oignore;
3856 /* If a macro spans multiple lines don't reset its state. */
3857 if (quotednl)
3858 CNL_SAVE_DEFINEDEF ();
3859 else
3860 CNL ();
3861 break;
3862 } /* switch (c) */
3864 } /* while not eof */
3866 free (lbs[0].lb.buffer);
3867 free (lbs[1].lb.buffer);
3871 * Process either a C++ file or a C file depending on the setting
3872 * of a global flag.
3874 static void
3875 default_C_entries (FILE *inf)
3877 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
3880 /* Always do plain C. */
3881 static void
3882 plain_C_entries (FILE *inf)
3884 C_entries (0, inf);
3887 /* Always do C++. */
3888 static void
3889 Cplusplus_entries (FILE *inf)
3891 C_entries (C_PLPL, inf);
3894 /* Always do Java. */
3895 static void
3896 Cjava_entries (FILE *inf)
3898 C_entries (C_JAVA, inf);
3901 /* Always do C*. */
3902 static void
3903 Cstar_entries (FILE *inf)
3905 C_entries (C_STAR, inf);
3908 /* Always do Yacc. */
3909 static void
3910 Yacc_entries (FILE *inf)
3912 C_entries (YACC, inf);
3916 /* Useful macros. */
3917 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
3918 for (; /* loop initialization */ \
3919 !feof (file_pointer) /* loop test */ \
3920 && /* instructions at start of loop */ \
3921 (readline (&line_buffer, file_pointer), \
3922 char_pointer = line_buffer.buffer, \
3923 TRUE); \
3926 #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \
3927 ((assert ("" kw), TRUE) /* syntax error if not a literal string */ \
3928 && strneq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3929 && notinname ((cp)[sizeof (kw)-1]) /* end of kw */ \
3930 && ((cp) = skip_spaces ((cp)+sizeof (kw)-1))) /* skip spaces */
3932 /* Similar to LOOKING_AT but does not use notinname, does not skip */
3933 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
3934 ((assert ("" kw), TRUE) /* syntax error if not a literal string */ \
3935 && strncaseeq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3936 && ((cp) += sizeof (kw)-1)) /* skip spaces */
3939 * Read a file, but do no processing. This is used to do regexp
3940 * matching on files that have no language defined.
3942 static void
3943 just_read_file (FILE *inf)
3945 while (!feof (inf))
3946 readline (&lb, inf);
3950 /* Fortran parsing */
3952 static void F_takeprec (void);
3953 static void F_getit (FILE *);
3955 static void
3956 F_takeprec (void)
3958 dbp = skip_spaces (dbp);
3959 if (*dbp != '*')
3960 return;
3961 dbp++;
3962 dbp = skip_spaces (dbp);
3963 if (strneq (dbp, "(*)", 3))
3965 dbp += 3;
3966 return;
3968 if (!ISDIGIT (*dbp))
3970 --dbp; /* force failure */
3971 return;
3974 dbp++;
3975 while (ISDIGIT (*dbp));
3978 static void
3979 F_getit (FILE *inf)
3981 register char *cp;
3983 dbp = skip_spaces (dbp);
3984 if (*dbp == '\0')
3986 readline (&lb, inf);
3987 dbp = lb.buffer;
3988 if (dbp[5] != '&')
3989 return;
3990 dbp += 6;
3991 dbp = skip_spaces (dbp);
3993 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
3994 return;
3995 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
3996 continue;
3997 make_tag (dbp, cp-dbp, TRUE,
3998 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4002 static void
4003 Fortran_functions (FILE *inf)
4005 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4007 if (*dbp == '%')
4008 dbp++; /* Ratfor escape to fortran */
4009 dbp = skip_spaces (dbp);
4010 if (*dbp == '\0')
4011 continue;
4013 if (LOOKING_AT_NOCASE (dbp, "recursive"))
4014 dbp = skip_spaces (dbp);
4016 if (LOOKING_AT_NOCASE (dbp, "pure"))
4017 dbp = skip_spaces (dbp);
4019 if (LOOKING_AT_NOCASE (dbp, "elemental"))
4020 dbp = skip_spaces (dbp);
4022 switch (lowcase (*dbp))
4024 case 'i':
4025 if (nocase_tail ("integer"))
4026 F_takeprec ();
4027 break;
4028 case 'r':
4029 if (nocase_tail ("real"))
4030 F_takeprec ();
4031 break;
4032 case 'l':
4033 if (nocase_tail ("logical"))
4034 F_takeprec ();
4035 break;
4036 case 'c':
4037 if (nocase_tail ("complex") || nocase_tail ("character"))
4038 F_takeprec ();
4039 break;
4040 case 'd':
4041 if (nocase_tail ("double"))
4043 dbp = skip_spaces (dbp);
4044 if (*dbp == '\0')
4045 continue;
4046 if (nocase_tail ("precision"))
4047 break;
4048 continue;
4050 break;
4052 dbp = skip_spaces (dbp);
4053 if (*dbp == '\0')
4054 continue;
4055 switch (lowcase (*dbp))
4057 case 'f':
4058 if (nocase_tail ("function"))
4059 F_getit (inf);
4060 continue;
4061 case 's':
4062 if (nocase_tail ("subroutine"))
4063 F_getit (inf);
4064 continue;
4065 case 'e':
4066 if (nocase_tail ("entry"))
4067 F_getit (inf);
4068 continue;
4069 case 'b':
4070 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4072 dbp = skip_spaces (dbp);
4073 if (*dbp == '\0') /* assume un-named */
4074 make_tag ("blockdata", 9, TRUE,
4075 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4076 else
4077 F_getit (inf); /* look for name */
4079 continue;
4086 * Ada parsing
4087 * Original code by
4088 * Philippe Waroquiers (1998)
4091 /* Once we are positioned after an "interesting" keyword, let's get
4092 the real tag value necessary. */
4093 static void
4094 Ada_getit (FILE *inf, const char *name_qualifier)
4096 register char *cp;
4097 char *name;
4098 char c;
4100 while (!feof (inf))
4102 dbp = skip_spaces (dbp);
4103 if (*dbp == '\0'
4104 || (dbp[0] == '-' && dbp[1] == '-'))
4106 readline (&lb, inf);
4107 dbp = lb.buffer;
4109 switch (lowcase (*dbp))
4111 case 'b':
4112 if (nocase_tail ("body"))
4114 /* Skipping body of procedure body or package body or ....
4115 resetting qualifier to body instead of spec. */
4116 name_qualifier = "/b";
4117 continue;
4119 break;
4120 case 't':
4121 /* Skipping type of task type or protected type ... */
4122 if (nocase_tail ("type"))
4123 continue;
4124 break;
4126 if (*dbp == '"')
4128 dbp += 1;
4129 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4130 continue;
4132 else
4134 dbp = skip_spaces (dbp);
4135 for (cp = dbp;
4136 (*cp != '\0'
4137 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4138 cp++)
4139 continue;
4140 if (cp == dbp)
4141 return;
4143 c = *cp;
4144 *cp = '\0';
4145 name = concat (dbp, name_qualifier, "");
4146 *cp = c;
4147 make_tag (name, strlen (name), TRUE,
4148 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4149 free (name);
4150 if (c == '"')
4151 dbp = cp + 1;
4152 return;
4156 static void
4157 Ada_funcs (FILE *inf)
4159 bool inquote = FALSE;
4160 bool skip_till_semicolumn = FALSE;
4162 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4164 while (*dbp != '\0')
4166 /* Skip a string i.e. "abcd". */
4167 if (inquote || (*dbp == '"'))
4169 dbp = etags_strchr (dbp + !inquote, '"');
4170 if (dbp != NULL)
4172 inquote = FALSE;
4173 dbp += 1;
4174 continue; /* advance char */
4176 else
4178 inquote = TRUE;
4179 break; /* advance line */
4183 /* Skip comments. */
4184 if (dbp[0] == '-' && dbp[1] == '-')
4185 break; /* advance line */
4187 /* Skip character enclosed in single quote i.e. 'a'
4188 and skip single quote starting an attribute i.e. 'Image. */
4189 if (*dbp == '\'')
4191 dbp++ ;
4192 if (*dbp != '\0')
4193 dbp++;
4194 continue;
4197 if (skip_till_semicolumn)
4199 if (*dbp == ';')
4200 skip_till_semicolumn = FALSE;
4201 dbp++;
4202 continue; /* advance char */
4205 /* Search for beginning of a token. */
4206 if (!begtoken (*dbp))
4208 dbp++;
4209 continue; /* advance char */
4212 /* We are at the beginning of a token. */
4213 switch (lowcase (*dbp))
4215 case 'f':
4216 if (!packages_only && nocase_tail ("function"))
4217 Ada_getit (inf, "/f");
4218 else
4219 break; /* from switch */
4220 continue; /* advance char */
4221 case 'p':
4222 if (!packages_only && nocase_tail ("procedure"))
4223 Ada_getit (inf, "/p");
4224 else if (nocase_tail ("package"))
4225 Ada_getit (inf, "/s");
4226 else if (nocase_tail ("protected")) /* protected type */
4227 Ada_getit (inf, "/t");
4228 else
4229 break; /* from switch */
4230 continue; /* advance char */
4232 case 'u':
4233 if (typedefs && !packages_only && nocase_tail ("use"))
4235 /* when tagging types, avoid tagging use type Pack.Typename;
4236 for this, we will skip everything till a ; */
4237 skip_till_semicolumn = TRUE;
4238 continue; /* advance char */
4241 case 't':
4242 if (!packages_only && nocase_tail ("task"))
4243 Ada_getit (inf, "/k");
4244 else if (typedefs && !packages_only && nocase_tail ("type"))
4246 Ada_getit (inf, "/t");
4247 while (*dbp != '\0')
4248 dbp += 1;
4250 else
4251 break; /* from switch */
4252 continue; /* advance char */
4255 /* Look for the end of the token. */
4256 while (!endtoken (*dbp))
4257 dbp++;
4259 } /* advance char */
4260 } /* advance line */
4265 * Unix and microcontroller assembly tag handling
4266 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4267 * Idea by Bob Weiner, Motorola Inc. (1994)
4269 static void
4270 Asm_labels (FILE *inf)
4272 register char *cp;
4274 LOOP_ON_INPUT_LINES (inf, lb, cp)
4276 /* If first char is alphabetic or one of [_.$], test for colon
4277 following identifier. */
4278 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4280 /* Read past label. */
4281 cp++;
4282 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4283 cp++;
4284 if (*cp == ':' || iswhite (*cp))
4285 /* Found end of label, so copy it and add it to the table. */
4286 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4287 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4294 * Perl support
4295 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4296 * Perl variable names: /^(my|local).../
4297 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4298 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4299 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4301 static void
4302 Perl_functions (FILE *inf)
4304 char *package = savestr ("main"); /* current package name */
4305 register char *cp;
4307 LOOP_ON_INPUT_LINES (inf, lb, cp)
4309 cp = skip_spaces (cp);
4311 if (LOOKING_AT (cp, "package"))
4313 free (package);
4314 get_tag (cp, &package);
4316 else if (LOOKING_AT (cp, "sub"))
4318 char *pos;
4319 char *sp = cp;
4321 while (!notinname (*cp))
4322 cp++;
4323 if (cp == sp)
4324 continue; /* nothing found */
4325 if ((pos = etags_strchr (sp, ':')) != NULL
4326 && pos < cp && pos[1] == ':')
4327 /* The name is already qualified. */
4328 make_tag (sp, cp - sp, TRUE,
4329 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4330 else
4331 /* Qualify it. */
4333 char savechar, *name;
4335 savechar = *cp;
4336 *cp = '\0';
4337 name = concat (package, "::", sp);
4338 *cp = savechar;
4339 make_tag (name, strlen (name), TRUE,
4340 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4341 free (name);
4344 else if (globals) /* only if we are tagging global vars */
4346 /* Skip a qualifier, if any. */
4347 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4348 /* After "my" or "local", but before any following paren or space. */
4349 char *varstart = cp;
4351 if (qual /* should this be removed? If yes, how? */
4352 && (*cp == '$' || *cp == '@' || *cp == '%'))
4354 varstart += 1;
4356 cp++;
4357 while (ISALNUM (*cp) || *cp == '_');
4359 else if (qual)
4361 /* Should be examining a variable list at this point;
4362 could insist on seeing an open parenthesis. */
4363 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4364 cp++;
4366 else
4367 continue;
4369 make_tag (varstart, cp - varstart, FALSE,
4370 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4373 free (package);
4378 * Python support
4379 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4380 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4381 * More ideas by seb bacon <seb@jamkit.com> (2002)
4383 static void
4384 Python_functions (FILE *inf)
4386 register char *cp;
4388 LOOP_ON_INPUT_LINES (inf, lb, cp)
4390 cp = skip_spaces (cp);
4391 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4393 char *name = cp;
4394 while (!notinname (*cp) && *cp != ':')
4395 cp++;
4396 make_tag (name, cp - name, TRUE,
4397 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4404 * PHP support
4405 * Look for:
4406 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4407 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4408 * - /^[ \t]*define\(\"[^\"]+/
4409 * Only with --members:
4410 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4411 * Idea by Diez B. Roggisch (2001)
4413 static void
4414 PHP_functions (FILE *inf)
4416 register char *cp, *name;
4417 bool search_identifier = FALSE;
4419 LOOP_ON_INPUT_LINES (inf, lb, cp)
4421 cp = skip_spaces (cp);
4422 name = cp;
4423 if (search_identifier
4424 && *cp != '\0')
4426 while (!notinname (*cp))
4427 cp++;
4428 make_tag (name, cp - name, TRUE,
4429 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4430 search_identifier = FALSE;
4432 else if (LOOKING_AT (cp, "function"))
4434 if (*cp == '&')
4435 cp = skip_spaces (cp+1);
4436 if (*cp != '\0')
4438 name = cp;
4439 while (!notinname (*cp))
4440 cp++;
4441 make_tag (name, cp - name, TRUE,
4442 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4444 else
4445 search_identifier = TRUE;
4447 else if (LOOKING_AT (cp, "class"))
4449 if (*cp != '\0')
4451 name = cp;
4452 while (*cp != '\0' && !iswhite (*cp))
4453 cp++;
4454 make_tag (name, cp - name, FALSE,
4455 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4457 else
4458 search_identifier = TRUE;
4460 else if (strneq (cp, "define", 6)
4461 && (cp = skip_spaces (cp+6))
4462 && *cp++ == '('
4463 && (*cp == '"' || *cp == '\''))
4465 char quote = *cp++;
4466 name = cp;
4467 while (*cp != quote && *cp != '\0')
4468 cp++;
4469 make_tag (name, cp - name, FALSE,
4470 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4472 else if (members
4473 && LOOKING_AT (cp, "var")
4474 && *cp == '$')
4476 name = cp;
4477 while (!notinname (*cp))
4478 cp++;
4479 make_tag (name, cp - name, FALSE,
4480 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4487 * Cobol tag functions
4488 * We could look for anything that could be a paragraph name.
4489 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4490 * Idea by Corny de Souza (1993)
4492 static void
4493 Cobol_paragraphs (FILE *inf)
4495 register char *bp, *ep;
4497 LOOP_ON_INPUT_LINES (inf, lb, bp)
4499 if (lb.len < 9)
4500 continue;
4501 bp += 8;
4503 /* If eoln, compiler option or comment ignore whole line. */
4504 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4505 continue;
4507 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4508 continue;
4509 if (*ep++ == '.')
4510 make_tag (bp, ep - bp, TRUE,
4511 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4517 * Makefile support
4518 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4520 static void
4521 Makefile_targets (FILE *inf)
4523 register char *bp;
4525 LOOP_ON_INPUT_LINES (inf, lb, bp)
4527 if (*bp == '\t' || *bp == '#')
4528 continue;
4529 while (*bp != '\0' && *bp != '=' && *bp != ':')
4530 bp++;
4531 if (*bp == ':' || (globals && *bp == '='))
4533 /* We should detect if there is more than one tag, but we do not.
4534 We just skip initial and final spaces. */
4535 char * namestart = skip_spaces (lb.buffer);
4536 while (--bp > namestart)
4537 if (!notinname (*bp))
4538 break;
4539 make_tag (namestart, bp - namestart + 1, TRUE,
4540 lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4547 * Pascal parsing
4548 * Original code by Mosur K. Mohan (1989)
4550 * Locates tags for procedures & functions. Doesn't do any type- or
4551 * var-definitions. It does look for the keyword "extern" or
4552 * "forward" immediately following the procedure statement; if found,
4553 * the tag is skipped.
4555 static void
4556 Pascal_functions (FILE *inf)
4558 linebuffer tline; /* mostly copied from C_entries */
4559 long save_lcno;
4560 int save_lineno, namelen, taglen;
4561 char c, *name;
4563 bool /* each of these flags is TRUE if: */
4564 incomment, /* point is inside a comment */
4565 inquote, /* point is inside '..' string */
4566 get_tagname, /* point is after PROCEDURE/FUNCTION
4567 keyword, so next item = potential tag */
4568 found_tag, /* point is after a potential tag */
4569 inparms, /* point is within parameter-list */
4570 verify_tag; /* point has passed the parm-list, so the
4571 next token will determine whether this
4572 is a FORWARD/EXTERN to be ignored, or
4573 whether it is a real tag */
4575 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4576 name = NULL; /* keep compiler quiet */
4577 dbp = lb.buffer;
4578 *dbp = '\0';
4579 linebuffer_init (&tline);
4581 incomment = inquote = FALSE;
4582 found_tag = FALSE; /* have a proc name; check if extern */
4583 get_tagname = FALSE; /* found "procedure" keyword */
4584 inparms = FALSE; /* found '(' after "proc" */
4585 verify_tag = FALSE; /* check if "extern" is ahead */
4588 while (!feof (inf)) /* long main loop to get next char */
4590 c = *dbp++;
4591 if (c == '\0') /* if end of line */
4593 readline (&lb, inf);
4594 dbp = lb.buffer;
4595 if (*dbp == '\0')
4596 continue;
4597 if (!((found_tag && verify_tag)
4598 || get_tagname))
4599 c = *dbp++; /* only if don't need *dbp pointing
4600 to the beginning of the name of
4601 the procedure or function */
4603 if (incomment)
4605 if (c == '}') /* within { } comments */
4606 incomment = FALSE;
4607 else if (c == '*' && *dbp == ')') /* within (* *) comments */
4609 dbp++;
4610 incomment = FALSE;
4612 continue;
4614 else if (inquote)
4616 if (c == '\'')
4617 inquote = FALSE;
4618 continue;
4620 else
4621 switch (c)
4623 case '\'':
4624 inquote = TRUE; /* found first quote */
4625 continue;
4626 case '{': /* found open { comment */
4627 incomment = TRUE;
4628 continue;
4629 case '(':
4630 if (*dbp == '*') /* found open (* comment */
4632 incomment = TRUE;
4633 dbp++;
4635 else if (found_tag) /* found '(' after tag, i.e., parm-list */
4636 inparms = TRUE;
4637 continue;
4638 case ')': /* end of parms list */
4639 if (inparms)
4640 inparms = FALSE;
4641 continue;
4642 case ';':
4643 if (found_tag && !inparms) /* end of proc or fn stmt */
4645 verify_tag = TRUE;
4646 break;
4648 continue;
4650 if (found_tag && verify_tag && (*dbp != ' '))
4652 /* Check if this is an "extern" declaration. */
4653 if (*dbp == '\0')
4654 continue;
4655 if (lowcase (*dbp) == 'e')
4657 if (nocase_tail ("extern")) /* superfluous, really! */
4659 found_tag = FALSE;
4660 verify_tag = FALSE;
4663 else if (lowcase (*dbp) == 'f')
4665 if (nocase_tail ("forward")) /* check for forward reference */
4667 found_tag = FALSE;
4668 verify_tag = FALSE;
4671 if (found_tag && verify_tag) /* not external proc, so make tag */
4673 found_tag = FALSE;
4674 verify_tag = FALSE;
4675 make_tag (name, namelen, TRUE,
4676 tline.buffer, taglen, save_lineno, save_lcno);
4677 continue;
4680 if (get_tagname) /* grab name of proc or fn */
4682 char *cp;
4684 if (*dbp == '\0')
4685 continue;
4687 /* Find block name. */
4688 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
4689 continue;
4691 /* Save all values for later tagging. */
4692 linebuffer_setlen (&tline, lb.len);
4693 strcpy (tline.buffer, lb.buffer);
4694 save_lineno = lineno;
4695 save_lcno = linecharno;
4696 name = tline.buffer + (dbp - lb.buffer);
4697 namelen = cp - dbp;
4698 taglen = cp - lb.buffer + 1;
4700 dbp = cp; /* set dbp to e-o-token */
4701 get_tagname = FALSE;
4702 found_tag = TRUE;
4703 continue;
4705 /* And proceed to check for "extern". */
4707 else if (!incomment && !inquote && !found_tag)
4709 /* Check for proc/fn keywords. */
4710 switch (lowcase (c))
4712 case 'p':
4713 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
4714 get_tagname = TRUE;
4715 continue;
4716 case 'f':
4717 if (nocase_tail ("unction"))
4718 get_tagname = TRUE;
4719 continue;
4722 } /* while not eof */
4724 free (tline.buffer);
4729 * Lisp tag functions
4730 * look for (def or (DEF, quote or QUOTE
4733 static void L_getit (void);
4735 static void
4736 L_getit (void)
4738 if (*dbp == '\'') /* Skip prefix quote */
4739 dbp++;
4740 else if (*dbp == '(')
4742 dbp++;
4743 /* Try to skip "(quote " */
4744 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
4745 /* Ok, then skip "(" before name in (defstruct (foo)) */
4746 dbp = skip_spaces (dbp);
4748 get_tag (dbp, NULL);
4751 static void
4752 Lisp_functions (FILE *inf)
4754 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4756 if (dbp[0] != '(')
4757 continue;
4759 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
4761 dbp = skip_non_spaces (dbp);
4762 dbp = skip_spaces (dbp);
4763 L_getit ();
4765 else
4767 /* Check for (foo::defmumble name-defined ... */
4769 dbp++;
4770 while (!notinname (*dbp) && *dbp != ':');
4771 if (*dbp == ':')
4774 dbp++;
4775 while (*dbp == ':');
4777 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
4779 dbp = skip_non_spaces (dbp);
4780 dbp = skip_spaces (dbp);
4781 L_getit ();
4790 * Lua script language parsing
4791 * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
4793 * "function" and "local function" are tags if they start at column 1.
4795 static void
4796 Lua_functions (FILE *inf)
4798 register char *bp;
4800 LOOP_ON_INPUT_LINES (inf, lb, bp)
4802 if (bp[0] != 'f' && bp[0] != 'l')
4803 continue;
4805 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
4807 if (LOOKING_AT (bp, "function"))
4808 get_tag (bp, NULL);
4814 * PostScript tags
4815 * Just look for lines where the first character is '/'
4816 * Also look at "defineps" for PSWrap
4817 * Ideas by:
4818 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
4819 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
4821 static void
4822 PS_functions (FILE *inf)
4824 register char *bp, *ep;
4826 LOOP_ON_INPUT_LINES (inf, lb, bp)
4828 if (bp[0] == '/')
4830 for (ep = bp+1;
4831 *ep != '\0' && *ep != ' ' && *ep != '{';
4832 ep++)
4833 continue;
4834 make_tag (bp, ep - bp, TRUE,
4835 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4837 else if (LOOKING_AT (bp, "defineps"))
4838 get_tag (bp, NULL);
4844 * Forth tags
4845 * Ignore anything after \ followed by space or in ( )
4846 * Look for words defined by :
4847 * Look for constant, code, create, defer, value, and variable
4848 * OBP extensions: Look for buffer:, field,
4849 * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
4851 static void
4852 Forth_words (FILE *inf)
4854 register char *bp;
4856 LOOP_ON_INPUT_LINES (inf, lb, bp)
4857 while ((bp = skip_spaces (bp))[0] != '\0')
4858 if (bp[0] == '\\' && iswhite (bp[1]))
4859 break; /* read next line */
4860 else if (bp[0] == '(' && iswhite (bp[1]))
4861 do /* skip to ) or eol */
4862 bp++;
4863 while (*bp != ')' && *bp != '\0');
4864 else if ((bp[0] == ':' && iswhite (bp[1]) && bp++)
4865 || LOOKING_AT_NOCASE (bp, "constant")
4866 || LOOKING_AT_NOCASE (bp, "code")
4867 || LOOKING_AT_NOCASE (bp, "create")
4868 || LOOKING_AT_NOCASE (bp, "defer")
4869 || LOOKING_AT_NOCASE (bp, "value")
4870 || LOOKING_AT_NOCASE (bp, "variable")
4871 || LOOKING_AT_NOCASE (bp, "buffer:")
4872 || LOOKING_AT_NOCASE (bp, "field"))
4873 get_tag (skip_spaces (bp), NULL); /* Yay! A definition! */
4874 else
4875 bp = skip_non_spaces (bp);
4880 * Scheme tag functions
4881 * look for (def... xyzzy
4882 * (def... (xyzzy
4883 * (def ... ((...(xyzzy ....
4884 * (set! xyzzy
4885 * Original code by Ken Haase (1985?)
4887 static void
4888 Scheme_functions (FILE *inf)
4890 register char *bp;
4892 LOOP_ON_INPUT_LINES (inf, lb, bp)
4894 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
4896 bp = skip_non_spaces (bp+4);
4897 /* Skip over open parens and white space. Don't continue past
4898 '\0'. */
4899 while (*bp && notinname (*bp))
4900 bp++;
4901 get_tag (bp, NULL);
4903 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
4904 get_tag (bp, NULL);
4909 /* Find tags in TeX and LaTeX input files. */
4911 /* TEX_toktab is a table of TeX control sequences that define tags.
4912 * Each entry records one such control sequence.
4914 * Original code from who knows whom.
4915 * Ideas by:
4916 * Stefan Monnier (2002)
4919 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
4921 /* Default set of control sequences to put into TEX_toktab.
4922 The value of environment var TEXTAGS is prepended to this. */
4923 static const char *TEX_defenv = "\
4924 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
4925 :part:appendix:entry:index:def\
4926 :newcommand:renewcommand:newenvironment:renewenvironment";
4928 static void TEX_mode (FILE *);
4929 static void TEX_decode_env (const char *, const char *);
4931 static char TEX_esc = '\\';
4932 static char TEX_opgrp = '{';
4933 static char TEX_clgrp = '}';
4936 * TeX/LaTeX scanning loop.
4938 static void
4939 TeX_commands (FILE *inf)
4941 char *cp;
4942 linebuffer *key;
4944 /* Select either \ or ! as escape character. */
4945 TEX_mode (inf);
4947 /* Initialize token table once from environment. */
4948 if (TEX_toktab == NULL)
4949 TEX_decode_env ("TEXTAGS", TEX_defenv);
4951 LOOP_ON_INPUT_LINES (inf, lb, cp)
4953 /* Look at each TEX keyword in line. */
4954 for (;;)
4956 /* Look for a TEX escape. */
4957 while (*cp++ != TEX_esc)
4958 if (cp[-1] == '\0' || cp[-1] == '%')
4959 goto tex_next_line;
4961 for (key = TEX_toktab; key->buffer != NULL; key++)
4962 if (strneq (cp, key->buffer, key->len))
4964 register char *p;
4965 int namelen, linelen;
4966 bool opgrp = FALSE;
4968 cp = skip_spaces (cp + key->len);
4969 if (*cp == TEX_opgrp)
4971 opgrp = TRUE;
4972 cp++;
4974 for (p = cp;
4975 (!iswhite (*p) && *p != '#' &&
4976 *p != TEX_opgrp && *p != TEX_clgrp);
4977 p++)
4978 continue;
4979 namelen = p - cp;
4980 linelen = lb.len;
4981 if (!opgrp || *p == TEX_clgrp)
4983 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
4984 p++;
4985 linelen = p - lb.buffer + 1;
4987 make_tag (cp, namelen, TRUE,
4988 lb.buffer, linelen, lineno, linecharno);
4989 goto tex_next_line; /* We only tag a line once */
4992 tex_next_line:
4997 #define TEX_LESC '\\'
4998 #define TEX_SESC '!'
5000 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5001 chars accordingly. */
5002 static void
5003 TEX_mode (FILE *inf)
5005 int c;
5007 while ((c = getc (inf)) != EOF)
5009 /* Skip to next line if we hit the TeX comment char. */
5010 if (c == '%')
5011 while (c != '\n' && c != EOF)
5012 c = getc (inf);
5013 else if (c == TEX_LESC || c == TEX_SESC )
5014 break;
5017 if (c == TEX_LESC)
5019 TEX_esc = TEX_LESC;
5020 TEX_opgrp = '{';
5021 TEX_clgrp = '}';
5023 else
5025 TEX_esc = TEX_SESC;
5026 TEX_opgrp = '<';
5027 TEX_clgrp = '>';
5029 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5030 No attempt is made to correct the situation. */
5031 rewind (inf);
5034 /* Read environment and prepend it to the default string.
5035 Build token table. */
5036 static void
5037 TEX_decode_env (const char *evarname, const char *defenv)
5039 register const char *env, *p;
5040 int i, len;
5042 /* Append default string to environment. */
5043 env = getenv (evarname);
5044 if (!env)
5045 env = defenv;
5046 else
5047 env = concat (env, defenv, "");
5049 /* Allocate a token table */
5050 for (len = 1, p = env; p;)
5051 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5052 len++;
5053 TEX_toktab = xnew (len, linebuffer);
5055 /* Unpack environment string into token table. Be careful about */
5056 /* zero-length strings (leading ':', "::" and trailing ':') */
5057 for (i = 0; *env != '\0';)
5059 p = etags_strchr (env, ':');
5060 if (!p) /* End of environment string. */
5061 p = env + strlen (env);
5062 if (p - env > 0)
5063 { /* Only non-zero strings. */
5064 TEX_toktab[i].buffer = savenstr (env, p - env);
5065 TEX_toktab[i].len = p - env;
5066 i++;
5068 if (*p)
5069 env = p + 1;
5070 else
5072 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5073 TEX_toktab[i].len = 0;
5074 break;
5080 /* Texinfo support. Dave Love, Mar. 2000. */
5081 static void
5082 Texinfo_nodes (FILE *inf)
5084 char *cp, *start;
5085 LOOP_ON_INPUT_LINES (inf, lb, cp)
5086 if (LOOKING_AT (cp, "@node"))
5088 start = cp;
5089 while (*cp != '\0' && *cp != ',')
5090 cp++;
5091 make_tag (start, cp - start, TRUE,
5092 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5098 * HTML support.
5099 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5100 * Contents of <a name=xxx> are tags with name xxx.
5102 * Francesco Potortì, 2002.
5104 static void
5105 HTML_labels (FILE *inf)
5107 bool getnext = FALSE; /* next text outside of HTML tags is a tag */
5108 bool skiptag = FALSE; /* skip to the end of the current HTML tag */
5109 bool intag = FALSE; /* inside an html tag, looking for ID= */
5110 bool inanchor = FALSE; /* when INTAG, is an anchor, look for NAME= */
5111 char *end;
5114 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5116 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5117 for (;;) /* loop on the same line */
5119 if (skiptag) /* skip HTML tag */
5121 while (*dbp != '\0' && *dbp != '>')
5122 dbp++;
5123 if (*dbp == '>')
5125 dbp += 1;
5126 skiptag = FALSE;
5127 continue; /* look on the same line */
5129 break; /* go to next line */
5132 else if (intag) /* look for "name=" or "id=" */
5134 while (*dbp != '\0' && *dbp != '>'
5135 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5136 dbp++;
5137 if (*dbp == '\0')
5138 break; /* go to next line */
5139 if (*dbp == '>')
5141 dbp += 1;
5142 intag = FALSE;
5143 continue; /* look on the same line */
5145 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5146 || LOOKING_AT_NOCASE (dbp, "id="))
5148 bool quoted = (dbp[0] == '"');
5150 if (quoted)
5151 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5152 continue;
5153 else
5154 for (end = dbp; *end != '\0' && intoken (*end); end++)
5155 continue;
5156 linebuffer_setlen (&token_name, end - dbp);
5157 memcpy (token_name.buffer, dbp, end - dbp);
5158 token_name.buffer[end - dbp] = '\0';
5160 dbp = end;
5161 intag = FALSE; /* we found what we looked for */
5162 skiptag = TRUE; /* skip to the end of the tag */
5163 getnext = TRUE; /* then grab the text */
5164 continue; /* look on the same line */
5166 dbp += 1;
5169 else if (getnext) /* grab next tokens and tag them */
5171 dbp = skip_spaces (dbp);
5172 if (*dbp == '\0')
5173 break; /* go to next line */
5174 if (*dbp == '<')
5176 intag = TRUE;
5177 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5178 continue; /* look on the same line */
5181 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5182 continue;
5183 make_tag (token_name.buffer, token_name.len, TRUE,
5184 dbp, end - dbp, lineno, linecharno);
5185 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5186 getnext = FALSE;
5187 break; /* go to next line */
5190 else /* look for an interesting HTML tag */
5192 while (*dbp != '\0' && *dbp != '<')
5193 dbp++;
5194 if (*dbp == '\0')
5195 break; /* go to next line */
5196 intag = TRUE;
5197 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5199 inanchor = TRUE;
5200 continue; /* look on the same line */
5202 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5203 || LOOKING_AT_NOCASE (dbp, "<h1>")
5204 || LOOKING_AT_NOCASE (dbp, "<h2>")
5205 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5207 intag = FALSE;
5208 getnext = TRUE;
5209 continue; /* look on the same line */
5211 dbp += 1;
5218 * Prolog support
5220 * Assumes that the predicate or rule starts at column 0.
5221 * Only the first clause of a predicate or rule is added.
5222 * Original code by Sunichirou Sugou (1989)
5223 * Rewritten by Anders Lindgren (1996)
5225 static size_t prolog_pr (char *, char *);
5226 static void prolog_skip_comment (linebuffer *, FILE *);
5227 static size_t prolog_atom (char *, size_t);
5229 static void
5230 Prolog_functions (FILE *inf)
5232 char *cp, *last;
5233 size_t len;
5234 size_t allocated;
5236 allocated = 0;
5237 len = 0;
5238 last = NULL;
5240 LOOP_ON_INPUT_LINES (inf, lb, cp)
5242 if (cp[0] == '\0') /* Empty line */
5243 continue;
5244 else if (iswhite (cp[0])) /* Not a predicate */
5245 continue;
5246 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5247 prolog_skip_comment (&lb, inf);
5248 else if ((len = prolog_pr (cp, last)) > 0)
5250 /* Predicate or rule. Store the function name so that we
5251 only generate a tag for the first clause. */
5252 if (last == NULL)
5253 last = xnew (len + 1, char);
5254 else if (len + 1 > allocated)
5255 xrnew (last, len + 1, char);
5256 allocated = len + 1;
5257 memcpy (last, cp, len);
5258 last[len] = '\0';
5261 free (last);
5265 static void
5266 prolog_skip_comment (linebuffer *plb, FILE *inf)
5268 char *cp;
5272 for (cp = plb->buffer; *cp != '\0'; cp++)
5273 if (cp[0] == '*' && cp[1] == '/')
5274 return;
5275 readline (plb, inf);
5277 while (!feof (inf));
5281 * A predicate or rule definition is added if it matches:
5282 * <beginning of line><Prolog Atom><whitespace>(
5283 * or <beginning of line><Prolog Atom><whitespace>:-
5285 * It is added to the tags database if it doesn't match the
5286 * name of the previous clause header.
5288 * Return the size of the name of the predicate or rule, or 0 if no
5289 * header was found.
5291 static size_t
5292 prolog_pr (char *s, char *last)
5294 /* Name of last clause. */
5296 size_t pos;
5297 size_t len;
5299 pos = prolog_atom (s, 0);
5300 if (! pos)
5301 return 0;
5303 len = pos;
5304 pos = skip_spaces (s + pos) - s;
5306 if ((s[pos] == '.'
5307 || (s[pos] == '(' && (pos += 1))
5308 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5309 && (last == NULL /* save only the first clause */
5310 || len != strlen (last)
5311 || !strneq (s, last, len)))
5313 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5314 return len;
5316 else
5317 return 0;
5321 * Consume a Prolog atom.
5322 * Return the number of bytes consumed, or 0 if there was an error.
5324 * A prolog atom, in this context, could be one of:
5325 * - An alphanumeric sequence, starting with a lower case letter.
5326 * - A quoted arbitrary string. Single quotes can escape themselves.
5327 * Backslash quotes everything.
5329 static size_t
5330 prolog_atom (char *s, size_t pos)
5332 size_t origpos;
5334 origpos = pos;
5336 if (ISLOWER (s[pos]) || (s[pos] == '_'))
5338 /* The atom is unquoted. */
5339 pos++;
5340 while (ISALNUM (s[pos]) || (s[pos] == '_'))
5342 pos++;
5344 return pos - origpos;
5346 else if (s[pos] == '\'')
5348 pos++;
5350 for (;;)
5352 if (s[pos] == '\'')
5354 pos++;
5355 if (s[pos] != '\'')
5356 break;
5357 pos++; /* A double quote */
5359 else if (s[pos] == '\0')
5360 /* Multiline quoted atoms are ignored. */
5361 return 0;
5362 else if (s[pos] == '\\')
5364 if (s[pos+1] == '\0')
5365 return 0;
5366 pos += 2;
5368 else
5369 pos++;
5371 return pos - origpos;
5373 else
5374 return 0;
5379 * Support for Erlang
5381 * Generates tags for functions, defines, and records.
5382 * Assumes that Erlang functions start at column 0.
5383 * Original code by Anders Lindgren (1996)
5385 static int erlang_func (char *, char *);
5386 static void erlang_attribute (char *);
5387 static int erlang_atom (char *);
5389 static void
5390 Erlang_functions (FILE *inf)
5392 char *cp, *last;
5393 int len;
5394 int allocated;
5396 allocated = 0;
5397 len = 0;
5398 last = NULL;
5400 LOOP_ON_INPUT_LINES (inf, lb, cp)
5402 if (cp[0] == '\0') /* Empty line */
5403 continue;
5404 else if (iswhite (cp[0])) /* Not function nor attribute */
5405 continue;
5406 else if (cp[0] == '%') /* comment */
5407 continue;
5408 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5409 continue;
5410 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5412 erlang_attribute (cp);
5413 if (last != NULL)
5415 free (last);
5416 last = NULL;
5419 else if ((len = erlang_func (cp, last)) > 0)
5422 * Function. Store the function name so that we only
5423 * generates a tag for the first clause.
5425 if (last == NULL)
5426 last = xnew (len + 1, char);
5427 else if (len + 1 > allocated)
5428 xrnew (last, len + 1, char);
5429 allocated = len + 1;
5430 memcpy (last, cp, len);
5431 last[len] = '\0';
5434 free (last);
5439 * A function definition is added if it matches:
5440 * <beginning of line><Erlang Atom><whitespace>(
5442 * It is added to the tags database if it doesn't match the
5443 * name of the previous clause header.
5445 * Return the size of the name of the function, or 0 if no function
5446 * was found.
5448 static int
5449 erlang_func (char *s, char *last)
5451 /* Name of last clause. */
5453 int pos;
5454 int len;
5456 pos = erlang_atom (s);
5457 if (pos < 1)
5458 return 0;
5460 len = pos;
5461 pos = skip_spaces (s + pos) - s;
5463 /* Save only the first clause. */
5464 if (s[pos++] == '('
5465 && (last == NULL
5466 || len != (int)strlen (last)
5467 || !strneq (s, last, len)))
5469 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5470 return len;
5473 return 0;
5478 * Handle attributes. Currently, tags are generated for defines
5479 * and records.
5481 * They are on the form:
5482 * -define(foo, bar).
5483 * -define(Foo(M, N), M+N).
5484 * -record(graph, {vtab = notable, cyclic = true}).
5486 static void
5487 erlang_attribute (char *s)
5489 char *cp = s;
5491 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5492 && *cp++ == '(')
5494 int len = erlang_atom (skip_spaces (cp));
5495 if (len > 0)
5496 make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5498 return;
5503 * Consume an Erlang atom (or variable).
5504 * Return the number of bytes consumed, or -1 if there was an error.
5506 static int
5507 erlang_atom (char *s)
5509 int pos = 0;
5511 if (ISALPHA (s[pos]) || s[pos] == '_')
5513 /* The atom is unquoted. */
5515 pos++;
5516 while (ISALNUM (s[pos]) || s[pos] == '_');
5518 else if (s[pos] == '\'')
5520 for (pos++; s[pos] != '\''; pos++)
5521 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5522 || (s[pos] == '\\' && s[++pos] == '\0'))
5523 return 0;
5524 pos++;
5527 return pos;
5531 static char *scan_separators (char *);
5532 static void add_regex (char *, language *);
5533 static char *substitute (char *, char *, struct re_registers *);
5536 * Take a string like "/blah/" and turn it into "blah", verifying
5537 * that the first and last characters are the same, and handling
5538 * quoted separator characters. Actually, stops on the occurrence of
5539 * an unquoted separator. Also process \t, \n, etc. and turn into
5540 * appropriate characters. Works in place. Null terminates name string.
5541 * Returns pointer to terminating separator, or NULL for
5542 * unterminated regexps.
5544 static char *
5545 scan_separators (char *name)
5547 char sep = name[0];
5548 char *copyto = name;
5549 bool quoted = FALSE;
5551 for (++name; *name != '\0'; ++name)
5553 if (quoted)
5555 switch (*name)
5557 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
5558 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
5559 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
5560 case 'e': *copyto++ = 033; break; /* ESC (delete) */
5561 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
5562 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
5563 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
5564 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
5565 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
5566 default:
5567 if (*name == sep)
5568 *copyto++ = sep;
5569 else
5571 /* Something else is quoted, so preserve the quote. */
5572 *copyto++ = '\\';
5573 *copyto++ = *name;
5575 break;
5577 quoted = FALSE;
5579 else if (*name == '\\')
5580 quoted = TRUE;
5581 else if (*name == sep)
5582 break;
5583 else
5584 *copyto++ = *name;
5586 if (*name != sep)
5587 name = NULL; /* signal unterminated regexp */
5589 /* Terminate copied string. */
5590 *copyto = '\0';
5591 return name;
5594 /* Look at the argument of --regex or --no-regex and do the right
5595 thing. Same for each line of a regexp file. */
5596 static void
5597 analyse_regex (char *regex_arg)
5599 if (regex_arg == NULL)
5601 free_regexps (); /* --no-regex: remove existing regexps */
5602 return;
5605 /* A real --regexp option or a line in a regexp file. */
5606 switch (regex_arg[0])
5608 /* Comments in regexp file or null arg to --regex. */
5609 case '\0':
5610 case ' ':
5611 case '\t':
5612 break;
5614 /* Read a regex file. This is recursive and may result in a
5615 loop, which will stop when the file descriptors are exhausted. */
5616 case '@':
5618 FILE *regexfp;
5619 linebuffer regexbuf;
5620 char *regexfile = regex_arg + 1;
5622 /* regexfile is a file containing regexps, one per line. */
5623 regexfp = fopen (regexfile, "r");
5624 if (regexfp == NULL)
5626 pfatal (regexfile);
5627 return;
5629 linebuffer_init (&regexbuf);
5630 while (readline_internal (&regexbuf, regexfp) > 0)
5631 analyse_regex (regexbuf.buffer);
5632 free (regexbuf.buffer);
5633 fclose (regexfp);
5635 break;
5637 /* Regexp to be used for a specific language only. */
5638 case '{':
5640 language *lang;
5641 char *lang_name = regex_arg + 1;
5642 char *cp;
5644 for (cp = lang_name; *cp != '}'; cp++)
5645 if (*cp == '\0')
5647 error ("unterminated language name in regex: %s", regex_arg);
5648 return;
5650 *cp++ = '\0';
5651 lang = get_language_from_langname (lang_name);
5652 if (lang == NULL)
5653 return;
5654 add_regex (cp, lang);
5656 break;
5658 /* Regexp to be used for any language. */
5659 default:
5660 add_regex (regex_arg, NULL);
5661 break;
5665 /* Separate the regexp pattern, compile it,
5666 and care for optional name and modifiers. */
5667 static void
5668 add_regex (char *regexp_pattern, language *lang)
5670 static struct re_pattern_buffer zeropattern;
5671 char sep, *pat, *name, *modifiers;
5672 char empty = '\0';
5673 const char *err;
5674 struct re_pattern_buffer *patbuf;
5675 regexp *rp;
5676 bool
5677 force_explicit_name = TRUE, /* do not use implicit tag names */
5678 ignore_case = FALSE, /* case is significant */
5679 multi_line = FALSE, /* matches are done one line at a time */
5680 single_line = FALSE; /* dot does not match newline */
5683 if (strlen (regexp_pattern) < 3)
5685 error ("null regexp");
5686 return;
5688 sep = regexp_pattern[0];
5689 name = scan_separators (regexp_pattern);
5690 if (name == NULL)
5692 error ("%s: unterminated regexp", regexp_pattern);
5693 return;
5695 if (name[1] == sep)
5697 error ("null name for regexp \"%s\"", regexp_pattern);
5698 return;
5700 modifiers = scan_separators (name);
5701 if (modifiers == NULL) /* no terminating separator --> no name */
5703 modifiers = name;
5704 name = &empty;
5706 else
5707 modifiers += 1; /* skip separator */
5709 /* Parse regex modifiers. */
5710 for (; modifiers[0] != '\0'; modifiers++)
5711 switch (modifiers[0])
5713 case 'N':
5714 if (modifiers == name)
5715 error ("forcing explicit tag name but no name, ignoring");
5716 force_explicit_name = TRUE;
5717 break;
5718 case 'i':
5719 ignore_case = TRUE;
5720 break;
5721 case 's':
5722 single_line = TRUE;
5723 /* FALLTHRU */
5724 case 'm':
5725 multi_line = TRUE;
5726 need_filebuf = TRUE;
5727 break;
5728 default:
5729 error ("invalid regexp modifier `%c', ignoring", modifiers[0]);
5730 break;
5733 patbuf = xnew (1, struct re_pattern_buffer);
5734 *patbuf = zeropattern;
5735 if (ignore_case)
5737 static char lc_trans[CHARS];
5738 int i;
5739 for (i = 0; i < CHARS; i++)
5740 lc_trans[i] = lowcase (i);
5741 patbuf->translate = lc_trans; /* translation table to fold case */
5744 if (multi_line)
5745 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
5746 else
5747 pat = regexp_pattern;
5749 if (single_line)
5750 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
5751 else
5752 re_set_syntax (RE_SYNTAX_EMACS);
5754 err = re_compile_pattern (pat, strlen (pat), patbuf);
5755 if (multi_line)
5756 free (pat);
5757 if (err != NULL)
5759 error ("%s while compiling pattern", err);
5760 return;
5763 rp = p_head;
5764 p_head = xnew (1, regexp);
5765 p_head->pattern = savestr (regexp_pattern);
5766 p_head->p_next = rp;
5767 p_head->lang = lang;
5768 p_head->pat = patbuf;
5769 p_head->name = savestr (name);
5770 p_head->error_signaled = FALSE;
5771 p_head->force_explicit_name = force_explicit_name;
5772 p_head->ignore_case = ignore_case;
5773 p_head->multi_line = multi_line;
5777 * Do the substitutions indicated by the regular expression and
5778 * arguments.
5780 static char *
5781 substitute (char *in, char *out, struct re_registers *regs)
5783 char *result, *t;
5784 int size, dig, diglen;
5786 result = NULL;
5787 size = strlen (out);
5789 /* Pass 1: figure out how much to allocate by finding all \N strings. */
5790 if (out[size - 1] == '\\')
5791 fatal ("pattern error in \"%s\"", out);
5792 for (t = etags_strchr (out, '\\');
5793 t != NULL;
5794 t = etags_strchr (t + 2, '\\'))
5795 if (ISDIGIT (t[1]))
5797 dig = t[1] - '0';
5798 diglen = regs->end[dig] - regs->start[dig];
5799 size += diglen - 2;
5801 else
5802 size -= 1;
5804 /* Allocate space and do the substitutions. */
5805 assert (size >= 0);
5806 result = xnew (size + 1, char);
5808 for (t = result; *out != '\0'; out++)
5809 if (*out == '\\' && ISDIGIT (*++out))
5811 dig = *out - '0';
5812 diglen = regs->end[dig] - regs->start[dig];
5813 memcpy (t, in + regs->start[dig], diglen);
5814 t += diglen;
5816 else
5817 *t++ = *out;
5818 *t = '\0';
5820 assert (t <= result + size);
5821 assert (t - result == (int)strlen (result));
5823 return result;
5826 /* Deallocate all regexps. */
5827 static void
5828 free_regexps (void)
5830 regexp *rp;
5831 while (p_head != NULL)
5833 rp = p_head->p_next;
5834 free (p_head->pattern);
5835 free (p_head->name);
5836 free (p_head);
5837 p_head = rp;
5839 return;
5843 * Reads the whole file as a single string from `filebuf' and looks for
5844 * multi-line regular expressions, creating tags on matches.
5845 * readline already dealt with normal regexps.
5847 * Idea by Ben Wing <ben@666.com> (2002).
5849 static void
5850 regex_tag_multiline (void)
5852 char *buffer = filebuf.buffer;
5853 regexp *rp;
5854 char *name;
5856 for (rp = p_head; rp != NULL; rp = rp->p_next)
5858 int match = 0;
5860 if (!rp->multi_line)
5861 continue; /* skip normal regexps */
5863 /* Generic initializations before parsing file from memory. */
5864 lineno = 1; /* reset global line number */
5865 charno = 0; /* reset global char number */
5866 linecharno = 0; /* reset global char number of line start */
5868 /* Only use generic regexps or those for the current language. */
5869 if (rp->lang != NULL && rp->lang != curfdp->lang)
5870 continue;
5872 while (match >= 0 && match < filebuf.len)
5874 match = re_search (rp->pat, buffer, filebuf.len, charno,
5875 filebuf.len - match, &rp->regs);
5876 switch (match)
5878 case -2:
5879 /* Some error. */
5880 if (!rp->error_signaled)
5882 error ("regexp stack overflow while matching \"%s\"",
5883 rp->pattern);
5884 rp->error_signaled = TRUE;
5886 break;
5887 case -1:
5888 /* No match. */
5889 break;
5890 default:
5891 if (match == rp->regs.end[0])
5893 if (!rp->error_signaled)
5895 error ("regexp matches the empty string: \"%s\"",
5896 rp->pattern);
5897 rp->error_signaled = TRUE;
5899 match = -3; /* exit from while loop */
5900 break;
5903 /* Match occurred. Construct a tag. */
5904 while (charno < rp->regs.end[0])
5905 if (buffer[charno++] == '\n')
5906 lineno++, linecharno = charno;
5907 name = rp->name;
5908 if (name[0] == '\0')
5909 name = NULL;
5910 else /* make a named tag */
5911 name = substitute (buffer, rp->name, &rp->regs);
5912 if (rp->force_explicit_name)
5913 /* Force explicit tag name, if a name is there. */
5914 pfnote (name, TRUE, buffer + linecharno,
5915 charno - linecharno + 1, lineno, linecharno);
5916 else
5917 make_tag (name, strlen (name), TRUE, buffer + linecharno,
5918 charno - linecharno + 1, lineno, linecharno);
5919 break;
5926 static bool
5927 nocase_tail (const char *cp)
5929 register int len = 0;
5931 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
5932 cp++, len++;
5933 if (*cp == '\0' && !intoken (dbp[len]))
5935 dbp += len;
5936 return TRUE;
5938 return FALSE;
5941 static void
5942 get_tag (register char *bp, char **namepp)
5944 register char *cp = bp;
5946 if (*bp != '\0')
5948 /* Go till you get to white space or a syntactic break */
5949 for (cp = bp + 1; !notinname (*cp); cp++)
5950 continue;
5951 make_tag (bp, cp - bp, TRUE,
5952 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5955 if (namepp != NULL)
5956 *namepp = savenstr (bp, cp - bp);
5960 * Read a line of text from `stream' into `lbp', excluding the
5961 * newline or CR-NL, if any. Return the number of characters read from
5962 * `stream', which is the length of the line including the newline.
5964 * On DOS or Windows we do not count the CR character, if any before the
5965 * NL, in the returned length; this mirrors the behavior of Emacs on those
5966 * platforms (for text files, it translates CR-NL to NL as it reads in the
5967 * file).
5969 * If multi-line regular expressions are requested, each line read is
5970 * appended to `filebuf'.
5972 static long
5973 readline_internal (linebuffer *lbp, register FILE *stream)
5975 char *buffer = lbp->buffer;
5976 register char *p = lbp->buffer;
5977 register char *pend;
5978 int chars_deleted;
5980 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
5982 for (;;)
5984 register int c = getc (stream);
5985 if (p == pend)
5987 /* We're at the end of linebuffer: expand it. */
5988 lbp->size *= 2;
5989 xrnew (buffer, lbp->size, char);
5990 p += buffer - lbp->buffer;
5991 pend = buffer + lbp->size;
5992 lbp->buffer = buffer;
5994 if (c == EOF)
5996 *p = '\0';
5997 chars_deleted = 0;
5998 break;
6000 if (c == '\n')
6002 if (p > buffer && p[-1] == '\r')
6004 p -= 1;
6005 #ifdef DOS_NT
6006 /* Assume CRLF->LF translation will be performed by Emacs
6007 when loading this file, so CRs won't appear in the buffer.
6008 It would be cleaner to compensate within Emacs;
6009 however, Emacs does not know how many CRs were deleted
6010 before any given point in the file. */
6011 chars_deleted = 1;
6012 #else
6013 chars_deleted = 2;
6014 #endif
6016 else
6018 chars_deleted = 1;
6020 *p = '\0';
6021 break;
6023 *p++ = c;
6025 lbp->len = p - buffer;
6027 if (need_filebuf /* we need filebuf for multi-line regexps */
6028 && chars_deleted > 0) /* not at EOF */
6030 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6032 /* Expand filebuf. */
6033 filebuf.size *= 2;
6034 xrnew (filebuf.buffer, filebuf.size, char);
6036 memcpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6037 filebuf.len += lbp->len;
6038 filebuf.buffer[filebuf.len++] = '\n';
6039 filebuf.buffer[filebuf.len] = '\0';
6042 return lbp->len + chars_deleted;
6046 * Like readline_internal, above, but in addition try to match the
6047 * input line against relevant regular expressions and manage #line
6048 * directives.
6050 static void
6051 readline (linebuffer *lbp, FILE *stream)
6053 long result;
6055 linecharno = charno; /* update global char number of line start */
6056 result = readline_internal (lbp, stream); /* read line */
6057 lineno += 1; /* increment global line number */
6058 charno += result; /* increment global char number */
6060 /* Honor #line directives. */
6061 if (!no_line_directive)
6063 static bool discard_until_line_directive;
6065 /* Check whether this is a #line directive. */
6066 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6068 unsigned int lno;
6069 int start = 0;
6071 if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6072 && start > 0) /* double quote character found */
6074 char *endp = lbp->buffer + start;
6076 while ((endp = etags_strchr (endp, '"')) != NULL
6077 && endp[-1] == '\\')
6078 endp++;
6079 if (endp != NULL)
6080 /* Ok, this is a real #line directive. Let's deal with it. */
6082 char *taggedabsname; /* absolute name of original file */
6083 char *taggedfname; /* name of original file as given */
6084 char *name; /* temp var */
6086 discard_until_line_directive = FALSE; /* found it */
6087 name = lbp->buffer + start;
6088 *endp = '\0';
6089 canonicalize_filename (name);
6090 taggedabsname = absolute_filename (name, tagfiledir);
6091 if (filename_is_absolute (name)
6092 || filename_is_absolute (curfdp->infname))
6093 taggedfname = savestr (taggedabsname);
6094 else
6095 taggedfname = relative_filename (taggedabsname,tagfiledir);
6097 if (streq (curfdp->taggedfname, taggedfname))
6098 /* The #line directive is only a line number change. We
6099 deal with this afterwards. */
6100 free (taggedfname);
6101 else
6102 /* The tags following this #line directive should be
6103 attributed to taggedfname. In order to do this, set
6104 curfdp accordingly. */
6106 fdesc *fdp; /* file description pointer */
6108 /* Go look for a file description already set up for the
6109 file indicated in the #line directive. If there is
6110 one, use it from now until the next #line
6111 directive. */
6112 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6113 if (streq (fdp->infname, curfdp->infname)
6114 && streq (fdp->taggedfname, taggedfname))
6115 /* If we remove the second test above (after the &&)
6116 then all entries pertaining to the same file are
6117 coalesced in the tags file. If we use it, then
6118 entries pertaining to the same file but generated
6119 from different files (via #line directives) will
6120 go into separate sections in the tags file. These
6121 alternatives look equivalent. The first one
6122 destroys some apparently useless information. */
6124 curfdp = fdp;
6125 free (taggedfname);
6126 break;
6128 /* Else, if we already tagged the real file, skip all
6129 input lines until the next #line directive. */
6130 if (fdp == NULL) /* not found */
6131 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6132 if (streq (fdp->infabsname, taggedabsname))
6134 discard_until_line_directive = TRUE;
6135 free (taggedfname);
6136 break;
6138 /* Else create a new file description and use that from
6139 now on, until the next #line directive. */
6140 if (fdp == NULL) /* not found */
6142 fdp = fdhead;
6143 fdhead = xnew (1, fdesc);
6144 *fdhead = *curfdp; /* copy curr. file description */
6145 fdhead->next = fdp;
6146 fdhead->infname = savestr (curfdp->infname);
6147 fdhead->infabsname = savestr (curfdp->infabsname);
6148 fdhead->infabsdir = savestr (curfdp->infabsdir);
6149 fdhead->taggedfname = taggedfname;
6150 fdhead->usecharno = FALSE;
6151 fdhead->prop = NULL;
6152 fdhead->written = FALSE;
6153 curfdp = fdhead;
6156 free (taggedabsname);
6157 lineno = lno - 1;
6158 readline (lbp, stream);
6159 return;
6160 } /* if a real #line directive */
6161 } /* if #line is followed by a number */
6162 } /* if line begins with "#line " */
6164 /* If we are here, no #line directive was found. */
6165 if (discard_until_line_directive)
6167 if (result > 0)
6169 /* Do a tail recursion on ourselves, thus discarding the contents
6170 of the line buffer. */
6171 readline (lbp, stream);
6172 return;
6174 /* End of file. */
6175 discard_until_line_directive = FALSE;
6176 return;
6178 } /* if #line directives should be considered */
6181 int match;
6182 regexp *rp;
6183 char *name;
6185 /* Match against relevant regexps. */
6186 if (lbp->len > 0)
6187 for (rp = p_head; rp != NULL; rp = rp->p_next)
6189 /* Only use generic regexps or those for the current language.
6190 Also do not use multiline regexps, which is the job of
6191 regex_tag_multiline. */
6192 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6193 || rp->multi_line)
6194 continue;
6196 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6197 switch (match)
6199 case -2:
6200 /* Some error. */
6201 if (!rp->error_signaled)
6203 error ("regexp stack overflow while matching \"%s\"",
6204 rp->pattern);
6205 rp->error_signaled = TRUE;
6207 break;
6208 case -1:
6209 /* No match. */
6210 break;
6211 case 0:
6212 /* Empty string matched. */
6213 if (!rp->error_signaled)
6215 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6216 rp->error_signaled = TRUE;
6218 break;
6219 default:
6220 /* Match occurred. Construct a tag. */
6221 name = rp->name;
6222 if (name[0] == '\0')
6223 name = NULL;
6224 else /* make a named tag */
6225 name = substitute (lbp->buffer, rp->name, &rp->regs);
6226 if (rp->force_explicit_name)
6227 /* Force explicit tag name, if a name is there. */
6228 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6229 else
6230 make_tag (name, strlen (name), TRUE,
6231 lbp->buffer, match, lineno, linecharno);
6232 break;
6240 * Return a pointer to a space of size strlen(cp)+1 allocated
6241 * with xnew where the string CP has been copied.
6243 static char *
6244 savestr (const char *cp)
6246 return savenstr (cp, strlen (cp));
6250 * Return a pointer to a space of size LEN+1 allocated with xnew where
6251 * the string CP has been copied for at most the first LEN characters.
6253 static char *
6254 savenstr (const char *cp, int len)
6256 register char *dp;
6258 dp = xnew (len + 1, char);
6259 memcpy (dp, cp, len);
6260 dp[len] = '\0';
6261 return dp;
6265 * Return the ptr in sp at which the character c last
6266 * appears; NULL if not found
6268 * Identical to POSIX strrchr, included for portability.
6270 static char *
6271 etags_strrchr (register const char *sp, register int c)
6273 register const char *r;
6275 r = NULL;
6278 if (*sp == c)
6279 r = sp;
6280 } while (*sp++);
6281 return (char *)r;
6285 * Return the ptr in sp at which the character c first
6286 * appears; NULL if not found
6288 * Identical to POSIX strchr, included for portability.
6290 static char *
6291 etags_strchr (register const char *sp, register int c)
6295 if (*sp == c)
6296 return (char *)sp;
6297 } while (*sp++);
6298 return NULL;
6301 /* Skip spaces (end of string is not space), return new pointer. */
6302 static char *
6303 skip_spaces (char *cp)
6305 while (iswhite (*cp))
6306 cp++;
6307 return cp;
6310 /* Skip non spaces, except end of string, return new pointer. */
6311 static char *
6312 skip_non_spaces (char *cp)
6314 while (*cp != '\0' && !iswhite (*cp))
6315 cp++;
6316 return cp;
6319 /* Print error message and exit. */
6320 void
6321 fatal (const char *s1, const char *s2)
6323 error (s1, s2);
6324 exit (EXIT_FAILURE);
6327 static void
6328 pfatal (const char *s1)
6330 perror (s1);
6331 exit (EXIT_FAILURE);
6334 static void
6335 suggest_asking_for_help (void)
6337 fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6338 progname, NO_LONG_OPTIONS ? "-h" : "--help");
6339 exit (EXIT_FAILURE);
6342 /* Output a diagnostic with printf-style FORMAT and args. */
6343 static void
6344 error (const char *format, ...)
6346 va_list ap;
6347 va_start (ap, format);
6348 fprintf (stderr, "%s: ", progname);
6349 vfprintf (stderr, format, ap);
6350 fprintf (stderr, "\n");
6351 va_end (ap);
6354 /* Return a newly-allocated string whose contents
6355 concatenate those of s1, s2, s3. */
6356 static char *
6357 concat (const char *s1, const char *s2, const char *s3)
6359 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6360 char *result = xnew (len1 + len2 + len3 + 1, char);
6362 strcpy (result, s1);
6363 strcpy (result + len1, s2);
6364 strcpy (result + len1 + len2, s3);
6365 result[len1 + len2 + len3] = '\0';
6367 return result;
6371 /* Does the same work as the system V getcwd, but does not need to
6372 guess the buffer size in advance. */
6373 static char *
6374 etags_getcwd (void)
6376 #ifdef HAVE_GETCWD
6377 int bufsize = 200;
6378 char *path = xnew (bufsize, char);
6380 while (getcwd (path, bufsize) == NULL)
6382 if (errno != ERANGE)
6383 pfatal ("getcwd");
6384 bufsize *= 2;
6385 free (path);
6386 path = xnew (bufsize, char);
6389 canonicalize_filename (path);
6390 return path;
6392 #else /* not HAVE_GETCWD */
6393 #if MSDOS
6395 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
6397 getwd (path);
6399 for (p = path; *p != '\0'; p++)
6400 if (*p == '\\')
6401 *p = '/';
6402 else
6403 *p = lowcase (*p);
6405 return strdup (path);
6406 #else /* not MSDOS */
6407 linebuffer path;
6408 FILE *pipe;
6410 linebuffer_init (&path);
6411 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6412 if (pipe == NULL || readline_internal (&path, pipe) == 0)
6413 pfatal ("pwd");
6414 pclose (pipe);
6416 return path.buffer;
6417 #endif /* not MSDOS */
6418 #endif /* not HAVE_GETCWD */
6421 /* Return a newly allocated string containing the file name of FILE
6422 relative to the absolute directory DIR (which should end with a slash). */
6423 static char *
6424 relative_filename (char *file, char *dir)
6426 char *fp, *dp, *afn, *res;
6427 int i;
6429 /* Find the common root of file and dir (with a trailing slash). */
6430 afn = absolute_filename (file, cwd);
6431 fp = afn;
6432 dp = dir;
6433 while (*fp++ == *dp++)
6434 continue;
6435 fp--, dp--; /* back to the first differing char */
6436 #ifdef DOS_NT
6437 if (fp == afn && afn[0] != '/') /* cannot build a relative name */
6438 return afn;
6439 #endif
6440 do /* look at the equal chars until '/' */
6441 fp--, dp--;
6442 while (*fp != '/');
6444 /* Build a sequence of "../" strings for the resulting relative file name. */
6445 i = 0;
6446 while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6447 i += 1;
6448 res = xnew (3*i + strlen (fp + 1) + 1, char);
6449 res[0] = '\0';
6450 while (i-- > 0)
6451 strcat (res, "../");
6453 /* Add the file name relative to the common root of file and dir. */
6454 strcat (res, fp + 1);
6455 free (afn);
6457 return res;
6460 /* Return a newly allocated string containing the absolute file name
6461 of FILE given DIR (which should end with a slash). */
6462 static char *
6463 absolute_filename (char *file, char *dir)
6465 char *slashp, *cp, *res;
6467 if (filename_is_absolute (file))
6468 res = savestr (file);
6469 #ifdef DOS_NT
6470 /* We don't support non-absolute file names with a drive
6471 letter, like `d:NAME' (it's too much hassle). */
6472 else if (file[1] == ':')
6473 fatal ("%s: relative file names with drive letters not supported", file);
6474 #endif
6475 else
6476 res = concat (dir, file, "");
6478 /* Delete the "/dirname/.." and "/." substrings. */
6479 slashp = etags_strchr (res, '/');
6480 while (slashp != NULL && slashp[0] != '\0')
6482 if (slashp[1] == '.')
6484 if (slashp[2] == '.'
6485 && (slashp[3] == '/' || slashp[3] == '\0'))
6487 cp = slashp;
6489 cp--;
6490 while (cp >= res && !filename_is_absolute (cp));
6491 if (cp < res)
6492 cp = slashp; /* the absolute name begins with "/.." */
6493 #ifdef DOS_NT
6494 /* Under MSDOS and NT we get `d:/NAME' as absolute
6495 file name, so the luser could say `d:/../NAME'.
6496 We silently treat this as `d:/NAME'. */
6497 else if (cp[0] != '/')
6498 cp = slashp;
6499 #endif
6500 memmove (cp, slashp + 3, strlen (slashp + 2));
6501 slashp = cp;
6502 continue;
6504 else if (slashp[2] == '/' || slashp[2] == '\0')
6506 memmove (slashp, slashp + 2, strlen (slashp + 1));
6507 continue;
6511 slashp = etags_strchr (slashp + 1, '/');
6514 if (res[0] == '\0') /* just a safety net: should never happen */
6516 free (res);
6517 return savestr ("/");
6519 else
6520 return res;
6523 /* Return a newly allocated string containing the absolute
6524 file name of dir where FILE resides given DIR (which should
6525 end with a slash). */
6526 static char *
6527 absolute_dirname (char *file, char *dir)
6529 char *slashp, *res;
6530 char save;
6532 slashp = etags_strrchr (file, '/');
6533 if (slashp == NULL)
6534 return savestr (dir);
6535 save = slashp[1];
6536 slashp[1] = '\0';
6537 res = absolute_filename (file, dir);
6538 slashp[1] = save;
6540 return res;
6543 /* Whether the argument string is an absolute file name. The argument
6544 string must have been canonicalized with canonicalize_filename. */
6545 static bool
6546 filename_is_absolute (char *fn)
6548 return (fn[0] == '/'
6549 #ifdef DOS_NT
6550 || (ISALPHA (fn[0]) && fn[1] == ':' && fn[2] == '/')
6551 #endif
6555 /* Downcase DOS drive letter and collapse separators into single slashes.
6556 Works in place. */
6557 static void
6558 canonicalize_filename (register char *fn)
6560 register char* cp;
6561 char sep = '/';
6563 #ifdef DOS_NT
6564 /* Canonicalize drive letter case. */
6565 # define ISUPPER(c) isupper (CHAR (c))
6566 if (fn[0] != '\0' && fn[1] == ':' && ISUPPER (fn[0]))
6567 fn[0] = lowcase (fn[0]);
6569 sep = '\\';
6570 #endif
6572 /* Collapse multiple separators into a single slash. */
6573 for (cp = fn; *cp != '\0'; cp++, fn++)
6574 if (*cp == sep)
6576 *fn = '/';
6577 while (cp[1] == sep)
6578 cp++;
6580 else
6581 *fn = *cp;
6582 *fn = '\0';
6586 /* Initialize a linebuffer for use. */
6587 static void
6588 linebuffer_init (linebuffer *lbp)
6590 lbp->size = (DEBUG) ? 3 : 200;
6591 lbp->buffer = xnew (lbp->size, char);
6592 lbp->buffer[0] = '\0';
6593 lbp->len = 0;
6596 /* Set the minimum size of a string contained in a linebuffer. */
6597 static void
6598 linebuffer_setlen (linebuffer *lbp, int toksize)
6600 while (lbp->size <= toksize)
6602 lbp->size *= 2;
6603 xrnew (lbp->buffer, lbp->size, char);
6605 lbp->len = toksize;
6608 /* Like malloc but get fatal error if memory is exhausted. */
6609 static void *
6610 xmalloc (size_t size)
6612 void *result = malloc (size);
6613 if (result == NULL)
6614 fatal ("virtual memory exhausted", (char *)NULL);
6615 return result;
6618 static void *
6619 xrealloc (char *ptr, size_t size)
6621 void *result = realloc (ptr, size);
6622 if (result == NULL)
6623 fatal ("virtual memory exhausted", (char *)NULL);
6624 return result;
6628 * Local Variables:
6629 * indent-tabs-mode: t
6630 * tab-width: 8
6631 * fill-column: 79
6632 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
6633 * c-file-style: "gnu"
6634 * End:
6637 /* etags.c ends here */