* progmodes/compile.el: Make all faces inherit from font-lock faces.
[emacs.git] / lib-src / etags.c
blob9471c0fe29fe60d05ced13d6d3c77c923ccd97a8
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-2011
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 #ifdef HAVE_CONFIG_H
95 # include <config.h>
96 /* On some systems, Emacs defines static as nothing for the sake
97 of unexec. We don't want that here since we don't use unexec. */
98 # undef static
99 # ifndef PTR /* for XEmacs */
100 # define PTR void *
101 # endif
102 #else /* no config.h */
103 # if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
104 # define PTR void * /* for generic pointers */
105 # else /* not standard C */
106 # define const /* remove const for old compilers' sake */
107 # define PTR long * /* don't use void* */
108 # endif
109 #endif /* !HAVE_CONFIG_H */
111 #ifndef _GNU_SOURCE
112 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
113 #endif
115 /* WIN32_NATIVE is for XEmacs.
116 MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
117 #ifdef WIN32_NATIVE
118 # undef MSDOS
119 # undef WINDOWSNT
120 # define WINDOWSNT
121 #endif /* WIN32_NATIVE */
123 #ifdef MSDOS
124 # undef MSDOS
125 # define MSDOS TRUE
126 # include <fcntl.h>
127 # include <sys/param.h>
128 # include <io.h>
129 # ifndef HAVE_CONFIG_H
130 # define DOS_NT
131 # include <sys/config.h>
132 # endif
133 #else
134 # define MSDOS FALSE
135 #endif /* MSDOS */
137 #ifdef WINDOWSNT
138 # include <stdlib.h>
139 # include <fcntl.h>
140 # include <string.h>
141 # include <direct.h>
142 # include <io.h>
143 # define MAXPATHLEN _MAX_PATH
144 # undef HAVE_NTGUI
145 # undef DOS_NT
146 # define DOS_NT
147 # ifndef HAVE_GETCWD
148 # define HAVE_GETCWD
149 # endif /* undef HAVE_GETCWD */
150 #else /* not WINDOWSNT */
151 # ifdef STDC_HEADERS
152 # include <stdlib.h>
153 # include <string.h>
154 # else /* no standard C headers */
155 extern char *getenv (const char *);
156 extern char *strcpy (char *, const char *);
157 extern char *strncpy (char *, const char *, unsigned long);
158 extern char *strcat (char *, const char *);
159 extern char *strncat (char *, const char *, unsigned long);
160 extern int strcmp (const char *, const char *);
161 extern int strncmp (const char *, const char *, unsigned long);
162 extern int system (const char *);
163 extern unsigned long strlen (const char *);
164 extern void *malloc (unsigned long);
165 extern void *realloc (void *, unsigned long);
166 extern void exit (int);
167 extern void free (void *);
168 extern void *memmove (void *, const void *, unsigned long);
169 # define EXIT_SUCCESS 0
170 # define EXIT_FAILURE 1
171 # endif
172 #endif /* !WINDOWSNT */
174 #include <unistd.h>
175 #ifndef HAVE_UNISTD_H
176 # if defined (HAVE_GETCWD) && !defined (WINDOWSNT)
177 extern char *getcwd (char *buf, size_t size);
178 # endif
179 #endif /* HAVE_UNISTD_H */
181 #include <stdio.h>
182 #include <ctype.h>
183 #include <errno.h>
184 #include <sys/types.h>
185 #include <sys/stat.h>
187 #include <assert.h>
188 #ifdef NDEBUG
189 # undef assert /* some systems have a buggy assert.h */
190 # define assert(x) ((void) 0)
191 #endif
193 #if !defined (S_ISREG) && defined (S_IFREG)
194 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
195 #endif
197 #ifdef NO_LONG_OPTIONS /* define this if you don't have GNU getopt */
198 # define NO_LONG_OPTIONS TRUE
199 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
200 extern char *optarg;
201 extern int optind, opterr;
202 #else
203 # define NO_LONG_OPTIONS FALSE
204 # include <getopt.h>
205 #endif /* NO_LONG_OPTIONS */
207 #ifndef HAVE_CONFIG_H /* this is a standalone compilation */
208 # ifdef __CYGWIN__ /* compiling on Cygwin */
209 !!! NOTICE !!!
210 the regex.h distributed with Cygwin is not compatible with etags, alas!
211 If you want regular expression support, you should delete this notice and
212 arrange to use the GNU regex.h and regex.c.
213 # endif
214 #endif
215 #include <regex.h>
217 /* Define CTAGS to make the program "ctags" compatible with the usual one.
218 Leave it undefined to make the program "etags", which makes emacs-style
219 tag tables and tags typedefs, #defines and struct/union/enum by default. */
220 #ifdef CTAGS
221 # undef CTAGS
222 # define CTAGS TRUE
223 #else
224 # define CTAGS FALSE
225 #endif
227 #define streq(s,t) (assert((s)!=NULL || (t)!=NULL), !strcmp (s, t))
228 #define strcaseeq(s,t) (assert((s)!=NULL && (t)!=NULL), !etags_strcasecmp (s, t))
229 #define strneq(s,t,n) (assert((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
230 #define strncaseeq(s,t,n) (assert((s)!=NULL && (t)!=NULL), !etags_strncasecmp (s, t, n))
232 #define CHARS 256 /* 2^sizeof(char) */
233 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
234 #define iswhite(c) (_wht[CHAR(c)]) /* c is white (see white) */
235 #define notinname(c) (_nin[CHAR(c)]) /* c is not in a name (see nonam) */
236 #define begtoken(c) (_btk[CHAR(c)]) /* c can start token (see begtk) */
237 #define intoken(c) (_itk[CHAR(c)]) /* c can be in token (see midtk) */
238 #define endtoken(c) (_etk[CHAR(c)]) /* c ends tokens (see endtk) */
240 #define ISALNUM(c) isalnum (CHAR(c))
241 #define ISALPHA(c) isalpha (CHAR(c))
242 #define ISDIGIT(c) isdigit (CHAR(c))
243 #define ISLOWER(c) islower (CHAR(c))
245 #define lowcase(c) tolower (CHAR(c))
246 #define upcase(c) toupper (CHAR(c))
250 * xnew, xrnew -- allocate, reallocate storage
252 * SYNOPSIS: Type *xnew (int n, Type);
253 * void xrnew (OldPointer, int n, Type);
255 #if DEBUG
256 # include "chkmalloc.h"
257 # define xnew(n,Type) ((Type *) trace_malloc (__FILE__, __LINE__, \
258 (n) * sizeof (Type)))
259 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
260 (char *) (op), (n) * sizeof (Type)))
261 #else
262 # define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
263 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
264 (char *) (op), (n) * sizeof (Type)))
265 #endif
267 #define bool int
269 typedef void Lang_function (FILE *);
271 typedef struct
273 const char *suffix; /* file name suffix for this compressor */
274 const char *command; /* takes one arg and decompresses to stdout */
275 } compressor;
277 typedef struct
279 const char *name; /* language name */
280 const char *help; /* detailed help for the language */
281 Lang_function *function; /* parse function */
282 const char **suffixes; /* name suffixes of this language's files */
283 const char **filenames; /* names of this language's files */
284 const char **interpreters; /* interpreters for this language */
285 bool metasource; /* source used to generate other sources */
286 } language;
288 typedef struct fdesc
290 struct fdesc *next; /* for the linked list */
291 char *infname; /* uncompressed input file name */
292 char *infabsname; /* absolute uncompressed input file name */
293 char *infabsdir; /* absolute dir of input file */
294 char *taggedfname; /* file name to write in tagfile */
295 language *lang; /* language of file */
296 char *prop; /* file properties to write in tagfile */
297 bool usecharno; /* etags tags shall contain char number */
298 bool written; /* entry written in the tags file */
299 } fdesc;
301 typedef struct node_st
302 { /* sorting structure */
303 struct node_st *left, *right; /* left and right sons */
304 fdesc *fdp; /* description of file to whom tag belongs */
305 char *name; /* tag name */
306 char *regex; /* search regexp */
307 bool valid; /* write this tag on the tag file */
308 bool is_func; /* function tag: use regexp in CTAGS mode */
309 bool been_warned; /* warning already given for duplicated tag */
310 int lno; /* line number tag is on */
311 long cno; /* character number line starts on */
312 } node;
315 * A `linebuffer' is a structure which holds a line of text.
316 * `readline_internal' reads a line from a stream into a linebuffer
317 * and works regardless of the length of the line.
318 * SIZE is the size of BUFFER, LEN is the length of the string in
319 * BUFFER after readline reads it.
321 typedef struct
323 long size;
324 int len;
325 char *buffer;
326 } linebuffer;
328 /* Used to support mixing of --lang and file names. */
329 typedef struct
331 enum {
332 at_language, /* a language specification */
333 at_regexp, /* a regular expression */
334 at_filename, /* a file name */
335 at_stdin, /* read from stdin here */
336 at_end /* stop parsing the list */
337 } arg_type; /* argument type */
338 language *lang; /* language associated with the argument */
339 char *what; /* the argument itself */
340 } argument;
342 /* Structure defining a regular expression. */
343 typedef struct regexp
345 struct regexp *p_next; /* pointer to next in list */
346 language *lang; /* if set, use only for this language */
347 char *pattern; /* the regexp pattern */
348 char *name; /* tag name */
349 struct re_pattern_buffer *pat; /* the compiled pattern */
350 struct re_registers regs; /* re registers */
351 bool error_signaled; /* already signaled for this regexp */
352 bool force_explicit_name; /* do not allow implict tag name */
353 bool ignore_case; /* ignore case when matching */
354 bool multi_line; /* do a multi-line match on the whole file */
355 } regexp;
358 /* Many compilers barf on this:
359 Lang_function Ada_funcs;
360 so let's write it this way */
361 static void Ada_funcs (FILE *);
362 static void Asm_labels (FILE *);
363 static void C_entries (int c_ext, FILE *);
364 static void default_C_entries (FILE *);
365 static void plain_C_entries (FILE *);
366 static void Cjava_entries (FILE *);
367 static void Cobol_paragraphs (FILE *);
368 static void Cplusplus_entries (FILE *);
369 static void Cstar_entries (FILE *);
370 static void Erlang_functions (FILE *);
371 static void Forth_words (FILE *);
372 static void Fortran_functions (FILE *);
373 static void HTML_labels (FILE *);
374 static void Lisp_functions (FILE *);
375 static void Lua_functions (FILE *);
376 static void Makefile_targets (FILE *);
377 static void Pascal_functions (FILE *);
378 static void Perl_functions (FILE *);
379 static void PHP_functions (FILE *);
380 static void PS_functions (FILE *);
381 static void Prolog_functions (FILE *);
382 static void Python_functions (FILE *);
383 static void Scheme_functions (FILE *);
384 static void TeX_commands (FILE *);
385 static void Texinfo_nodes (FILE *);
386 static void Yacc_entries (FILE *);
387 static void just_read_file (FILE *);
389 static void print_language_names (void);
390 static void print_version (void);
391 static void print_help (argument *);
392 int main (int, char **);
394 static compressor *get_compressor_from_suffix (char *, char **);
395 static language *get_language_from_langname (const char *);
396 static language *get_language_from_interpreter (char *);
397 static language *get_language_from_filename (char *, bool);
398 static void readline (linebuffer *, FILE *);
399 static long readline_internal (linebuffer *, FILE *);
400 static bool nocase_tail (const char *);
401 static void get_tag (char *, char **);
403 static void analyse_regex (char *);
404 static void free_regexps (void);
405 static void regex_tag_multiline (void);
406 static void error (const char *, const char *);
407 static void suggest_asking_for_help (void) NO_RETURN;
408 void fatal (const char *, const char *) NO_RETURN;
409 static void pfatal (const char *) NO_RETURN;
410 static void add_node (node *, node **);
412 static void init (void);
413 static void process_file_name (char *, language *);
414 static void process_file (FILE *, char *, language *);
415 static void find_entries (FILE *);
416 static void free_tree (node *);
417 static void free_fdesc (fdesc *);
418 static void pfnote (char *, bool, char *, int, int, long);
419 static void make_tag (const char *, int, bool, char *, int, int, long);
420 static void invalidate_nodes (fdesc *, node **);
421 static void put_entries (node *);
423 static char *concat (const char *, const char *, const char *);
424 static char *skip_spaces (char *);
425 static char *skip_non_spaces (char *);
426 static char *savenstr (const char *, int);
427 static char *savestr (const char *);
428 static char *etags_strchr (const char *, int);
429 static char *etags_strrchr (const char *, int);
430 static int etags_strcasecmp (const char *, const char *);
431 static int etags_strncasecmp (const char *, const char *, int);
432 static char *etags_getcwd (void);
433 static char *relative_filename (char *, char *);
434 static char *absolute_filename (char *, char *);
435 static char *absolute_dirname (char *, char *);
436 static bool filename_is_absolute (char *f);
437 static void canonicalize_filename (char *);
438 static void linebuffer_init (linebuffer *);
439 static void linebuffer_setlen (linebuffer *, int);
440 static PTR xmalloc (unsigned int);
441 static PTR xrealloc (char *, unsigned int);
444 static char searchar = '/'; /* use /.../ searches */
446 static char *tagfile; /* output file */
447 static char *progname; /* name this program was invoked with */
448 static char *cwd; /* current working directory */
449 static char *tagfiledir; /* directory of tagfile */
450 static FILE *tagf; /* ioptr for tags file */
452 static fdesc *fdhead; /* head of file description list */
453 static fdesc *curfdp; /* current file description */
454 static int lineno; /* line number of current line */
455 static long charno; /* current character number */
456 static long linecharno; /* charno of start of current line */
457 static char *dbp; /* pointer to start of current tag */
459 static const int invalidcharno = -1;
461 static node *nodehead; /* the head of the binary tree of tags */
462 static node *last_node; /* the last node created */
464 static linebuffer lb; /* the current line */
465 static linebuffer filebuf; /* a buffer containing the whole file */
466 static linebuffer token_name; /* a buffer containing a tag name */
468 /* boolean "functions" (see init) */
469 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
470 static const char
471 /* white chars */
472 *white = " \f\t\n\r\v",
473 /* not in a name */
474 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
475 /* token ending chars */
476 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
477 /* token starting chars */
478 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
479 /* valid in-token chars */
480 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
482 static bool append_to_tagfile; /* -a: append to tags */
483 /* The next five default to TRUE in C and derived languages. */
484 static bool typedefs; /* -t: create tags for C and Ada typedefs */
485 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
486 /* 0 struct/enum/union decls, and C++ */
487 /* member functions. */
488 static bool constantypedefs; /* -d: create tags for C #define, enum */
489 /* constants and variables. */
490 /* -D: opposite of -d. Default under ctags. */
491 static bool globals; /* create tags for global variables */
492 static bool members; /* create tags for C member variables */
493 static bool declarations; /* --declarations: tag them and extern in C&Co*/
494 static bool no_line_directive; /* ignore #line directives (undocumented) */
495 static bool no_duplicates; /* no duplicate tags for ctags (undocumented) */
496 static bool update; /* -u: update tags */
497 static bool vgrind_style; /* -v: create vgrind style index output */
498 static bool no_warnings; /* -w: suppress warnings (undocumented) */
499 static bool cxref_style; /* -x: create cxref style output */
500 static bool cplusplus; /* .[hc] means C++, not C (undocumented) */
501 static bool ignoreindent; /* -I: ignore indentation in C */
502 static bool packages_only; /* --packages-only: in Ada, only tag packages*/
504 /* STDIN is defined in LynxOS system headers */
505 #ifdef STDIN
506 # undef STDIN
507 #endif
509 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
510 static bool parsing_stdin; /* --parse-stdin used */
512 static regexp *p_head; /* list of all regexps */
513 static bool need_filebuf; /* some regexes are multi-line */
515 static struct option longopts[] =
517 { "append", no_argument, NULL, 'a' },
518 { "packages-only", no_argument, &packages_only, TRUE },
519 { "c++", no_argument, NULL, 'C' },
520 { "declarations", no_argument, &declarations, TRUE },
521 { "no-line-directive", no_argument, &no_line_directive, TRUE },
522 { "no-duplicates", no_argument, &no_duplicates, TRUE },
523 { "help", no_argument, NULL, 'h' },
524 { "help", no_argument, NULL, 'H' },
525 { "ignore-indentation", no_argument, NULL, 'I' },
526 { "language", required_argument, NULL, 'l' },
527 { "members", no_argument, &members, TRUE },
528 { "no-members", no_argument, &members, FALSE },
529 { "output", required_argument, NULL, 'o' },
530 { "regex", required_argument, NULL, 'r' },
531 { "no-regex", no_argument, NULL, 'R' },
532 { "ignore-case-regex", required_argument, NULL, 'c' },
533 { "parse-stdin", required_argument, NULL, STDIN },
534 { "version", no_argument, NULL, 'V' },
536 #if CTAGS /* Ctags options */
537 { "backward-search", no_argument, NULL, 'B' },
538 { "cxref", no_argument, NULL, 'x' },
539 { "defines", no_argument, NULL, 'd' },
540 { "globals", no_argument, &globals, TRUE },
541 { "typedefs", no_argument, NULL, 't' },
542 { "typedefs-and-c++", no_argument, NULL, 'T' },
543 { "update", no_argument, NULL, 'u' },
544 { "vgrind", no_argument, NULL, 'v' },
545 { "no-warn", no_argument, NULL, 'w' },
547 #else /* Etags options */
548 { "no-defines", no_argument, NULL, 'D' },
549 { "no-globals", no_argument, &globals, FALSE },
550 { "include", required_argument, NULL, 'i' },
551 #endif
552 { NULL }
555 static compressor compressors[] =
557 { "z", "gzip -d -c"},
558 { "Z", "gzip -d -c"},
559 { "gz", "gzip -d -c"},
560 { "GZ", "gzip -d -c"},
561 { "bz2", "bzip2 -d -c" },
562 { "xz", "xz -d -c" },
563 { NULL }
567 * Language stuff.
570 /* Ada code */
571 static const char *Ada_suffixes [] =
572 { "ads", "adb", "ada", NULL };
573 static const char Ada_help [] =
574 "In Ada code, functions, procedures, packages, tasks and types are\n\
575 tags. Use the `--packages-only' option to create tags for\n\
576 packages only.\n\
577 Ada tag names have suffixes indicating the type of entity:\n\
578 Entity type: Qualifier:\n\
579 ------------ ----------\n\
580 function /f\n\
581 procedure /p\n\
582 package spec /s\n\
583 package body /b\n\
584 type /t\n\
585 task /k\n\
586 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
587 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
588 will just search for any tag `bidule'.";
590 /* Assembly code */
591 static const char *Asm_suffixes [] =
592 { "a", /* Unix assembler */
593 "asm", /* Microcontroller assembly */
594 "def", /* BSO/Tasking definition includes */
595 "inc", /* Microcontroller include files */
596 "ins", /* Microcontroller include files */
597 "s", "sa", /* Unix assembler */
598 "S", /* cpp-processed Unix assembler */
599 "src", /* BSO/Tasking C compiler output */
600 NULL
602 static const char Asm_help [] =
603 "In assembler code, labels appearing at the beginning of a line,\n\
604 followed by a colon, are tags.";
607 /* Note that .c and .h can be considered C++, if the --c++ flag was
608 given, or if the `class' or `template' keywords are met inside the file.
609 That is why default_C_entries is called for these. */
610 static const char *default_C_suffixes [] =
611 { "c", "h", NULL };
612 #if CTAGS /* C help for Ctags */
613 static const char default_C_help [] =
614 "In C code, any C function is a tag. Use -t to tag typedefs.\n\
615 Use -T to tag definitions of `struct', `union' and `enum'.\n\
616 Use -d to tag `#define' macro definitions and `enum' constants.\n\
617 Use --globals to tag global variables.\n\
618 You can tag function declarations and external variables by\n\
619 using `--declarations', and struct members by using `--members'.";
620 #else /* C help for Etags */
621 static const char default_C_help [] =
622 "In C code, any C function or typedef is a tag, and so are\n\
623 definitions of `struct', `union' and `enum'. `#define' macro\n\
624 definitions and `enum' constants are tags unless you specify\n\
625 `--no-defines'. Global variables are tags unless you specify\n\
626 `--no-globals' and so are struct members unless you specify\n\
627 `--no-members'. Use of `--no-globals', `--no-defines' and\n\
628 `--no-members' can make the tags table file much smaller.\n\
629 You can tag function declarations and external variables by\n\
630 using `--declarations'.";
631 #endif /* C help for Ctags and Etags */
633 static const char *Cplusplus_suffixes [] =
634 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
635 "M", /* Objective C++ */
636 "pdb", /* Postscript with C syntax */
637 NULL };
638 static const char Cplusplus_help [] =
639 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
640 --help --lang=c --lang=c++ for full help.)\n\
641 In addition to C tags, member functions are also recognized. Member\n\
642 variables are recognized unless you use the `--no-members' option.\n\
643 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
644 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
645 `operator+'.";
647 static const char *Cjava_suffixes [] =
648 { "java", NULL };
649 static char Cjava_help [] =
650 "In Java code, all the tags constructs of C and C++ code are\n\
651 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
654 static const char *Cobol_suffixes [] =
655 { "COB", "cob", NULL };
656 static char Cobol_help [] =
657 "In Cobol code, tags are paragraph names; that is, any word\n\
658 starting in column 8 and followed by a period.";
660 static const char *Cstar_suffixes [] =
661 { "cs", "hs", NULL };
663 static const char *Erlang_suffixes [] =
664 { "erl", "hrl", NULL };
665 static const char Erlang_help [] =
666 "In Erlang code, the tags are the functions, records and macros\n\
667 defined in the file.";
669 const char *Forth_suffixes [] =
670 { "fth", "tok", NULL };
671 static const char Forth_help [] =
672 "In Forth code, tags are words defined by `:',\n\
673 constant, code, create, defer, value, variable, buffer:, field.";
675 static const char *Fortran_suffixes [] =
676 { "F", "f", "f90", "for", NULL };
677 static const char Fortran_help [] =
678 "In Fortran code, functions, subroutines and block data are tags.";
680 static const char *HTML_suffixes [] =
681 { "htm", "html", "shtml", NULL };
682 static const char HTML_help [] =
683 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
684 `h3' headers. Also, tags are `name=' in anchors and all\n\
685 occurrences of `id='.";
687 static const char *Lisp_suffixes [] =
688 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
689 static const char Lisp_help [] =
690 "In Lisp code, any function defined with `defun', any variable\n\
691 defined with `defvar' or `defconst', and in general the first\n\
692 argument of any expression that starts with `(def' in column zero\n\
693 is a tag.";
695 static const char *Lua_suffixes [] =
696 { "lua", "LUA", NULL };
697 static const char Lua_help [] =
698 "In Lua scripts, all functions are tags.";
700 static const char *Makefile_filenames [] =
701 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
702 static const char Makefile_help [] =
703 "In makefiles, targets are tags; additionally, variables are tags\n\
704 unless you specify `--no-globals'.";
706 static const char *Objc_suffixes [] =
707 { "lm", /* Objective lex file */
708 "m", /* Objective C file */
709 NULL };
710 static const char Objc_help [] =
711 "In Objective C code, tags include Objective C definitions for classes,\n\
712 class categories, methods and protocols. Tags for variables and\n\
713 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
714 (Use --help --lang=c --lang=objc --lang=java for full help.)";
716 static const char *Pascal_suffixes [] =
717 { "p", "pas", NULL };
718 static const char Pascal_help [] =
719 "In Pascal code, the tags are the functions and procedures defined\n\
720 in the file.";
721 /* " // this is for working around an Emacs highlighting bug... */
723 static const char *Perl_suffixes [] =
724 { "pl", "pm", NULL };
725 static const char *Perl_interpreters [] =
726 { "perl", "@PERL@", NULL };
727 static const char Perl_help [] =
728 "In Perl code, the tags are the packages, subroutines and variables\n\
729 defined by the `package', `sub', `my' and `local' keywords. Use\n\
730 `--globals' if you want to tag global variables. Tags for\n\
731 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
732 defined in the default package is `main::SUB'.";
734 static const char *PHP_suffixes [] =
735 { "php", "php3", "php4", NULL };
736 static const char PHP_help [] =
737 "In PHP code, tags are functions, classes and defines. Unless you use\n\
738 the `--no-members' option, vars are tags too.";
740 static const char *plain_C_suffixes [] =
741 { "pc", /* Pro*C file */
742 NULL };
744 static const char *PS_suffixes [] =
745 { "ps", "psw", NULL }; /* .psw is for PSWrap */
746 static const char PS_help [] =
747 "In PostScript code, the tags are the functions.";
749 static const char *Prolog_suffixes [] =
750 { "prolog", NULL };
751 static const char Prolog_help [] =
752 "In Prolog code, tags are predicates and rules at the beginning of\n\
753 line.";
755 static const char *Python_suffixes [] =
756 { "py", NULL };
757 static const char Python_help [] =
758 "In Python code, `def' or `class' at the beginning of a line\n\
759 generate a tag.";
761 /* Can't do the `SCM' or `scm' prefix with a version number. */
762 static const char *Scheme_suffixes [] =
763 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
764 static const char Scheme_help [] =
765 "In Scheme code, tags include anything defined with `def' or with a\n\
766 construct whose name starts with `def'. They also include\n\
767 variables set with `set!' at top level in the file.";
769 static const char *TeX_suffixes [] =
770 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
771 static const char TeX_help [] =
772 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
773 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
774 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
775 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
776 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
778 Other commands can be specified by setting the environment variable\n\
779 `TEXTAGS' to a colon-separated list like, for example,\n\
780 TEXTAGS=\"mycommand:myothercommand\".";
783 static const char *Texinfo_suffixes [] =
784 { "texi", "texinfo", "txi", NULL };
785 static const char Texinfo_help [] =
786 "for texinfo files, lines starting with @node are tagged.";
788 static const char *Yacc_suffixes [] =
789 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
790 static const char Yacc_help [] =
791 "In Bison or Yacc input files, each rule defines as a tag the\n\
792 nonterminal it constructs. The portions of the file that contain\n\
793 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
794 for full help).";
796 static const char auto_help [] =
797 "`auto' is not a real language, it indicates to use\n\
798 a default language for files base on file name suffix and file contents.";
800 static const char none_help [] =
801 "`none' is not a real language, it indicates to only do\n\
802 regexp processing on files.";
804 static const char no_lang_help [] =
805 "No detailed help available for this language.";
809 * Table of languages.
811 * It is ok for a given function to be listed under more than one
812 * name. I just didn't.
815 static language lang_names [] =
817 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
818 { "asm", Asm_help, Asm_labels, Asm_suffixes },
819 { "c", default_C_help, default_C_entries, default_C_suffixes },
820 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
821 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
822 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
823 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
824 { "forth", Forth_help, Forth_words, Forth_suffixes },
825 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
826 { "html", HTML_help, HTML_labels, HTML_suffixes },
827 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
828 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
829 { "lua", Lua_help, Lua_functions, Lua_suffixes },
830 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
831 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
832 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
833 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
834 { "php", PHP_help, PHP_functions, PHP_suffixes },
835 { "postscript",PS_help, PS_functions, PS_suffixes },
836 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
837 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
838 { "python", Python_help, Python_functions, Python_suffixes },
839 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
840 { "tex", TeX_help, TeX_commands, TeX_suffixes },
841 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
842 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
843 { "auto", auto_help }, /* default guessing scheme */
844 { "none", none_help, just_read_file }, /* regexp matching only */
845 { NULL } /* end of list */
849 static void
850 print_language_names (void)
852 language *lang;
853 const char **name, **ext;
855 puts ("\nThese are the currently supported languages, along with the\n\
856 default file names and dot suffixes:");
857 for (lang = lang_names; lang->name != NULL; lang++)
859 printf (" %-*s", 10, lang->name);
860 if (lang->filenames != NULL)
861 for (name = lang->filenames; *name != NULL; name++)
862 printf (" %s", *name);
863 if (lang->suffixes != NULL)
864 for (ext = lang->suffixes; *ext != NULL; ext++)
865 printf (" .%s", *ext);
866 puts ("");
868 puts ("where `auto' means use default language for files based on file\n\
869 name suffix, and `none' means only do regexp processing on files.\n\
870 If no language is specified and no matching suffix is found,\n\
871 the first line of the file is read for a sharp-bang (#!) sequence\n\
872 followed by the name of an interpreter. If no such sequence is found,\n\
873 Fortran is tried first; if no tags are found, C is tried next.\n\
874 When parsing any C file, a \"class\" or \"template\" keyword\n\
875 switches to C++.");
876 puts ("Compressed files are supported using gzip, bzip2, and xz.\n\
878 For detailed help on a given language use, for example,\n\
879 etags --help --lang=ada.");
882 #ifndef EMACS_NAME
883 # define EMACS_NAME "standalone"
884 #endif
885 #ifndef VERSION
886 # define VERSION "17.38.1.4"
887 #endif
888 static void
889 print_version (void)
891 /* Makes it easier to update automatically. */
892 char emacs_copyright[] = "Copyright (C) 2011 Free Software Foundation, Inc.";
894 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
895 puts (emacs_copyright);
896 puts ("This program is distributed under the terms in ETAGS.README");
898 exit (EXIT_SUCCESS);
901 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
902 # define PRINT_UNDOCUMENTED_OPTIONS_HELP FALSE
903 #endif
905 static void
906 print_help (argument *argbuffer)
908 bool help_for_lang = FALSE;
910 for (; argbuffer->arg_type != at_end; argbuffer++)
911 if (argbuffer->arg_type == at_language)
913 if (help_for_lang)
914 puts ("");
915 puts (argbuffer->lang->help);
916 help_for_lang = TRUE;
919 if (help_for_lang)
920 exit (EXIT_SUCCESS);
922 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
924 These are the options accepted by %s.\n", progname, progname);
925 if (NO_LONG_OPTIONS)
926 puts ("WARNING: long option names do not work with this executable,\n\
927 as it is not linked with GNU getopt.");
928 else
929 puts ("You may use unambiguous abbreviations for the long option names.");
930 puts (" A - as file name means read names from stdin (one per line).\n\
931 Absolute names are stored in the output file as they are.\n\
932 Relative ones are stored relative to the output file's directory.\n");
934 puts ("-a, --append\n\
935 Append tag entries to existing tags file.");
937 puts ("--packages-only\n\
938 For Ada files, only generate tags for packages.");
940 if (CTAGS)
941 puts ("-B, --backward-search\n\
942 Write the search commands for the tag entries using '?', the\n\
943 backward-search command instead of '/', the forward-search command.");
945 /* This option is mostly obsolete, because etags can now automatically
946 detect C++. Retained for backward compatibility and for debugging and
947 experimentation. In principle, we could want to tag as C++ even
948 before any "class" or "template" keyword.
949 puts ("-C, --c++\n\
950 Treat files whose name suffix defaults to C language as C++ files.");
953 puts ("--declarations\n\
954 In C and derived languages, create tags for function declarations,");
955 if (CTAGS)
956 puts ("\tand create tags for extern variables if --globals is used.");
957 else
958 puts
959 ("\tand create tags for extern variables unless --no-globals is used.");
961 if (CTAGS)
962 puts ("-d, --defines\n\
963 Create tag entries for C #define constants and enum constants, too.");
964 else
965 puts ("-D, --no-defines\n\
966 Don't create tag entries for C #define constants and enum constants.\n\
967 This makes the tags file smaller.");
969 if (!CTAGS)
970 puts ("-i FILE, --include=FILE\n\
971 Include a note in tag file indicating that, when searching for\n\
972 a tag, one should also consult the tags file FILE after\n\
973 checking the current file.");
975 puts ("-l LANG, --language=LANG\n\
976 Force the following files to be considered as written in the\n\
977 named language up to the next --language=LANG option.");
979 if (CTAGS)
980 puts ("--globals\n\
981 Create tag entries for global variables in some languages.");
982 else
983 puts ("--no-globals\n\
984 Do not create tag entries for global variables in some\n\
985 languages. This makes the tags file smaller.");
987 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
988 puts ("--no-line-directive\n\
989 Ignore #line preprocessor directives in C and derived languages.");
991 if (CTAGS)
992 puts ("--members\n\
993 Create tag entries for members of structures in some languages.");
994 else
995 puts ("--no-members\n\
996 Do not create tag entries for members of structures\n\
997 in some languages.");
999 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
1000 Make a tag for each line matching a regular expression pattern\n\
1001 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
1002 files only. REGEXFILE is a file containing one REGEXP per line.\n\
1003 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
1004 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
1005 puts (" If TAGNAME/ is present, the tags created are named.\n\
1006 For example Tcl named tags can be created with:\n\
1007 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
1008 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
1009 `m' means to allow multi-line matches, `s' implies `m' and\n\
1010 causes dot to match any character, including newline.");
1012 puts ("-R, --no-regex\n\
1013 Don't create tags from regexps for the following files.");
1015 puts ("-I, --ignore-indentation\n\
1016 In C and C++ do not assume that a closing brace in the first\n\
1017 column is the final brace of a function or structure definition.");
1019 puts ("-o FILE, --output=FILE\n\
1020 Write the tags to FILE.");
1022 puts ("--parse-stdin=NAME\n\
1023 Read from standard input and record tags as belonging to file NAME.");
1025 if (CTAGS)
1027 puts ("-t, --typedefs\n\
1028 Generate tag entries for C and Ada typedefs.");
1029 puts ("-T, --typedefs-and-c++\n\
1030 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
1031 and C++ member functions.");
1034 if (CTAGS)
1035 puts ("-u, --update\n\
1036 Update the tag entries for the given files, leaving tag\n\
1037 entries for other files in place. Currently, this is\n\
1038 implemented by deleting the existing entries for the given\n\
1039 files and then rewriting the new entries at the end of the\n\
1040 tags file. It is often faster to simply rebuild the entire\n\
1041 tag file than to use this.");
1043 if (CTAGS)
1045 puts ("-v, --vgrind\n\
1046 Print on the standard output an index of items intended for\n\
1047 human consumption, similar to the output of vgrind. The index\n\
1048 is sorted, and gives the page number of each item.");
1050 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1051 puts ("-w, --no-duplicates\n\
1052 Do not create duplicate tag entries, for compatibility with\n\
1053 traditional ctags.");
1055 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1056 puts ("-w, --no-warn\n\
1057 Suppress warning messages about duplicate tag entries.");
1059 puts ("-x, --cxref\n\
1060 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
1061 The output uses line numbers instead of page numbers, but\n\
1062 beyond that the differences are cosmetic; try both to see\n\
1063 which you like.");
1066 puts ("-V, --version\n\
1067 Print the version of the program.\n\
1068 -h, --help\n\
1069 Print this help message.\n\
1070 Followed by one or more `--language' options prints detailed\n\
1071 help about tag generation for the specified languages.");
1073 print_language_names ();
1075 puts ("");
1076 puts ("Report bugs to bug-gnu-emacs@gnu.org");
1078 exit (EXIT_SUCCESS);
1083 main (int argc, char **argv)
1085 int i;
1086 unsigned int nincluded_files;
1087 char **included_files;
1088 argument *argbuffer;
1089 int current_arg, file_count;
1090 linebuffer filename_lb;
1091 bool help_asked = FALSE;
1092 char *optstring;
1093 int opt;
1096 #ifdef DOS_NT
1097 _fmode = O_BINARY; /* all of files are treated as binary files */
1098 #endif /* DOS_NT */
1100 progname = argv[0];
1101 nincluded_files = 0;
1102 included_files = xnew (argc, char *);
1103 current_arg = 0;
1104 file_count = 0;
1106 /* Allocate enough no matter what happens. Overkill, but each one
1107 is small. */
1108 argbuffer = xnew (argc, argument);
1111 * Always find typedefs and structure tags.
1112 * Also default to find macro constants, enum constants, struct
1113 * members and global variables. Do it for both etags and ctags.
1115 typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1116 globals = members = TRUE;
1118 /* When the optstring begins with a '-' getopt_long does not rearrange the
1119 non-options arguments to be at the end, but leaves them alone. */
1120 optstring = concat (NO_LONG_OPTIONS ? "" : "-",
1121 "ac:Cf:Il:o:r:RSVhH",
1122 (CTAGS) ? "BxdtTuvw" : "Di:");
1124 while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1125 switch (opt)
1127 case 0:
1128 /* If getopt returns 0, then it has already processed a
1129 long-named option. We should do nothing. */
1130 break;
1132 case 1:
1133 /* This means that a file name has been seen. Record it. */
1134 argbuffer[current_arg].arg_type = at_filename;
1135 argbuffer[current_arg].what = optarg;
1136 ++current_arg;
1137 ++file_count;
1138 break;
1140 case STDIN:
1141 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1142 argbuffer[current_arg].arg_type = at_stdin;
1143 argbuffer[current_arg].what = optarg;
1144 ++current_arg;
1145 ++file_count;
1146 if (parsing_stdin)
1147 fatal ("cannot parse standard input more than once", (char *)NULL);
1148 parsing_stdin = TRUE;
1149 break;
1151 /* Common options. */
1152 case 'a': append_to_tagfile = TRUE; break;
1153 case 'C': cplusplus = TRUE; break;
1154 case 'f': /* for compatibility with old makefiles */
1155 case 'o':
1156 if (tagfile)
1158 error ("-o option may only be given once.", (char *)NULL);
1159 suggest_asking_for_help ();
1160 /* NOTREACHED */
1162 tagfile = optarg;
1163 break;
1164 case 'I':
1165 case 'S': /* for backward compatibility */
1166 ignoreindent = TRUE;
1167 break;
1168 case 'l':
1170 language *lang = get_language_from_langname (optarg);
1171 if (lang != NULL)
1173 argbuffer[current_arg].lang = lang;
1174 argbuffer[current_arg].arg_type = at_language;
1175 ++current_arg;
1178 break;
1179 case 'c':
1180 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1181 optarg = concat (optarg, "i", ""); /* memory leak here */
1182 /* FALLTHRU */
1183 case 'r':
1184 argbuffer[current_arg].arg_type = at_regexp;
1185 argbuffer[current_arg].what = optarg;
1186 ++current_arg;
1187 break;
1188 case 'R':
1189 argbuffer[current_arg].arg_type = at_regexp;
1190 argbuffer[current_arg].what = NULL;
1191 ++current_arg;
1192 break;
1193 case 'V':
1194 print_version ();
1195 break;
1196 case 'h':
1197 case 'H':
1198 help_asked = TRUE;
1199 break;
1201 /* Etags options */
1202 case 'D': constantypedefs = FALSE; break;
1203 case 'i': included_files[nincluded_files++] = optarg; break;
1205 /* Ctags options. */
1206 case 'B': searchar = '?'; break;
1207 case 'd': constantypedefs = TRUE; break;
1208 case 't': typedefs = TRUE; break;
1209 case 'T': typedefs = typedefs_or_cplusplus = TRUE; break;
1210 case 'u': update = TRUE; break;
1211 case 'v': vgrind_style = TRUE; /*FALLTHRU*/
1212 case 'x': cxref_style = TRUE; break;
1213 case 'w': no_warnings = TRUE; break;
1214 default:
1215 suggest_asking_for_help ();
1216 /* NOTREACHED */
1219 /* No more options. Store the rest of arguments. */
1220 for (; optind < argc; optind++)
1222 argbuffer[current_arg].arg_type = at_filename;
1223 argbuffer[current_arg].what = argv[optind];
1224 ++current_arg;
1225 ++file_count;
1228 argbuffer[current_arg].arg_type = at_end;
1230 if (help_asked)
1231 print_help (argbuffer);
1232 /* NOTREACHED */
1234 if (nincluded_files == 0 && file_count == 0)
1236 error ("no input files specified.", (char *)NULL);
1237 suggest_asking_for_help ();
1238 /* NOTREACHED */
1241 if (tagfile == NULL)
1242 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1243 cwd = etags_getcwd (); /* the current working directory */
1244 if (cwd[strlen (cwd) - 1] != '/')
1246 char *oldcwd = cwd;
1247 cwd = concat (oldcwd, "/", "");
1248 free (oldcwd);
1251 /* Compute base directory for relative file names. */
1252 if (streq (tagfile, "-")
1253 || strneq (tagfile, "/dev/", 5))
1254 tagfiledir = cwd; /* relative file names are relative to cwd */
1255 else
1257 canonicalize_filename (tagfile);
1258 tagfiledir = absolute_dirname (tagfile, cwd);
1261 init (); /* set up boolean "functions" */
1263 linebuffer_init (&lb);
1264 linebuffer_init (&filename_lb);
1265 linebuffer_init (&filebuf);
1266 linebuffer_init (&token_name);
1268 if (!CTAGS)
1270 if (streq (tagfile, "-"))
1272 tagf = stdout;
1273 #ifdef DOS_NT
1274 /* Switch redirected `stdout' to binary mode (setting `_fmode'
1275 doesn't take effect until after `stdout' is already open). */
1276 if (!isatty (fileno (stdout)))
1277 setmode (fileno (stdout), O_BINARY);
1278 #endif /* DOS_NT */
1280 else
1281 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1282 if (tagf == NULL)
1283 pfatal (tagfile);
1287 * Loop through files finding functions.
1289 for (i = 0; i < current_arg; i++)
1291 static language *lang; /* non-NULL if language is forced */
1292 char *this_file;
1294 switch (argbuffer[i].arg_type)
1296 case at_language:
1297 lang = argbuffer[i].lang;
1298 break;
1299 case at_regexp:
1300 analyse_regex (argbuffer[i].what);
1301 break;
1302 case at_filename:
1303 this_file = argbuffer[i].what;
1304 /* Input file named "-" means read file names from stdin
1305 (one per line) and use them. */
1306 if (streq (this_file, "-"))
1308 if (parsing_stdin)
1309 fatal ("cannot parse standard input AND read file names from it",
1310 (char *)NULL);
1311 while (readline_internal (&filename_lb, stdin) > 0)
1312 process_file_name (filename_lb.buffer, lang);
1314 else
1315 process_file_name (this_file, lang);
1316 break;
1317 case at_stdin:
1318 this_file = argbuffer[i].what;
1319 process_file (stdin, this_file, lang);
1320 break;
1324 free_regexps ();
1325 free (lb.buffer);
1326 free (filebuf.buffer);
1327 free (token_name.buffer);
1329 if (!CTAGS || cxref_style)
1331 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1332 put_entries (nodehead);
1333 free_tree (nodehead);
1334 nodehead = NULL;
1335 if (!CTAGS)
1337 fdesc *fdp;
1339 /* Output file entries that have no tags. */
1340 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1341 if (!fdp->written)
1342 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1344 while (nincluded_files-- > 0)
1345 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1347 if (fclose (tagf) == EOF)
1348 pfatal (tagfile);
1351 exit (EXIT_SUCCESS);
1354 /* From here on, we are in (CTAGS && !cxref_style) */
1355 if (update)
1357 char cmd[BUFSIZ];
1358 for (i = 0; i < current_arg; ++i)
1360 switch (argbuffer[i].arg_type)
1362 case at_filename:
1363 case at_stdin:
1364 break;
1365 default:
1366 continue; /* the for loop */
1368 sprintf (cmd,
1369 "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
1370 tagfile, argbuffer[i].what, tagfile);
1371 if (system (cmd) != EXIT_SUCCESS)
1372 fatal ("failed to execute shell command", (char *)NULL);
1374 append_to_tagfile = TRUE;
1377 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1378 if (tagf == NULL)
1379 pfatal (tagfile);
1380 put_entries (nodehead); /* write all the tags (CTAGS) */
1381 free_tree (nodehead);
1382 nodehead = NULL;
1383 if (fclose (tagf) == EOF)
1384 pfatal (tagfile);
1386 if (CTAGS)
1387 if (append_to_tagfile || update)
1389 char cmd[2*BUFSIZ+20];
1390 /* Maybe these should be used:
1391 setenv ("LC_COLLATE", "C", 1);
1392 setenv ("LC_ALL", "C", 1); */
1393 sprintf (cmd, "sort -u -o %.*s %.*s", BUFSIZ, tagfile, BUFSIZ, tagfile);
1394 exit (system (cmd));
1396 return EXIT_SUCCESS;
1401 * Return a compressor given the file name. If EXTPTR is non-zero,
1402 * return a pointer into FILE where the compressor-specific
1403 * extension begins. If no compressor is found, NULL is returned
1404 * and EXTPTR is not significant.
1405 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1407 static compressor *
1408 get_compressor_from_suffix (char *file, char **extptr)
1410 compressor *compr;
1411 char *slash, *suffix;
1413 /* File has been processed by canonicalize_filename,
1414 so we don't need to consider backslashes on DOS_NT. */
1415 slash = etags_strrchr (file, '/');
1416 suffix = etags_strrchr (file, '.');
1417 if (suffix == NULL || suffix < slash)
1418 return NULL;
1419 if (extptr != NULL)
1420 *extptr = suffix;
1421 suffix += 1;
1422 /* Let those poor souls who live with DOS 8+3 file name limits get
1423 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1424 Only the first do loop is run if not MSDOS */
1427 for (compr = compressors; compr->suffix != NULL; compr++)
1428 if (streq (compr->suffix, suffix))
1429 return compr;
1430 if (!MSDOS)
1431 break; /* do it only once: not really a loop */
1432 if (extptr != NULL)
1433 *extptr = ++suffix;
1434 } while (*suffix != '\0');
1435 return NULL;
1441 * Return a language given the name.
1443 static language *
1444 get_language_from_langname (const char *name)
1446 language *lang;
1448 if (name == NULL)
1449 error ("empty language name", (char *)NULL);
1450 else
1452 for (lang = lang_names; lang->name != NULL; lang++)
1453 if (streq (name, lang->name))
1454 return lang;
1455 error ("unknown language \"%s\"", name);
1458 return NULL;
1463 * Return a language given the interpreter name.
1465 static language *
1466 get_language_from_interpreter (char *interpreter)
1468 language *lang;
1469 const char **iname;
1471 if (interpreter == NULL)
1472 return NULL;
1473 for (lang = lang_names; lang->name != NULL; lang++)
1474 if (lang->interpreters != NULL)
1475 for (iname = lang->interpreters; *iname != NULL; iname++)
1476 if (streq (*iname, interpreter))
1477 return lang;
1479 return NULL;
1485 * Return a language given the file name.
1487 static language *
1488 get_language_from_filename (char *file, int case_sensitive)
1490 language *lang;
1491 const char **name, **ext, *suffix;
1493 /* Try whole file name first. */
1494 for (lang = lang_names; lang->name != NULL; lang++)
1495 if (lang->filenames != NULL)
1496 for (name = lang->filenames; *name != NULL; name++)
1497 if ((case_sensitive)
1498 ? streq (*name, file)
1499 : strcaseeq (*name, file))
1500 return lang;
1502 /* If not found, try suffix after last dot. */
1503 suffix = etags_strrchr (file, '.');
1504 if (suffix == NULL)
1505 return NULL;
1506 suffix += 1;
1507 for (lang = lang_names; lang->name != NULL; lang++)
1508 if (lang->suffixes != NULL)
1509 for (ext = lang->suffixes; *ext != NULL; ext++)
1510 if ((case_sensitive)
1511 ? streq (*ext, suffix)
1512 : strcaseeq (*ext, suffix))
1513 return lang;
1514 return NULL;
1519 * This routine is called on each file argument.
1521 static void
1522 process_file_name (char *file, language *lang)
1524 struct stat stat_buf;
1525 FILE *inf;
1526 fdesc *fdp;
1527 compressor *compr;
1528 char *compressed_name, *uncompressed_name;
1529 char *ext, *real_name;
1530 int retval;
1532 canonicalize_filename (file);
1533 if (streq (file, tagfile) && !streq (tagfile, "-"))
1535 error ("skipping inclusion of %s in self.", file);
1536 return;
1538 if ((compr = get_compressor_from_suffix (file, &ext)) == NULL)
1540 compressed_name = NULL;
1541 real_name = uncompressed_name = savestr (file);
1543 else
1545 real_name = compressed_name = savestr (file);
1546 uncompressed_name = savenstr (file, ext - file);
1549 /* If the canonicalized uncompressed name
1550 has already been dealt with, skip it silently. */
1551 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1553 assert (fdp->infname != NULL);
1554 if (streq (uncompressed_name, fdp->infname))
1555 goto cleanup;
1558 if (stat (real_name, &stat_buf) != 0)
1560 /* Reset real_name and try with a different name. */
1561 real_name = NULL;
1562 if (compressed_name != NULL) /* try with the given suffix */
1564 if (stat (uncompressed_name, &stat_buf) == 0)
1565 real_name = uncompressed_name;
1567 else /* try all possible suffixes */
1569 for (compr = compressors; compr->suffix != NULL; compr++)
1571 compressed_name = concat (file, ".", compr->suffix);
1572 if (stat (compressed_name, &stat_buf) != 0)
1574 if (MSDOS)
1576 char *suf = compressed_name + strlen (file);
1577 size_t suflen = strlen (compr->suffix) + 1;
1578 for ( ; suf[1]; suf++, suflen--)
1580 memmove (suf, suf + 1, suflen);
1581 if (stat (compressed_name, &stat_buf) == 0)
1583 real_name = compressed_name;
1584 break;
1587 if (real_name != NULL)
1588 break;
1589 } /* MSDOS */
1590 free (compressed_name);
1591 compressed_name = NULL;
1593 else
1595 real_name = compressed_name;
1596 break;
1600 if (real_name == NULL)
1602 perror (file);
1603 goto cleanup;
1605 } /* try with a different name */
1607 if (!S_ISREG (stat_buf.st_mode))
1609 error ("skipping %s: it is not a regular file.", real_name);
1610 goto cleanup;
1612 if (real_name == compressed_name)
1614 char *cmd = concat (compr->command, " ", real_name);
1615 inf = (FILE *) popen (cmd, "r");
1616 free (cmd);
1618 else
1619 inf = fopen (real_name, "r");
1620 if (inf == NULL)
1622 perror (real_name);
1623 goto cleanup;
1626 process_file (inf, uncompressed_name, lang);
1628 if (real_name == compressed_name)
1629 retval = pclose (inf);
1630 else
1631 retval = fclose (inf);
1632 if (retval < 0)
1633 pfatal (file);
1635 cleanup:
1636 free (compressed_name);
1637 free (uncompressed_name);
1638 last_node = NULL;
1639 curfdp = NULL;
1640 return;
1643 static void
1644 process_file (FILE *fh, char *fn, language *lang)
1646 static const fdesc emptyfdesc;
1647 fdesc *fdp;
1649 /* Create a new input file description entry. */
1650 fdp = xnew (1, fdesc);
1651 *fdp = emptyfdesc;
1652 fdp->next = fdhead;
1653 fdp->infname = savestr (fn);
1654 fdp->lang = lang;
1655 fdp->infabsname = absolute_filename (fn, cwd);
1656 fdp->infabsdir = absolute_dirname (fn, cwd);
1657 if (filename_is_absolute (fn))
1659 /* An absolute file name. Canonicalize it. */
1660 fdp->taggedfname = absolute_filename (fn, NULL);
1662 else
1664 /* A file name relative to cwd. Make it relative
1665 to the directory of the tags file. */
1666 fdp->taggedfname = relative_filename (fn, tagfiledir);
1668 fdp->usecharno = TRUE; /* use char position when making tags */
1669 fdp->prop = NULL;
1670 fdp->written = FALSE; /* not written on tags file yet */
1672 fdhead = fdp;
1673 curfdp = fdhead; /* the current file description */
1675 find_entries (fh);
1677 /* If not Ctags, and if this is not metasource and if it contained no #line
1678 directives, we can write the tags and free all nodes pointing to
1679 curfdp. */
1680 if (!CTAGS
1681 && curfdp->usecharno /* no #line directives in this file */
1682 && !curfdp->lang->metasource)
1684 node *np, *prev;
1686 /* Look for the head of the sublist relative to this file. See add_node
1687 for the structure of the node tree. */
1688 prev = NULL;
1689 for (np = nodehead; np != NULL; prev = np, np = np->left)
1690 if (np->fdp == curfdp)
1691 break;
1693 /* If we generated tags for this file, write and delete them. */
1694 if (np != NULL)
1696 /* This is the head of the last sublist, if any. The following
1697 instructions depend on this being true. */
1698 assert (np->left == NULL);
1700 assert (fdhead == curfdp);
1701 assert (last_node->fdp == curfdp);
1702 put_entries (np); /* write tags for file curfdp->taggedfname */
1703 free_tree (np); /* remove the written nodes */
1704 if (prev == NULL)
1705 nodehead = NULL; /* no nodes left */
1706 else
1707 prev->left = NULL; /* delete the pointer to the sublist */
1713 * This routine sets up the boolean pseudo-functions which work
1714 * by setting boolean flags dependent upon the corresponding character.
1715 * Every char which is NOT in that string is not a white char. Therefore,
1716 * all of the array "_wht" is set to FALSE, and then the elements
1717 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1718 * of a char is TRUE if it is the string "white", else FALSE.
1720 static void
1721 init (void)
1723 register const char *sp;
1724 register int i;
1726 for (i = 0; i < CHARS; i++)
1727 iswhite(i) = notinname(i) = begtoken(i) = intoken(i) = endtoken(i) = FALSE;
1728 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1729 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1730 notinname('\0') = notinname('\n');
1731 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1732 begtoken('\0') = begtoken('\n');
1733 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1734 intoken('\0') = intoken('\n');
1735 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1736 endtoken('\0') = endtoken('\n');
1740 * This routine opens the specified file and calls the function
1741 * which finds the function and type definitions.
1743 static void
1744 find_entries (FILE *inf)
1746 char *cp;
1747 language *lang = curfdp->lang;
1748 Lang_function *parser = NULL;
1750 /* If user specified a language, use it. */
1751 if (lang != NULL && lang->function != NULL)
1753 parser = lang->function;
1756 /* Else try to guess the language given the file name. */
1757 if (parser == NULL)
1759 lang = get_language_from_filename (curfdp->infname, TRUE);
1760 if (lang != NULL && lang->function != NULL)
1762 curfdp->lang = lang;
1763 parser = lang->function;
1767 /* Else look for sharp-bang as the first two characters. */
1768 if (parser == NULL
1769 && readline_internal (&lb, inf) > 0
1770 && lb.len >= 2
1771 && lb.buffer[0] == '#'
1772 && lb.buffer[1] == '!')
1774 char *lp;
1776 /* Set lp to point at the first char after the last slash in the
1777 line or, if no slashes, at the first nonblank. Then set cp to
1778 the first successive blank and terminate the string. */
1779 lp = etags_strrchr (lb.buffer+2, '/');
1780 if (lp != NULL)
1781 lp += 1;
1782 else
1783 lp = skip_spaces (lb.buffer + 2);
1784 cp = skip_non_spaces (lp);
1785 *cp = '\0';
1787 if (strlen (lp) > 0)
1789 lang = get_language_from_interpreter (lp);
1790 if (lang != NULL && lang->function != NULL)
1792 curfdp->lang = lang;
1793 parser = lang->function;
1798 /* We rewind here, even if inf may be a pipe. We fail if the
1799 length of the first line is longer than the pipe block size,
1800 which is unlikely. */
1801 rewind (inf);
1803 /* Else try to guess the language given the case insensitive file name. */
1804 if (parser == NULL)
1806 lang = get_language_from_filename (curfdp->infname, FALSE);
1807 if (lang != NULL && lang->function != NULL)
1809 curfdp->lang = lang;
1810 parser = lang->function;
1814 /* Else try Fortran or C. */
1815 if (parser == NULL)
1817 node *old_last_node = last_node;
1819 curfdp->lang = get_language_from_langname ("fortran");
1820 find_entries (inf);
1822 if (old_last_node == last_node)
1823 /* No Fortran entries found. Try C. */
1825 /* We do not tag if rewind fails.
1826 Only the file name will be recorded in the tags file. */
1827 rewind (inf);
1828 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1829 find_entries (inf);
1831 return;
1834 if (!no_line_directive
1835 && curfdp->lang != NULL && curfdp->lang->metasource)
1836 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1837 file, or anyway we parsed a file that is automatically generated from
1838 this one. If this is the case, the bingo.c file contained #line
1839 directives that generated tags pointing to this file. Let's delete
1840 them all before parsing this file, which is the real source. */
1842 fdesc **fdpp = &fdhead;
1843 while (*fdpp != NULL)
1844 if (*fdpp != curfdp
1845 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1846 /* We found one of those! We must delete both the file description
1847 and all tags referring to it. */
1849 fdesc *badfdp = *fdpp;
1851 /* Delete the tags referring to badfdp->taggedfname
1852 that were obtained from badfdp->infname. */
1853 invalidate_nodes (badfdp, &nodehead);
1855 *fdpp = badfdp->next; /* remove the bad description from the list */
1856 free_fdesc (badfdp);
1858 else
1859 fdpp = &(*fdpp)->next; /* advance the list pointer */
1862 assert (parser != NULL);
1864 /* Generic initialisations before reading from file. */
1865 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1867 /* Generic initialisations before parsing file with readline. */
1868 lineno = 0; /* reset global line number */
1869 charno = 0; /* reset global char number */
1870 linecharno = 0; /* reset global char number of line start */
1872 parser (inf);
1874 regex_tag_multiline ();
1879 * Check whether an implicitly named tag should be created,
1880 * then call `pfnote'.
1881 * NAME is a string that is internally copied by this function.
1883 * TAGS format specification
1884 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1885 * The following is explained in some more detail in etc/ETAGS.EBNF.
1887 * make_tag creates tags with "implicit tag names" (unnamed tags)
1888 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1889 * 1. NAME does not contain any of the characters in NONAM;
1890 * 2. LINESTART contains name as either a rightmost, or rightmost but
1891 * one character, substring;
1892 * 3. the character, if any, immediately before NAME in LINESTART must
1893 * be a character in NONAM;
1894 * 4. the character, if any, immediately after NAME in LINESTART must
1895 * also be a character in NONAM.
1897 * The implementation uses the notinname() macro, which recognises the
1898 * characters stored in the string `nonam'.
1899 * etags.el needs to use the same characters that are in NONAM.
1901 static void
1902 make_tag (const char *name, /* tag name, or NULL if unnamed */
1903 int namelen, /* tag length */
1904 int is_func, /* tag is a function */
1905 char *linestart, /* start of the line where tag is */
1906 int linelen, /* length of the line where tag is */
1907 int lno, /* line number */
1908 long int cno) /* character number */
1910 bool named = (name != NULL && namelen > 0);
1911 char *nname = NULL;
1913 if (!CTAGS && named) /* maybe set named to false */
1914 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1915 such that etags.el can guess a name from it. */
1917 int i;
1918 register const char *cp = name;
1920 for (i = 0; i < namelen; i++)
1921 if (notinname (*cp++))
1922 break;
1923 if (i == namelen) /* rule #1 */
1925 cp = linestart + linelen - namelen;
1926 if (notinname (linestart[linelen-1]))
1927 cp -= 1; /* rule #4 */
1928 if (cp >= linestart /* rule #2 */
1929 && (cp == linestart
1930 || notinname (cp[-1])) /* rule #3 */
1931 && strneq (name, cp, namelen)) /* rule #2 */
1932 named = FALSE; /* use implicit tag name */
1936 if (named)
1937 nname = savenstr (name, namelen);
1939 pfnote (nname, is_func, linestart, linelen, lno, cno);
1942 /* Record a tag. */
1943 static void
1944 pfnote (char *name, int is_func, char *linestart, int linelen, int lno, long int cno)
1945 /* tag name, or NULL if unnamed */
1946 /* tag is a function */
1947 /* start of the line where tag is */
1948 /* length of the line where tag is */
1949 /* line number */
1950 /* character number */
1952 register node *np;
1954 assert (name == NULL || name[0] != '\0');
1955 if (CTAGS && name == NULL)
1956 return;
1958 np = xnew (1, node);
1960 /* If ctags mode, change name "main" to M<thisfilename>. */
1961 if (CTAGS && !cxref_style && streq (name, "main"))
1963 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
1964 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
1965 fp = etags_strrchr (np->name, '.');
1966 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
1967 fp[0] = '\0';
1969 else
1970 np->name = name;
1971 np->valid = TRUE;
1972 np->been_warned = FALSE;
1973 np->fdp = curfdp;
1974 np->is_func = is_func;
1975 np->lno = lno;
1976 if (np->fdp->usecharno)
1977 /* Our char numbers are 0-base, because of C language tradition?
1978 ctags compatibility? old versions compatibility? I don't know.
1979 Anyway, since emacs's are 1-base we expect etags.el to take care
1980 of the difference. If we wanted to have 1-based numbers, we would
1981 uncomment the +1 below. */
1982 np->cno = cno /* + 1 */ ;
1983 else
1984 np->cno = invalidcharno;
1985 np->left = np->right = NULL;
1986 if (CTAGS && !cxref_style)
1988 if (strlen (linestart) < 50)
1989 np->regex = concat (linestart, "$", "");
1990 else
1991 np->regex = savenstr (linestart, 50);
1993 else
1994 np->regex = savenstr (linestart, linelen);
1996 add_node (np, &nodehead);
2000 * free_tree ()
2001 * recurse on left children, iterate on right children.
2003 static void
2004 free_tree (register node *np)
2006 while (np)
2008 register node *node_right = np->right;
2009 free_tree (np->left);
2010 free (np->name);
2011 free (np->regex);
2012 free (np);
2013 np = node_right;
2018 * free_fdesc ()
2019 * delete a file description
2021 static void
2022 free_fdesc (register fdesc *fdp)
2024 free (fdp->infname);
2025 free (fdp->infabsname);
2026 free (fdp->infabsdir);
2027 free (fdp->taggedfname);
2028 free (fdp->prop);
2029 free (fdp);
2033 * add_node ()
2034 * Adds a node to the tree of nodes. In etags mode, sort by file
2035 * name. In ctags mode, sort by tag name. Make no attempt at
2036 * balancing.
2038 * add_node is the only function allowed to add nodes, so it can
2039 * maintain state.
2041 static void
2042 add_node (node *np, node **cur_node_p)
2044 register int dif;
2045 register node *cur_node = *cur_node_p;
2047 if (cur_node == NULL)
2049 *cur_node_p = np;
2050 last_node = np;
2051 return;
2054 if (!CTAGS)
2055 /* Etags Mode */
2057 /* For each file name, tags are in a linked sublist on the right
2058 pointer. The first tags of different files are a linked list
2059 on the left pointer. last_node points to the end of the last
2060 used sublist. */
2061 if (last_node != NULL && last_node->fdp == np->fdp)
2063 /* Let's use the same sublist as the last added node. */
2064 assert (last_node->right == NULL);
2065 last_node->right = np;
2066 last_node = np;
2068 else if (cur_node->fdp == np->fdp)
2070 /* Scanning the list we found the head of a sublist which is
2071 good for us. Let's scan this sublist. */
2072 add_node (np, &cur_node->right);
2074 else
2075 /* The head of this sublist is not good for us. Let's try the
2076 next one. */
2077 add_node (np, &cur_node->left);
2078 } /* if ETAGS mode */
2080 else
2082 /* Ctags Mode */
2083 dif = strcmp (np->name, cur_node->name);
2086 * If this tag name matches an existing one, then
2087 * do not add the node, but maybe print a warning.
2089 if (no_duplicates && !dif)
2091 if (np->fdp == cur_node->fdp)
2093 if (!no_warnings)
2095 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2096 np->fdp->infname, lineno, np->name);
2097 fprintf (stderr, "Second entry ignored\n");
2100 else if (!cur_node->been_warned && !no_warnings)
2102 fprintf
2103 (stderr,
2104 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2105 np->fdp->infname, cur_node->fdp->infname, np->name);
2106 cur_node->been_warned = TRUE;
2108 return;
2111 /* Actually add the node */
2112 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2113 } /* if CTAGS mode */
2117 * invalidate_nodes ()
2118 * Scan the node tree and invalidate all nodes pointing to the
2119 * given file description (CTAGS case) or free them (ETAGS case).
2121 static void
2122 invalidate_nodes (fdesc *badfdp, node **npp)
2124 node *np = *npp;
2126 if (np == NULL)
2127 return;
2129 if (CTAGS)
2131 if (np->left != NULL)
2132 invalidate_nodes (badfdp, &np->left);
2133 if (np->fdp == badfdp)
2134 np->valid = FALSE;
2135 if (np->right != NULL)
2136 invalidate_nodes (badfdp, &np->right);
2138 else
2140 assert (np->fdp != NULL);
2141 if (np->fdp == badfdp)
2143 *npp = np->left; /* detach the sublist from the list */
2144 np->left = NULL; /* isolate it */
2145 free_tree (np); /* free it */
2146 invalidate_nodes (badfdp, npp);
2148 else
2149 invalidate_nodes (badfdp, &np->left);
2154 static int total_size_of_entries (node *);
2155 static int number_len (long);
2157 /* Length of a non-negative number's decimal representation. */
2158 static int
2159 number_len (long int num)
2161 int len = 1;
2162 while ((num /= 10) > 0)
2163 len += 1;
2164 return len;
2168 * Return total number of characters that put_entries will output for
2169 * the nodes in the linked list at the right of the specified node.
2170 * This count is irrelevant with etags.el since emacs 19.34 at least,
2171 * but is still supplied for backward compatibility.
2173 static int
2174 total_size_of_entries (register node *np)
2176 register int total = 0;
2178 for (; np != NULL; np = np->right)
2179 if (np->valid)
2181 total += strlen (np->regex) + 1; /* pat\177 */
2182 if (np->name != NULL)
2183 total += strlen (np->name) + 1; /* name\001 */
2184 total += number_len ((long) np->lno) + 1; /* lno, */
2185 if (np->cno != invalidcharno) /* cno */
2186 total += number_len (np->cno);
2187 total += 1; /* newline */
2190 return total;
2193 static void
2194 put_entries (register node *np)
2196 register char *sp;
2197 static fdesc *fdp = NULL;
2199 if (np == NULL)
2200 return;
2202 /* Output subentries that precede this one */
2203 if (CTAGS)
2204 put_entries (np->left);
2206 /* Output this entry */
2207 if (np->valid)
2209 if (!CTAGS)
2211 /* Etags mode */
2212 if (fdp != np->fdp)
2214 fdp = np->fdp;
2215 fprintf (tagf, "\f\n%s,%d\n",
2216 fdp->taggedfname, total_size_of_entries (np));
2217 fdp->written = TRUE;
2219 fputs (np->regex, tagf);
2220 fputc ('\177', tagf);
2221 if (np->name != NULL)
2223 fputs (np->name, tagf);
2224 fputc ('\001', tagf);
2226 fprintf (tagf, "%d,", np->lno);
2227 if (np->cno != invalidcharno)
2228 fprintf (tagf, "%ld", np->cno);
2229 fputs ("\n", tagf);
2231 else
2233 /* Ctags mode */
2234 if (np->name == NULL)
2235 error ("internal error: NULL name in ctags mode.", (char *)NULL);
2237 if (cxref_style)
2239 if (vgrind_style)
2240 fprintf (stdout, "%s %s %d\n",
2241 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2242 else
2243 fprintf (stdout, "%-16s %3d %-16s %s\n",
2244 np->name, np->lno, np->fdp->taggedfname, np->regex);
2246 else
2248 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2250 if (np->is_func)
2251 { /* function or #define macro with args */
2252 putc (searchar, tagf);
2253 putc ('^', tagf);
2255 for (sp = np->regex; *sp; sp++)
2257 if (*sp == '\\' || *sp == searchar)
2258 putc ('\\', tagf);
2259 putc (*sp, tagf);
2261 putc (searchar, tagf);
2263 else
2264 { /* anything else; text pattern inadequate */
2265 fprintf (tagf, "%d", np->lno);
2267 putc ('\n', tagf);
2270 } /* if this node contains a valid tag */
2272 /* Output subentries that follow this one */
2273 put_entries (np->right);
2274 if (!CTAGS)
2275 put_entries (np->left);
2279 /* C extensions. */
2280 #define C_EXT 0x00fff /* C extensions */
2281 #define C_PLAIN 0x00000 /* C */
2282 #define C_PLPL 0x00001 /* C++ */
2283 #define C_STAR 0x00003 /* C* */
2284 #define C_JAVA 0x00005 /* JAVA */
2285 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2286 #define YACC 0x10000 /* yacc file */
2289 * The C symbol tables.
2291 enum sym_type
2293 st_none,
2294 st_C_objprot, st_C_objimpl, st_C_objend,
2295 st_C_gnumacro,
2296 st_C_ignore, st_C_attribute,
2297 st_C_javastruct,
2298 st_C_operator,
2299 st_C_class, st_C_template,
2300 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2303 static unsigned int hash (const char *, unsigned int);
2304 static struct C_stab_entry * in_word_set (const char *, unsigned int);
2305 static enum sym_type C_symtype (char *, int, int);
2307 /* Feed stuff between (but not including) %[ and %] lines to:
2308 gperf -m 5
2310 %compare-strncmp
2311 %enum
2312 %struct-type
2313 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2315 if, 0, st_C_ignore
2316 for, 0, st_C_ignore
2317 while, 0, st_C_ignore
2318 switch, 0, st_C_ignore
2319 return, 0, st_C_ignore
2320 __attribute__, 0, st_C_attribute
2321 GTY, 0, st_C_attribute
2322 @interface, 0, st_C_objprot
2323 @protocol, 0, st_C_objprot
2324 @implementation,0, st_C_objimpl
2325 @end, 0, st_C_objend
2326 import, (C_JAVA & ~C_PLPL), st_C_ignore
2327 package, (C_JAVA & ~C_PLPL), st_C_ignore
2328 friend, C_PLPL, st_C_ignore
2329 extends, (C_JAVA & ~C_PLPL), st_C_javastruct
2330 implements, (C_JAVA & ~C_PLPL), st_C_javastruct
2331 interface, (C_JAVA & ~C_PLPL), st_C_struct
2332 class, 0, st_C_class
2333 namespace, C_PLPL, st_C_struct
2334 domain, C_STAR, st_C_struct
2335 union, 0, st_C_struct
2336 struct, 0, st_C_struct
2337 extern, 0, st_C_extern
2338 enum, 0, st_C_enum
2339 typedef, 0, st_C_typedef
2340 define, 0, st_C_define
2341 undef, 0, st_C_define
2342 operator, C_PLPL, st_C_operator
2343 template, 0, st_C_template
2344 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2345 DEFUN, 0, st_C_gnumacro
2346 SYSCALL, 0, st_C_gnumacro
2347 ENTRY, 0, st_C_gnumacro
2348 PSEUDO, 0, st_C_gnumacro
2349 # These are defined inside C functions, so currently they are not met.
2350 # EXFUN used in glibc, DEFVAR_* in emacs.
2351 #EXFUN, 0, st_C_gnumacro
2352 #DEFVAR_, 0, st_C_gnumacro
2354 and replace lines between %< and %> with its output, then:
2355 - remove the #if characterset check
2356 - make in_word_set static and not inline. */
2357 /*%<*/
2358 /* C code produced by gperf version 3.0.1 */
2359 /* Command-line: gperf -m 5 */
2360 /* Computed positions: -k'2-3' */
2362 struct C_stab_entry { const char *name; int c_ext; enum sym_type type; };
2363 /* maximum key range = 33, duplicates = 0 */
2365 #ifdef __GNUC__
2366 __inline
2367 #else
2368 #ifdef __cplusplus
2369 inline
2370 #endif
2371 #endif
2372 static unsigned int
2373 hash (register const char *str, register unsigned int len)
2375 static unsigned char asso_values[] =
2377 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2378 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2379 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2380 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2381 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2382 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2383 35, 35, 35, 35, 35, 35, 35, 35, 35, 3,
2384 26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2385 35, 35, 35, 24, 0, 35, 35, 35, 35, 0,
2386 35, 35, 35, 35, 35, 1, 35, 16, 35, 6,
2387 23, 0, 0, 35, 22, 0, 35, 35, 5, 0,
2388 0, 15, 1, 35, 6, 35, 8, 19, 35, 16,
2389 4, 5, 35, 35, 35, 35, 35, 35, 35, 35,
2390 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2391 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2392 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2393 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2394 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2395 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2396 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2397 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2398 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2399 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2400 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2401 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2402 35, 35, 35, 35, 35, 35
2404 register int hval = len;
2406 switch (hval)
2408 default:
2409 hval += asso_values[(unsigned char)str[2]];
2410 /*FALLTHROUGH*/
2411 case 2:
2412 hval += asso_values[(unsigned char)str[1]];
2413 break;
2415 return hval;
2418 static struct C_stab_entry *
2419 in_word_set (register const char *str, register unsigned int len)
2421 enum
2423 TOTAL_KEYWORDS = 33,
2424 MIN_WORD_LENGTH = 2,
2425 MAX_WORD_LENGTH = 15,
2426 MIN_HASH_VALUE = 2,
2427 MAX_HASH_VALUE = 34
2430 static struct C_stab_entry wordlist[] =
2432 {""}, {""},
2433 {"if", 0, st_C_ignore},
2434 {"GTY", 0, st_C_attribute},
2435 {"@end", 0, st_C_objend},
2436 {"union", 0, st_C_struct},
2437 {"define", 0, st_C_define},
2438 {"import", (C_JAVA & ~C_PLPL), st_C_ignore},
2439 {"template", 0, st_C_template},
2440 {"operator", C_PLPL, st_C_operator},
2441 {"@interface", 0, st_C_objprot},
2442 {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct},
2443 {"friend", C_PLPL, st_C_ignore},
2444 {"typedef", 0, st_C_typedef},
2445 {"return", 0, st_C_ignore},
2446 {"@implementation",0, st_C_objimpl},
2447 {"@protocol", 0, st_C_objprot},
2448 {"interface", (C_JAVA & ~C_PLPL), st_C_struct},
2449 {"extern", 0, st_C_extern},
2450 {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct},
2451 {"struct", 0, st_C_struct},
2452 {"domain", C_STAR, st_C_struct},
2453 {"switch", 0, st_C_ignore},
2454 {"enum", 0, st_C_enum},
2455 {"for", 0, st_C_ignore},
2456 {"namespace", C_PLPL, st_C_struct},
2457 {"class", 0, st_C_class},
2458 {"while", 0, st_C_ignore},
2459 {"undef", 0, st_C_define},
2460 {"package", (C_JAVA & ~C_PLPL), st_C_ignore},
2461 {"__attribute__", 0, st_C_attribute},
2462 {"SYSCALL", 0, st_C_gnumacro},
2463 {"ENTRY", 0, st_C_gnumacro},
2464 {"PSEUDO", 0, st_C_gnumacro},
2465 {"DEFUN", 0, st_C_gnumacro}
2468 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2470 register int key = hash (str, len);
2472 if (key <= MAX_HASH_VALUE && key >= 0)
2474 register const char *s = wordlist[key].name;
2476 if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2477 return &wordlist[key];
2480 return 0;
2482 /*%>*/
2484 static enum sym_type
2485 C_symtype (char *str, int len, int c_ext)
2487 register struct C_stab_entry *se = in_word_set (str, len);
2489 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2490 return st_none;
2491 return se->type;
2496 * Ignoring __attribute__ ((list))
2498 static bool inattribute; /* looking at an __attribute__ construct */
2501 * C functions and variables are recognized using a simple
2502 * finite automaton. fvdef is its state variable.
2504 static enum
2506 fvnone, /* nothing seen */
2507 fdefunkey, /* Emacs DEFUN keyword seen */
2508 fdefunname, /* Emacs DEFUN name seen */
2509 foperator, /* func: operator keyword seen (cplpl) */
2510 fvnameseen, /* function or variable name seen */
2511 fstartlist, /* func: just after open parenthesis */
2512 finlist, /* func: in parameter list */
2513 flistseen, /* func: after parameter list */
2514 fignore, /* func: before open brace */
2515 vignore /* var-like: ignore until ';' */
2516 } fvdef;
2518 static bool fvextern; /* func or var: extern keyword seen; */
2521 * typedefs are recognized using a simple finite automaton.
2522 * typdef is its state variable.
2524 static enum
2526 tnone, /* nothing seen */
2527 tkeyseen, /* typedef keyword seen */
2528 ttypeseen, /* defined type seen */
2529 tinbody, /* inside typedef body */
2530 tend, /* just before typedef tag */
2531 tignore /* junk after typedef tag */
2532 } typdef;
2535 * struct-like structures (enum, struct and union) are recognized
2536 * using another simple finite automaton. `structdef' is its state
2537 * variable.
2539 static enum
2541 snone, /* nothing seen yet,
2542 or in struct body if bracelev > 0 */
2543 skeyseen, /* struct-like keyword seen */
2544 stagseen, /* struct-like tag seen */
2545 scolonseen /* colon seen after struct-like tag */
2546 } structdef;
2549 * When objdef is different from onone, objtag is the name of the class.
2551 static const char *objtag = "<uninited>";
2554 * Yet another little state machine to deal with preprocessor lines.
2556 static enum
2558 dnone, /* nothing seen */
2559 dsharpseen, /* '#' seen as first char on line */
2560 ddefineseen, /* '#' and 'define' seen */
2561 dignorerest /* ignore rest of line */
2562 } definedef;
2565 * State machine for Objective C protocols and implementations.
2566 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2568 static enum
2570 onone, /* nothing seen */
2571 oprotocol, /* @interface or @protocol seen */
2572 oimplementation, /* @implementations seen */
2573 otagseen, /* class name seen */
2574 oparenseen, /* parenthesis before category seen */
2575 ocatseen, /* category name seen */
2576 oinbody, /* in @implementation body */
2577 omethodsign, /* in @implementation body, after +/- */
2578 omethodtag, /* after method name */
2579 omethodcolon, /* after method colon */
2580 omethodparm, /* after method parameter */
2581 oignore /* wait for @end */
2582 } objdef;
2586 * Use this structure to keep info about the token read, and how it
2587 * should be tagged. Used by the make_C_tag function to build a tag.
2589 static struct tok
2591 char *line; /* string containing the token */
2592 int offset; /* where the token starts in LINE */
2593 int length; /* token length */
2595 The previous members can be used to pass strings around for generic
2596 purposes. The following ones specifically refer to creating tags. In this
2597 case the token contained here is the pattern that will be used to create a
2598 tag.
2600 bool valid; /* do not create a tag; the token should be
2601 invalidated whenever a state machine is
2602 reset prematurely */
2603 bool named; /* create a named tag */
2604 int lineno; /* source line number of tag */
2605 long linepos; /* source char number of tag */
2606 } token; /* latest token read */
2609 * Variables and functions for dealing with nested structures.
2610 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2612 static void pushclass_above (int, char *, int);
2613 static void popclass_above (int);
2614 static void write_classname (linebuffer *, const char *qualifier);
2616 static struct {
2617 char **cname; /* nested class names */
2618 int *bracelev; /* nested class brace level */
2619 int nl; /* class nesting level (elements used) */
2620 int size; /* length of the array */
2621 } cstack; /* stack for nested declaration tags */
2622 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2623 #define nestlev (cstack.nl)
2624 /* After struct keyword or in struct body, not inside a nested function. */
2625 #define instruct (structdef == snone && nestlev > 0 \
2626 && bracelev == cstack.bracelev[nestlev-1] + 1)
2628 static void
2629 pushclass_above (int bracelev, char *str, int len)
2631 int nl;
2633 popclass_above (bracelev);
2634 nl = cstack.nl;
2635 if (nl >= cstack.size)
2637 int size = cstack.size *= 2;
2638 xrnew (cstack.cname, size, char *);
2639 xrnew (cstack.bracelev, size, int);
2641 assert (nl == 0 || cstack.bracelev[nl-1] < bracelev);
2642 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2643 cstack.bracelev[nl] = bracelev;
2644 cstack.nl = nl + 1;
2647 static void
2648 popclass_above (int bracelev)
2650 int nl;
2652 for (nl = cstack.nl - 1;
2653 nl >= 0 && cstack.bracelev[nl] >= bracelev;
2654 nl--)
2656 free (cstack.cname[nl]);
2657 cstack.nl = nl;
2661 static void
2662 write_classname (linebuffer *cn, const char *qualifier)
2664 int i, len;
2665 int qlen = strlen (qualifier);
2667 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2669 len = 0;
2670 cn->len = 0;
2671 cn->buffer[0] = '\0';
2673 else
2675 len = strlen (cstack.cname[0]);
2676 linebuffer_setlen (cn, len);
2677 strcpy (cn->buffer, cstack.cname[0]);
2679 for (i = 1; i < cstack.nl; i++)
2681 char *s;
2682 int slen;
2684 s = cstack.cname[i];
2685 if (s == NULL)
2686 continue;
2687 slen = strlen (s);
2688 len += slen + qlen;
2689 linebuffer_setlen (cn, len);
2690 strncat (cn->buffer, qualifier, qlen);
2691 strncat (cn->buffer, s, slen);
2696 static bool consider_token (char *, int, int, int *, int, int, bool *);
2697 static void make_C_tag (bool);
2700 * consider_token ()
2701 * checks to see if the current token is at the start of a
2702 * function or variable, or corresponds to a typedef, or
2703 * is a struct/union/enum tag, or #define, or an enum constant.
2705 * *IS_FUNC gets TRUE if the token is a function or #define macro
2706 * with args. C_EXTP points to which language we are looking at.
2708 * Globals
2709 * fvdef IN OUT
2710 * structdef IN OUT
2711 * definedef IN OUT
2712 * typdef IN OUT
2713 * objdef IN OUT
2716 static bool
2717 consider_token (register char *str, register int len, register int c, int *c_extp, int bracelev, int parlev, int *is_func_or_var)
2718 /* IN: token pointer */
2719 /* IN: token length */
2720 /* IN: first char after the token */
2721 /* IN, OUT: C extensions mask */
2722 /* IN: brace level */
2723 /* IN: parenthesis level */
2724 /* OUT: function or variable found */
2726 /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2727 structtype is the type of the preceding struct-like keyword, and
2728 structbracelev is the brace level where it has been seen. */
2729 static enum sym_type structtype;
2730 static int structbracelev;
2731 static enum sym_type toktype;
2734 toktype = C_symtype (str, len, *c_extp);
2737 * Skip __attribute__
2739 if (toktype == st_C_attribute)
2741 inattribute = TRUE;
2742 return FALSE;
2746 * Advance the definedef state machine.
2748 switch (definedef)
2750 case dnone:
2751 /* We're not on a preprocessor line. */
2752 if (toktype == st_C_gnumacro)
2754 fvdef = fdefunkey;
2755 return FALSE;
2757 break;
2758 case dsharpseen:
2759 if (toktype == st_C_define)
2761 definedef = ddefineseen;
2763 else
2765 definedef = dignorerest;
2767 return FALSE;
2768 case ddefineseen:
2770 * Make a tag for any macro, unless it is a constant
2771 * and constantypedefs is FALSE.
2773 definedef = dignorerest;
2774 *is_func_or_var = (c == '(');
2775 if (!*is_func_or_var && !constantypedefs)
2776 return FALSE;
2777 else
2778 return TRUE;
2779 case dignorerest:
2780 return FALSE;
2781 default:
2782 error ("internal error: definedef value.", (char *)NULL);
2786 * Now typedefs
2788 switch (typdef)
2790 case tnone:
2791 if (toktype == st_C_typedef)
2793 if (typedefs)
2794 typdef = tkeyseen;
2795 fvextern = FALSE;
2796 fvdef = fvnone;
2797 return FALSE;
2799 break;
2800 case tkeyseen:
2801 switch (toktype)
2803 case st_none:
2804 case st_C_class:
2805 case st_C_struct:
2806 case st_C_enum:
2807 typdef = ttypeseen;
2809 break;
2810 case ttypeseen:
2811 if (structdef == snone && fvdef == fvnone)
2813 fvdef = fvnameseen;
2814 return TRUE;
2816 break;
2817 case tend:
2818 switch (toktype)
2820 case st_C_class:
2821 case st_C_struct:
2822 case st_C_enum:
2823 return FALSE;
2825 return TRUE;
2828 switch (toktype)
2830 case st_C_javastruct:
2831 if (structdef == stagseen)
2832 structdef = scolonseen;
2833 return FALSE;
2834 case st_C_template:
2835 case st_C_class:
2836 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2837 && bracelev == 0
2838 && definedef == dnone && structdef == snone
2839 && typdef == tnone && fvdef == fvnone)
2840 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2841 if (toktype == st_C_template)
2842 break;
2843 /* FALLTHRU */
2844 case st_C_struct:
2845 case st_C_enum:
2846 if (parlev == 0
2847 && fvdef != vignore
2848 && (typdef == tkeyseen
2849 || (typedefs_or_cplusplus && structdef == snone)))
2851 structdef = skeyseen;
2852 structtype = toktype;
2853 structbracelev = bracelev;
2854 if (fvdef == fvnameseen)
2855 fvdef = fvnone;
2857 return FALSE;
2860 if (structdef == skeyseen)
2862 structdef = stagseen;
2863 return TRUE;
2866 if (typdef != tnone)
2867 definedef = dnone;
2869 /* Detect Objective C constructs. */
2870 switch (objdef)
2872 case onone:
2873 switch (toktype)
2875 case st_C_objprot:
2876 objdef = oprotocol;
2877 return FALSE;
2878 case st_C_objimpl:
2879 objdef = oimplementation;
2880 return FALSE;
2882 break;
2883 case oimplementation:
2884 /* Save the class tag for functions or variables defined inside. */
2885 objtag = savenstr (str, len);
2886 objdef = oinbody;
2887 return FALSE;
2888 case oprotocol:
2889 /* Save the class tag for categories. */
2890 objtag = savenstr (str, len);
2891 objdef = otagseen;
2892 *is_func_or_var = TRUE;
2893 return TRUE;
2894 case oparenseen:
2895 objdef = ocatseen;
2896 *is_func_or_var = TRUE;
2897 return TRUE;
2898 case oinbody:
2899 break;
2900 case omethodsign:
2901 if (parlev == 0)
2903 fvdef = fvnone;
2904 objdef = omethodtag;
2905 linebuffer_setlen (&token_name, len);
2906 strncpy (token_name.buffer, str, len);
2907 token_name.buffer[len] = '\0';
2908 return TRUE;
2910 return FALSE;
2911 case omethodcolon:
2912 if (parlev == 0)
2913 objdef = omethodparm;
2914 return FALSE;
2915 case omethodparm:
2916 if (parlev == 0)
2918 fvdef = fvnone;
2919 objdef = omethodtag;
2920 linebuffer_setlen (&token_name, token_name.len + len);
2921 strncat (token_name.buffer, str, len);
2922 return TRUE;
2924 return FALSE;
2925 case oignore:
2926 if (toktype == st_C_objend)
2928 /* Memory leakage here: the string pointed by objtag is
2929 never released, because many tests would be needed to
2930 avoid breaking on incorrect input code. The amount of
2931 memory leaked here is the sum of the lengths of the
2932 class tags.
2933 free (objtag); */
2934 objdef = onone;
2936 return FALSE;
2939 /* A function, variable or enum constant? */
2940 switch (toktype)
2942 case st_C_extern:
2943 fvextern = TRUE;
2944 switch (fvdef)
2946 case finlist:
2947 case flistseen:
2948 case fignore:
2949 case vignore:
2950 break;
2951 default:
2952 fvdef = fvnone;
2954 return FALSE;
2955 case st_C_ignore:
2956 fvextern = FALSE;
2957 fvdef = vignore;
2958 return FALSE;
2959 case st_C_operator:
2960 fvdef = foperator;
2961 *is_func_or_var = TRUE;
2962 return TRUE;
2963 case st_none:
2964 if (constantypedefs
2965 && structdef == snone
2966 && structtype == st_C_enum && bracelev > structbracelev)
2967 return TRUE; /* enum constant */
2968 switch (fvdef)
2970 case fdefunkey:
2971 if (bracelev > 0)
2972 break;
2973 fvdef = fdefunname; /* GNU macro */
2974 *is_func_or_var = TRUE;
2975 return TRUE;
2976 case fvnone:
2977 switch (typdef)
2979 case ttypeseen:
2980 return FALSE;
2981 case tnone:
2982 if ((strneq (str, "asm", 3) && endtoken (str[3]))
2983 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
2985 fvdef = vignore;
2986 return FALSE;
2988 break;
2990 /* FALLTHRU */
2991 case fvnameseen:
2992 if (len >= 10 && strneq (str+len-10, "::operator", 10))
2994 if (*c_extp & C_AUTO) /* automatic detection of C++ */
2995 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2996 fvdef = foperator;
2997 *is_func_or_var = TRUE;
2998 return TRUE;
3000 if (bracelev > 0 && !instruct)
3001 break;
3002 fvdef = fvnameseen; /* function or variable */
3003 *is_func_or_var = TRUE;
3004 return TRUE;
3006 break;
3009 return FALSE;
3014 * C_entries often keeps pointers to tokens or lines which are older than
3015 * the line currently read. By keeping two line buffers, and switching
3016 * them at end of line, it is possible to use those pointers.
3018 static struct
3020 long linepos;
3021 linebuffer lb;
3022 } lbs[2];
3024 #define current_lb_is_new (newndx == curndx)
3025 #define switch_line_buffers() (curndx = 1 - curndx)
3027 #define curlb (lbs[curndx].lb)
3028 #define newlb (lbs[newndx].lb)
3029 #define curlinepos (lbs[curndx].linepos)
3030 #define newlinepos (lbs[newndx].linepos)
3032 #define plainc ((c_ext & C_EXT) == C_PLAIN)
3033 #define cplpl (c_ext & C_PLPL)
3034 #define cjava ((c_ext & C_JAVA) == C_JAVA)
3036 #define CNL_SAVE_DEFINEDEF() \
3037 do { \
3038 curlinepos = charno; \
3039 readline (&curlb, inf); \
3040 lp = curlb.buffer; \
3041 quotednl = FALSE; \
3042 newndx = curndx; \
3043 } while (0)
3045 #define CNL() \
3046 do { \
3047 CNL_SAVE_DEFINEDEF(); \
3048 if (savetoken.valid) \
3050 token = savetoken; \
3051 savetoken.valid = FALSE; \
3053 definedef = dnone; \
3054 } while (0)
3057 static void
3058 make_C_tag (int isfun)
3060 /* This function is never called when token.valid is FALSE, but
3061 we must protect against invalid input or internal errors. */
3062 if (token.valid)
3063 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3064 token.offset+token.length+1, token.lineno, token.linepos);
3065 else if (DEBUG)
3066 { /* this branch is optimised away if !DEBUG */
3067 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3068 token_name.len + 17, isfun, token.line,
3069 token.offset+token.length+1, token.lineno, token.linepos);
3070 error ("INVALID TOKEN", NULL);
3073 token.valid = FALSE;
3078 * C_entries ()
3079 * This routine finds functions, variables, typedefs,
3080 * #define's, enum constants and struct/union/enum definitions in
3081 * C syntax and adds them to the list.
3083 static void
3084 C_entries (int c_ext, FILE *inf)
3085 /* extension of C */
3086 /* input file */
3088 register char c; /* latest char read; '\0' for end of line */
3089 register char *lp; /* pointer one beyond the character `c' */
3090 int curndx, newndx; /* indices for current and new lb */
3091 register int tokoff; /* offset in line of start of current token */
3092 register int toklen; /* length of current token */
3093 const char *qualifier; /* string used to qualify names */
3094 int qlen; /* length of qualifier */
3095 int bracelev; /* current brace level */
3096 int bracketlev; /* current bracket level */
3097 int parlev; /* current parenthesis level */
3098 int attrparlev; /* __attribute__ parenthesis level */
3099 int templatelev; /* current template level */
3100 int typdefbracelev; /* bracelev where a typedef struct body begun */
3101 bool incomm, inquote, inchar, quotednl, midtoken;
3102 bool yacc_rules; /* in the rules part of a yacc file */
3103 struct tok savetoken = {0}; /* token saved during preprocessor handling */
3106 linebuffer_init (&lbs[0].lb);
3107 linebuffer_init (&lbs[1].lb);
3108 if (cstack.size == 0)
3110 cstack.size = (DEBUG) ? 1 : 4;
3111 cstack.nl = 0;
3112 cstack.cname = xnew (cstack.size, char *);
3113 cstack.bracelev = xnew (cstack.size, int);
3116 tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3117 curndx = newndx = 0;
3118 lp = curlb.buffer;
3119 *lp = 0;
3121 fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3122 structdef = snone; definedef = dnone; objdef = onone;
3123 yacc_rules = FALSE;
3124 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3125 token.valid = savetoken.valid = FALSE;
3126 bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3127 if (cjava)
3128 { qualifier = "."; qlen = 1; }
3129 else
3130 { qualifier = "::"; qlen = 2; }
3133 while (!feof (inf))
3135 c = *lp++;
3136 if (c == '\\')
3138 /* If we are at the end of the line, the next character is a
3139 '\0'; do not skip it, because it is what tells us
3140 to read the next line. */
3141 if (*lp == '\0')
3143 quotednl = TRUE;
3144 continue;
3146 lp++;
3147 c = ' ';
3149 else if (incomm)
3151 switch (c)
3153 case '*':
3154 if (*lp == '/')
3156 c = *lp++;
3157 incomm = FALSE;
3159 break;
3160 case '\0':
3161 /* Newlines inside comments do not end macro definitions in
3162 traditional cpp. */
3163 CNL_SAVE_DEFINEDEF ();
3164 break;
3166 continue;
3168 else if (inquote)
3170 switch (c)
3172 case '"':
3173 inquote = FALSE;
3174 break;
3175 case '\0':
3176 /* Newlines inside strings do not end macro definitions
3177 in traditional cpp, even though compilers don't
3178 usually accept them. */
3179 CNL_SAVE_DEFINEDEF ();
3180 break;
3182 continue;
3184 else if (inchar)
3186 switch (c)
3188 case '\0':
3189 /* Hmmm, something went wrong. */
3190 CNL ();
3191 /* FALLTHRU */
3192 case '\'':
3193 inchar = FALSE;
3194 break;
3196 continue;
3198 else if (bracketlev > 0)
3200 switch (c)
3202 case ']':
3203 if (--bracketlev > 0)
3204 continue;
3205 break;
3206 case '\0':
3207 CNL_SAVE_DEFINEDEF ();
3208 break;
3210 continue;
3212 else switch (c)
3214 case '"':
3215 inquote = TRUE;
3216 if (inattribute)
3217 break;
3218 switch (fvdef)
3220 case fdefunkey:
3221 case fstartlist:
3222 case finlist:
3223 case fignore:
3224 case vignore:
3225 break;
3226 default:
3227 fvextern = FALSE;
3228 fvdef = fvnone;
3230 continue;
3231 case '\'':
3232 inchar = TRUE;
3233 if (inattribute)
3234 break;
3235 if (fvdef != finlist && fvdef != fignore && fvdef !=vignore)
3237 fvextern = FALSE;
3238 fvdef = fvnone;
3240 continue;
3241 case '/':
3242 if (*lp == '*')
3244 incomm = TRUE;
3245 lp++;
3246 c = ' ';
3248 else if (/* cplpl && */ *lp == '/')
3250 c = '\0';
3252 break;
3253 case '%':
3254 if ((c_ext & YACC) && *lp == '%')
3256 /* Entering or exiting rules section in yacc file. */
3257 lp++;
3258 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3259 typdef = tnone; structdef = snone;
3260 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3261 bracelev = 0;
3262 yacc_rules = !yacc_rules;
3263 continue;
3265 else
3266 break;
3267 case '#':
3268 if (definedef == dnone)
3270 char *cp;
3271 bool cpptoken = TRUE;
3273 /* Look back on this line. If all blanks, or nonblanks
3274 followed by an end of comment, this is a preprocessor
3275 token. */
3276 for (cp = newlb.buffer; cp < lp-1; cp++)
3277 if (!iswhite (*cp))
3279 if (*cp == '*' && *(cp+1) == '/')
3281 cp++;
3282 cpptoken = TRUE;
3284 else
3285 cpptoken = FALSE;
3287 if (cpptoken)
3288 definedef = dsharpseen;
3289 } /* if (definedef == dnone) */
3290 continue;
3291 case '[':
3292 bracketlev++;
3293 continue;
3294 } /* switch (c) */
3297 /* Consider token only if some involved conditions are satisfied. */
3298 if (typdef != tignore
3299 && definedef != dignorerest
3300 && fvdef != finlist
3301 && templatelev == 0
3302 && (definedef != dnone
3303 || structdef != scolonseen)
3304 && !inattribute)
3306 if (midtoken)
3308 if (endtoken (c))
3310 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3311 /* This handles :: in the middle,
3312 but not at the beginning of an identifier.
3313 Also, space-separated :: is not recognised. */
3315 if (c_ext & C_AUTO) /* automatic detection of C++ */
3316 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3317 lp += 2;
3318 toklen += 2;
3319 c = lp[-1];
3320 goto still_in_token;
3322 else
3324 bool funorvar = FALSE;
3326 if (yacc_rules
3327 || consider_token (newlb.buffer + tokoff, toklen, c,
3328 &c_ext, bracelev, parlev,
3329 &funorvar))
3331 if (fvdef == foperator)
3333 char *oldlp = lp;
3334 lp = skip_spaces (lp-1);
3335 if (*lp != '\0')
3336 lp += 1;
3337 while (*lp != '\0'
3338 && !iswhite (*lp) && *lp != '(')
3339 lp += 1;
3340 c = *lp++;
3341 toklen += lp - oldlp;
3343 token.named = FALSE;
3344 if (!plainc
3345 && nestlev > 0 && definedef == dnone)
3346 /* in struct body */
3348 write_classname (&token_name, qualifier);
3349 linebuffer_setlen (&token_name,
3350 token_name.len+qlen+toklen);
3351 strcat (token_name.buffer, qualifier);
3352 strncat (token_name.buffer,
3353 newlb.buffer + tokoff, toklen);
3354 token.named = TRUE;
3356 else if (objdef == ocatseen)
3357 /* Objective C category */
3359 int len = strlen (objtag) + 2 + toklen;
3360 linebuffer_setlen (&token_name, len);
3361 strcpy (token_name.buffer, objtag);
3362 strcat (token_name.buffer, "(");
3363 strncat (token_name.buffer,
3364 newlb.buffer + tokoff, toklen);
3365 strcat (token_name.buffer, ")");
3366 token.named = TRUE;
3368 else if (objdef == omethodtag
3369 || objdef == omethodparm)
3370 /* Objective C method */
3372 token.named = TRUE;
3374 else if (fvdef == fdefunname)
3375 /* GNU DEFUN and similar macros */
3377 bool defun = (newlb.buffer[tokoff] == 'F');
3378 int off = tokoff;
3379 int len = toklen;
3381 /* Rewrite the tag so that emacs lisp DEFUNs
3382 can be found by their elisp name */
3383 if (defun)
3385 off += 1;
3386 len -= 1;
3388 linebuffer_setlen (&token_name, len);
3389 strncpy (token_name.buffer,
3390 newlb.buffer + off, len);
3391 token_name.buffer[len] = '\0';
3392 if (defun)
3393 while (--len >= 0)
3394 if (token_name.buffer[len] == '_')
3395 token_name.buffer[len] = '-';
3396 token.named = defun;
3398 else
3400 linebuffer_setlen (&token_name, toklen);
3401 strncpy (token_name.buffer,
3402 newlb.buffer + tokoff, toklen);
3403 token_name.buffer[toklen] = '\0';
3404 /* Name macros and members. */
3405 token.named = (structdef == stagseen
3406 || typdef == ttypeseen
3407 || typdef == tend
3408 || (funorvar
3409 && definedef == dignorerest)
3410 || (funorvar
3411 && definedef == dnone
3412 && structdef == snone
3413 && bracelev > 0));
3415 token.lineno = lineno;
3416 token.offset = tokoff;
3417 token.length = toklen;
3418 token.line = newlb.buffer;
3419 token.linepos = newlinepos;
3420 token.valid = TRUE;
3422 if (definedef == dnone
3423 && (fvdef == fvnameseen
3424 || fvdef == foperator
3425 || structdef == stagseen
3426 || typdef == tend
3427 || typdef == ttypeseen
3428 || objdef != onone))
3430 if (current_lb_is_new)
3431 switch_line_buffers ();
3433 else if (definedef != dnone
3434 || fvdef == fdefunname
3435 || instruct)
3436 make_C_tag (funorvar);
3438 else /* not yacc and consider_token failed */
3440 if (inattribute && fvdef == fignore)
3442 /* We have just met __attribute__ after a
3443 function parameter list: do not tag the
3444 function again. */
3445 fvdef = fvnone;
3448 midtoken = FALSE;
3450 } /* if (endtoken (c)) */
3451 else if (intoken (c))
3452 still_in_token:
3454 toklen++;
3455 continue;
3457 } /* if (midtoken) */
3458 else if (begtoken (c))
3460 switch (definedef)
3462 case dnone:
3463 switch (fvdef)
3465 case fstartlist:
3466 /* This prevents tagging fb in
3467 void (__attribute__((noreturn)) *fb) (void);
3468 Fixing this is not easy and not very important. */
3469 fvdef = finlist;
3470 continue;
3471 case flistseen:
3472 if (plainc || declarations)
3474 make_C_tag (TRUE); /* a function */
3475 fvdef = fignore;
3477 break;
3479 if (structdef == stagseen && !cjava)
3481 popclass_above (bracelev);
3482 structdef = snone;
3484 break;
3485 case dsharpseen:
3486 savetoken = token;
3487 break;
3489 if (!yacc_rules || lp == newlb.buffer + 1)
3491 tokoff = lp - 1 - newlb.buffer;
3492 toklen = 1;
3493 midtoken = TRUE;
3495 continue;
3496 } /* if (begtoken) */
3497 } /* if must look at token */
3500 /* Detect end of line, colon, comma, semicolon and various braces
3501 after having handled a token.*/
3502 switch (c)
3504 case ':':
3505 if (inattribute)
3506 break;
3507 if (yacc_rules && token.offset == 0 && token.valid)
3509 make_C_tag (FALSE); /* a yacc function */
3510 break;
3512 if (definedef != dnone)
3513 break;
3514 switch (objdef)
3516 case otagseen:
3517 objdef = oignore;
3518 make_C_tag (TRUE); /* an Objective C class */
3519 break;
3520 case omethodtag:
3521 case omethodparm:
3522 objdef = omethodcolon;
3523 linebuffer_setlen (&token_name, token_name.len + 1);
3524 strcat (token_name.buffer, ":");
3525 break;
3527 if (structdef == stagseen)
3529 structdef = scolonseen;
3530 break;
3532 /* Should be useless, but may be work as a safety net. */
3533 if (cplpl && fvdef == flistseen)
3535 make_C_tag (TRUE); /* a function */
3536 fvdef = fignore;
3537 break;
3539 break;
3540 case ';':
3541 if (definedef != dnone || inattribute)
3542 break;
3543 switch (typdef)
3545 case tend:
3546 case ttypeseen:
3547 make_C_tag (FALSE); /* a typedef */
3548 typdef = tnone;
3549 fvdef = fvnone;
3550 break;
3551 case tnone:
3552 case tinbody:
3553 case tignore:
3554 switch (fvdef)
3556 case fignore:
3557 if (typdef == tignore || cplpl)
3558 fvdef = fvnone;
3559 break;
3560 case fvnameseen:
3561 if ((globals && bracelev == 0 && (!fvextern || declarations))
3562 || (members && instruct))
3563 make_C_tag (FALSE); /* a variable */
3564 fvextern = FALSE;
3565 fvdef = fvnone;
3566 token.valid = FALSE;
3567 break;
3568 case flistseen:
3569 if ((declarations
3570 && (cplpl || !instruct)
3571 && (typdef == tnone || (typdef != tignore && instruct)))
3572 || (members
3573 && plainc && instruct))
3574 make_C_tag (TRUE); /* a function */
3575 /* FALLTHRU */
3576 default:
3577 fvextern = FALSE;
3578 fvdef = fvnone;
3579 if (declarations
3580 && cplpl && structdef == stagseen)
3581 make_C_tag (FALSE); /* forward declaration */
3582 else
3583 token.valid = FALSE;
3584 } /* switch (fvdef) */
3585 /* FALLTHRU */
3586 default:
3587 if (!instruct)
3588 typdef = tnone;
3590 if (structdef == stagseen)
3591 structdef = snone;
3592 break;
3593 case ',':
3594 if (definedef != dnone || inattribute)
3595 break;
3596 switch (objdef)
3598 case omethodtag:
3599 case omethodparm:
3600 make_C_tag (TRUE); /* an Objective C method */
3601 objdef = oinbody;
3602 break;
3604 switch (fvdef)
3606 case fdefunkey:
3607 case foperator:
3608 case fstartlist:
3609 case finlist:
3610 case fignore:
3611 case vignore:
3612 break;
3613 case fdefunname:
3614 fvdef = fignore;
3615 break;
3616 case fvnameseen:
3617 if (parlev == 0
3618 && ((globals
3619 && bracelev == 0
3620 && templatelev == 0
3621 && (!fvextern || declarations))
3622 || (members && instruct)))
3623 make_C_tag (FALSE); /* a variable */
3624 break;
3625 case flistseen:
3626 if ((declarations && typdef == tnone && !instruct)
3627 || (members && typdef != tignore && instruct))
3629 make_C_tag (TRUE); /* a function */
3630 fvdef = fvnameseen;
3632 else if (!declarations)
3633 fvdef = fvnone;
3634 token.valid = FALSE;
3635 break;
3636 default:
3637 fvdef = fvnone;
3639 if (structdef == stagseen)
3640 structdef = snone;
3641 break;
3642 case ']':
3643 if (definedef != dnone || inattribute)
3644 break;
3645 if (structdef == stagseen)
3646 structdef = snone;
3647 switch (typdef)
3649 case ttypeseen:
3650 case tend:
3651 typdef = tignore;
3652 make_C_tag (FALSE); /* a typedef */
3653 break;
3654 case tnone:
3655 case tinbody:
3656 switch (fvdef)
3658 case foperator:
3659 case finlist:
3660 case fignore:
3661 case vignore:
3662 break;
3663 case fvnameseen:
3664 if ((members && bracelev == 1)
3665 || (globals && bracelev == 0
3666 && (!fvextern || declarations)))
3667 make_C_tag (FALSE); /* a variable */
3668 /* FALLTHRU */
3669 default:
3670 fvdef = fvnone;
3672 break;
3674 break;
3675 case '(':
3676 if (inattribute)
3678 attrparlev++;
3679 break;
3681 if (definedef != dnone)
3682 break;
3683 if (objdef == otagseen && parlev == 0)
3684 objdef = oparenseen;
3685 switch (fvdef)
3687 case fvnameseen:
3688 if (typdef == ttypeseen
3689 && *lp != '*'
3690 && !instruct)
3692 /* This handles constructs like:
3693 typedef void OperatorFun (int fun); */
3694 make_C_tag (FALSE);
3695 typdef = tignore;
3696 fvdef = fignore;
3697 break;
3699 /* FALLTHRU */
3700 case foperator:
3701 fvdef = fstartlist;
3702 break;
3703 case flistseen:
3704 fvdef = finlist;
3705 break;
3707 parlev++;
3708 break;
3709 case ')':
3710 if (inattribute)
3712 if (--attrparlev == 0)
3713 inattribute = FALSE;
3714 break;
3716 if (definedef != dnone)
3717 break;
3718 if (objdef == ocatseen && parlev == 1)
3720 make_C_tag (TRUE); /* an Objective C category */
3721 objdef = oignore;
3723 if (--parlev == 0)
3725 switch (fvdef)
3727 case fstartlist:
3728 case finlist:
3729 fvdef = flistseen;
3730 break;
3732 if (!instruct
3733 && (typdef == tend
3734 || typdef == ttypeseen))
3736 typdef = tignore;
3737 make_C_tag (FALSE); /* a typedef */
3740 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
3741 parlev = 0;
3742 break;
3743 case '{':
3744 if (definedef != dnone)
3745 break;
3746 if (typdef == ttypeseen)
3748 /* Whenever typdef is set to tinbody (currently only
3749 here), typdefbracelev should be set to bracelev. */
3750 typdef = tinbody;
3751 typdefbracelev = bracelev;
3753 switch (fvdef)
3755 case flistseen:
3756 make_C_tag (TRUE); /* a function */
3757 /* FALLTHRU */
3758 case fignore:
3759 fvdef = fvnone;
3760 break;
3761 case fvnone:
3762 switch (objdef)
3764 case otagseen:
3765 make_C_tag (TRUE); /* an Objective C class */
3766 objdef = oignore;
3767 break;
3768 case omethodtag:
3769 case omethodparm:
3770 make_C_tag (TRUE); /* an Objective C method */
3771 objdef = oinbody;
3772 break;
3773 default:
3774 /* Neutralize `extern "C" {' grot. */
3775 if (bracelev == 0 && structdef == snone && nestlev == 0
3776 && typdef == tnone)
3777 bracelev = -1;
3779 break;
3781 switch (structdef)
3783 case skeyseen: /* unnamed struct */
3784 pushclass_above (bracelev, NULL, 0);
3785 structdef = snone;
3786 break;
3787 case stagseen: /* named struct or enum */
3788 case scolonseen: /* a class */
3789 pushclass_above (bracelev,token.line+token.offset, token.length);
3790 structdef = snone;
3791 make_C_tag (FALSE); /* a struct or enum */
3792 break;
3794 bracelev += 1;
3795 break;
3796 case '*':
3797 if (definedef != dnone)
3798 break;
3799 if (fvdef == fstartlist)
3801 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
3802 token.valid = FALSE;
3804 break;
3805 case '}':
3806 if (definedef != dnone)
3807 break;
3808 bracelev -= 1;
3809 if (!ignoreindent && lp == newlb.buffer + 1)
3811 if (bracelev != 0)
3812 token.valid = FALSE; /* unexpected value, token unreliable */
3813 bracelev = 0; /* reset brace level if first column */
3814 parlev = 0; /* also reset paren level, just in case... */
3816 else if (bracelev < 0)
3818 token.valid = FALSE; /* something gone amiss, token unreliable */
3819 bracelev = 0;
3821 if (bracelev == 0 && fvdef == vignore)
3822 fvdef = fvnone; /* end of function */
3823 popclass_above (bracelev);
3824 structdef = snone;
3825 /* Only if typdef == tinbody is typdefbracelev significant. */
3826 if (typdef == tinbody && bracelev <= typdefbracelev)
3828 assert (bracelev == typdefbracelev);
3829 typdef = tend;
3831 break;
3832 case '=':
3833 if (definedef != dnone)
3834 break;
3835 switch (fvdef)
3837 case foperator:
3838 case finlist:
3839 case fignore:
3840 case vignore:
3841 break;
3842 case fvnameseen:
3843 if ((members && bracelev == 1)
3844 || (globals && bracelev == 0 && (!fvextern || declarations)))
3845 make_C_tag (FALSE); /* a variable */
3846 /* FALLTHRU */
3847 default:
3848 fvdef = vignore;
3850 break;
3851 case '<':
3852 if (cplpl
3853 && (structdef == stagseen || fvdef == fvnameseen))
3855 templatelev++;
3856 break;
3858 goto resetfvdef;
3859 case '>':
3860 if (templatelev > 0)
3862 templatelev--;
3863 break;
3865 goto resetfvdef;
3866 case '+':
3867 case '-':
3868 if (objdef == oinbody && bracelev == 0)
3870 objdef = omethodsign;
3871 break;
3873 /* FALLTHRU */
3874 resetfvdef:
3875 case '#': case '~': case '&': case '%': case '/':
3876 case '|': case '^': case '!': case '.': case '?':
3877 if (definedef != dnone)
3878 break;
3879 /* These surely cannot follow a function tag in C. */
3880 switch (fvdef)
3882 case foperator:
3883 case finlist:
3884 case fignore:
3885 case vignore:
3886 break;
3887 default:
3888 fvdef = fvnone;
3890 break;
3891 case '\0':
3892 if (objdef == otagseen)
3894 make_C_tag (TRUE); /* an Objective C class */
3895 objdef = oignore;
3897 /* If a macro spans multiple lines don't reset its state. */
3898 if (quotednl)
3899 CNL_SAVE_DEFINEDEF ();
3900 else
3901 CNL ();
3902 break;
3903 } /* switch (c) */
3905 } /* while not eof */
3907 free (lbs[0].lb.buffer);
3908 free (lbs[1].lb.buffer);
3912 * Process either a C++ file or a C file depending on the setting
3913 * of a global flag.
3915 static void
3916 default_C_entries (FILE *inf)
3918 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
3921 /* Always do plain C. */
3922 static void
3923 plain_C_entries (FILE *inf)
3925 C_entries (0, inf);
3928 /* Always do C++. */
3929 static void
3930 Cplusplus_entries (FILE *inf)
3932 C_entries (C_PLPL, inf);
3935 /* Always do Java. */
3936 static void
3937 Cjava_entries (FILE *inf)
3939 C_entries (C_JAVA, inf);
3942 /* Always do C*. */
3943 static void
3944 Cstar_entries (FILE *inf)
3946 C_entries (C_STAR, inf);
3949 /* Always do Yacc. */
3950 static void
3951 Yacc_entries (FILE *inf)
3953 C_entries (YACC, inf);
3957 /* Useful macros. */
3958 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
3959 for (; /* loop initialization */ \
3960 !feof (file_pointer) /* loop test */ \
3961 && /* instructions at start of loop */ \
3962 (readline (&line_buffer, file_pointer), \
3963 char_pointer = line_buffer.buffer, \
3964 TRUE); \
3967 #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \
3968 ((assert("" kw), TRUE) /* syntax error if not a literal string */ \
3969 && strneq ((cp), kw, sizeof(kw)-1) /* cp points at kw */ \
3970 && notinname ((cp)[sizeof(kw)-1]) /* end of kw */ \
3971 && ((cp) = skip_spaces((cp)+sizeof(kw)-1))) /* skip spaces */
3973 /* Similar to LOOKING_AT but does not use notinname, does not skip */
3974 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
3975 ((assert("" kw), TRUE) /* syntax error if not a literal string */ \
3976 && strncaseeq ((cp), kw, sizeof(kw)-1) /* cp points at kw */ \
3977 && ((cp) += sizeof(kw)-1)) /* skip spaces */
3980 * Read a file, but do no processing. This is used to do regexp
3981 * matching on files that have no language defined.
3983 static void
3984 just_read_file (FILE *inf)
3986 register char *dummy;
3988 LOOP_ON_INPUT_LINES (inf, lb, dummy)
3989 continue;
3993 /* Fortran parsing */
3995 static void F_takeprec (void);
3996 static void F_getit (FILE *);
3998 static void
3999 F_takeprec (void)
4001 dbp = skip_spaces (dbp);
4002 if (*dbp != '*')
4003 return;
4004 dbp++;
4005 dbp = skip_spaces (dbp);
4006 if (strneq (dbp, "(*)", 3))
4008 dbp += 3;
4009 return;
4011 if (!ISDIGIT (*dbp))
4013 --dbp; /* force failure */
4014 return;
4017 dbp++;
4018 while (ISDIGIT (*dbp));
4021 static void
4022 F_getit (FILE *inf)
4024 register char *cp;
4026 dbp = skip_spaces (dbp);
4027 if (*dbp == '\0')
4029 readline (&lb, inf);
4030 dbp = lb.buffer;
4031 if (dbp[5] != '&')
4032 return;
4033 dbp += 6;
4034 dbp = skip_spaces (dbp);
4036 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
4037 return;
4038 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
4039 continue;
4040 make_tag (dbp, cp-dbp, TRUE,
4041 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4045 static void
4046 Fortran_functions (FILE *inf)
4048 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4050 if (*dbp == '%')
4051 dbp++; /* Ratfor escape to fortran */
4052 dbp = skip_spaces (dbp);
4053 if (*dbp == '\0')
4054 continue;
4056 if (LOOKING_AT_NOCASE (dbp, "recursive"))
4057 dbp = skip_spaces (dbp);
4059 switch (lowcase (*dbp))
4061 case 'i':
4062 if (nocase_tail ("integer"))
4063 F_takeprec ();
4064 break;
4065 case 'r':
4066 if (nocase_tail ("real"))
4067 F_takeprec ();
4068 break;
4069 case 'l':
4070 if (nocase_tail ("logical"))
4071 F_takeprec ();
4072 break;
4073 case 'c':
4074 if (nocase_tail ("complex") || nocase_tail ("character"))
4075 F_takeprec ();
4076 break;
4077 case 'd':
4078 if (nocase_tail ("double"))
4080 dbp = skip_spaces (dbp);
4081 if (*dbp == '\0')
4082 continue;
4083 if (nocase_tail ("precision"))
4084 break;
4085 continue;
4087 break;
4089 dbp = skip_spaces (dbp);
4090 if (*dbp == '\0')
4091 continue;
4092 switch (lowcase (*dbp))
4094 case 'f':
4095 if (nocase_tail ("function"))
4096 F_getit (inf);
4097 continue;
4098 case 's':
4099 if (nocase_tail ("subroutine"))
4100 F_getit (inf);
4101 continue;
4102 case 'e':
4103 if (nocase_tail ("entry"))
4104 F_getit (inf);
4105 continue;
4106 case 'b':
4107 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4109 dbp = skip_spaces (dbp);
4110 if (*dbp == '\0') /* assume un-named */
4111 make_tag ("blockdata", 9, TRUE,
4112 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4113 else
4114 F_getit (inf); /* look for name */
4116 continue;
4123 * Ada parsing
4124 * Original code by
4125 * Philippe Waroquiers (1998)
4128 /* Once we are positioned after an "interesting" keyword, let's get
4129 the real tag value necessary. */
4130 static void
4131 Ada_getit (FILE *inf, const char *name_qualifier)
4133 register char *cp;
4134 char *name;
4135 char c;
4137 while (!feof (inf))
4139 dbp = skip_spaces (dbp);
4140 if (*dbp == '\0'
4141 || (dbp[0] == '-' && dbp[1] == '-'))
4143 readline (&lb, inf);
4144 dbp = lb.buffer;
4146 switch (lowcase(*dbp))
4148 case 'b':
4149 if (nocase_tail ("body"))
4151 /* Skipping body of procedure body or package body or ....
4152 resetting qualifier to body instead of spec. */
4153 name_qualifier = "/b";
4154 continue;
4156 break;
4157 case 't':
4158 /* Skipping type of task type or protected type ... */
4159 if (nocase_tail ("type"))
4160 continue;
4161 break;
4163 if (*dbp == '"')
4165 dbp += 1;
4166 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4167 continue;
4169 else
4171 dbp = skip_spaces (dbp);
4172 for (cp = dbp;
4173 (*cp != '\0'
4174 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4175 cp++)
4176 continue;
4177 if (cp == dbp)
4178 return;
4180 c = *cp;
4181 *cp = '\0';
4182 name = concat (dbp, name_qualifier, "");
4183 *cp = c;
4184 make_tag (name, strlen (name), TRUE,
4185 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4186 free (name);
4187 if (c == '"')
4188 dbp = cp + 1;
4189 return;
4193 static void
4194 Ada_funcs (FILE *inf)
4196 bool inquote = FALSE;
4197 bool skip_till_semicolumn = FALSE;
4199 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4201 while (*dbp != '\0')
4203 /* Skip a string i.e. "abcd". */
4204 if (inquote || (*dbp == '"'))
4206 dbp = etags_strchr ((inquote) ? dbp : dbp+1, '"');
4207 if (dbp != NULL)
4209 inquote = FALSE;
4210 dbp += 1;
4211 continue; /* advance char */
4213 else
4215 inquote = TRUE;
4216 break; /* advance line */
4220 /* Skip comments. */
4221 if (dbp[0] == '-' && dbp[1] == '-')
4222 break; /* advance line */
4224 /* Skip character enclosed in single quote i.e. 'a'
4225 and skip single quote starting an attribute i.e. 'Image. */
4226 if (*dbp == '\'')
4228 dbp++ ;
4229 if (*dbp != '\0')
4230 dbp++;
4231 continue;
4234 if (skip_till_semicolumn)
4236 if (*dbp == ';')
4237 skip_till_semicolumn = FALSE;
4238 dbp++;
4239 continue; /* advance char */
4242 /* Search for beginning of a token. */
4243 if (!begtoken (*dbp))
4245 dbp++;
4246 continue; /* advance char */
4249 /* We are at the beginning of a token. */
4250 switch (lowcase(*dbp))
4252 case 'f':
4253 if (!packages_only && nocase_tail ("function"))
4254 Ada_getit (inf, "/f");
4255 else
4256 break; /* from switch */
4257 continue; /* advance char */
4258 case 'p':
4259 if (!packages_only && nocase_tail ("procedure"))
4260 Ada_getit (inf, "/p");
4261 else if (nocase_tail ("package"))
4262 Ada_getit (inf, "/s");
4263 else if (nocase_tail ("protected")) /* protected type */
4264 Ada_getit (inf, "/t");
4265 else
4266 break; /* from switch */
4267 continue; /* advance char */
4269 case 'u':
4270 if (typedefs && !packages_only && nocase_tail ("use"))
4272 /* when tagging types, avoid tagging use type Pack.Typename;
4273 for this, we will skip everything till a ; */
4274 skip_till_semicolumn = TRUE;
4275 continue; /* advance char */
4278 case 't':
4279 if (!packages_only && nocase_tail ("task"))
4280 Ada_getit (inf, "/k");
4281 else if (typedefs && !packages_only && nocase_tail ("type"))
4283 Ada_getit (inf, "/t");
4284 while (*dbp != '\0')
4285 dbp += 1;
4287 else
4288 break; /* from switch */
4289 continue; /* advance char */
4292 /* Look for the end of the token. */
4293 while (!endtoken (*dbp))
4294 dbp++;
4296 } /* advance char */
4297 } /* advance line */
4302 * Unix and microcontroller assembly tag handling
4303 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4304 * Idea by Bob Weiner, Motorola Inc. (1994)
4306 static void
4307 Asm_labels (FILE *inf)
4309 register char *cp;
4311 LOOP_ON_INPUT_LINES (inf, lb, cp)
4313 /* If first char is alphabetic or one of [_.$], test for colon
4314 following identifier. */
4315 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4317 /* Read past label. */
4318 cp++;
4319 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4320 cp++;
4321 if (*cp == ':' || iswhite (*cp))
4322 /* Found end of label, so copy it and add it to the table. */
4323 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4324 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4331 * Perl support
4332 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4333 * Perl variable names: /^(my|local).../
4334 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4335 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4336 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4338 static void
4339 Perl_functions (FILE *inf)
4341 char *package = savestr ("main"); /* current package name */
4342 register char *cp;
4344 LOOP_ON_INPUT_LINES (inf, lb, cp)
4346 cp = skip_spaces (cp);
4348 if (LOOKING_AT (cp, "package"))
4350 free (package);
4351 get_tag (cp, &package);
4353 else if (LOOKING_AT (cp, "sub"))
4355 char *pos;
4356 char *sp = cp;
4358 while (!notinname (*cp))
4359 cp++;
4360 if (cp == sp)
4361 continue; /* nothing found */
4362 if ((pos = etags_strchr (sp, ':')) != NULL
4363 && pos < cp && pos[1] == ':')
4364 /* The name is already qualified. */
4365 make_tag (sp, cp - sp, TRUE,
4366 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4367 else
4368 /* Qualify it. */
4370 char savechar, *name;
4372 savechar = *cp;
4373 *cp = '\0';
4374 name = concat (package, "::", sp);
4375 *cp = savechar;
4376 make_tag (name, strlen(name), TRUE,
4377 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4378 free (name);
4381 else if (globals) /* only if we are tagging global vars */
4383 /* Skip a qualifier, if any. */
4384 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4385 /* After "my" or "local", but before any following paren or space. */
4386 char *varstart = cp;
4388 if (qual /* should this be removed? If yes, how? */
4389 && (*cp == '$' || *cp == '@' || *cp == '%'))
4391 varstart += 1;
4393 cp++;
4394 while (ISALNUM (*cp) || *cp == '_');
4396 else if (qual)
4398 /* Should be examining a variable list at this point;
4399 could insist on seeing an open parenthesis. */
4400 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4401 cp++;
4403 else
4404 continue;
4406 make_tag (varstart, cp - varstart, FALSE,
4407 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4410 free (package);
4415 * Python support
4416 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4417 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4418 * More ideas by seb bacon <seb@jamkit.com> (2002)
4420 static void
4421 Python_functions (FILE *inf)
4423 register char *cp;
4425 LOOP_ON_INPUT_LINES (inf, lb, cp)
4427 cp = skip_spaces (cp);
4428 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4430 char *name = cp;
4431 while (!notinname (*cp) && *cp != ':')
4432 cp++;
4433 make_tag (name, cp - name, TRUE,
4434 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4441 * PHP support
4442 * Look for:
4443 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4444 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4445 * - /^[ \t]*define\(\"[^\"]+/
4446 * Only with --members:
4447 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4448 * Idea by Diez B. Roggisch (2001)
4450 static void
4451 PHP_functions (FILE *inf)
4453 register char *cp, *name;
4454 bool search_identifier = FALSE;
4456 LOOP_ON_INPUT_LINES (inf, lb, cp)
4458 cp = skip_spaces (cp);
4459 name = cp;
4460 if (search_identifier
4461 && *cp != '\0')
4463 while (!notinname (*cp))
4464 cp++;
4465 make_tag (name, cp - name, TRUE,
4466 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4467 search_identifier = FALSE;
4469 else if (LOOKING_AT (cp, "function"))
4471 if(*cp == '&')
4472 cp = skip_spaces (cp+1);
4473 if(*cp != '\0')
4475 name = cp;
4476 while (!notinname (*cp))
4477 cp++;
4478 make_tag (name, cp - name, TRUE,
4479 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4481 else
4482 search_identifier = TRUE;
4484 else if (LOOKING_AT (cp, "class"))
4486 if (*cp != '\0')
4488 name = cp;
4489 while (*cp != '\0' && !iswhite (*cp))
4490 cp++;
4491 make_tag (name, cp - name, FALSE,
4492 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4494 else
4495 search_identifier = TRUE;
4497 else if (strneq (cp, "define", 6)
4498 && (cp = skip_spaces (cp+6))
4499 && *cp++ == '('
4500 && (*cp == '"' || *cp == '\''))
4502 char quote = *cp++;
4503 name = cp;
4504 while (*cp != quote && *cp != '\0')
4505 cp++;
4506 make_tag (name, cp - name, FALSE,
4507 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4509 else if (members
4510 && LOOKING_AT (cp, "var")
4511 && *cp == '$')
4513 name = cp;
4514 while (!notinname(*cp))
4515 cp++;
4516 make_tag (name, cp - name, FALSE,
4517 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4524 * Cobol tag functions
4525 * We could look for anything that could be a paragraph name.
4526 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4527 * Idea by Corny de Souza (1993)
4529 static void
4530 Cobol_paragraphs (FILE *inf)
4532 register char *bp, *ep;
4534 LOOP_ON_INPUT_LINES (inf, lb, bp)
4536 if (lb.len < 9)
4537 continue;
4538 bp += 8;
4540 /* If eoln, compiler option or comment ignore whole line. */
4541 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4542 continue;
4544 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4545 continue;
4546 if (*ep++ == '.')
4547 make_tag (bp, ep - bp, TRUE,
4548 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4554 * Makefile support
4555 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4557 static void
4558 Makefile_targets (FILE *inf)
4560 register char *bp;
4562 LOOP_ON_INPUT_LINES (inf, lb, bp)
4564 if (*bp == '\t' || *bp == '#')
4565 continue;
4566 while (*bp != '\0' && *bp != '=' && *bp != ':')
4567 bp++;
4568 if (*bp == ':' || (globals && *bp == '='))
4570 /* We should detect if there is more than one tag, but we do not.
4571 We just skip initial and final spaces. */
4572 char * namestart = skip_spaces (lb.buffer);
4573 while (--bp > namestart)
4574 if (!notinname (*bp))
4575 break;
4576 make_tag (namestart, bp - namestart + 1, TRUE,
4577 lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4584 * Pascal parsing
4585 * Original code by Mosur K. Mohan (1989)
4587 * Locates tags for procedures & functions. Doesn't do any type- or
4588 * var-definitions. It does look for the keyword "extern" or
4589 * "forward" immediately following the procedure statement; if found,
4590 * the tag is skipped.
4592 static void
4593 Pascal_functions (FILE *inf)
4595 linebuffer tline; /* mostly copied from C_entries */
4596 long save_lcno;
4597 int save_lineno, namelen, taglen;
4598 char c, *name;
4600 bool /* each of these flags is TRUE if: */
4601 incomment, /* point is inside a comment */
4602 inquote, /* point is inside '..' string */
4603 get_tagname, /* point is after PROCEDURE/FUNCTION
4604 keyword, so next item = potential tag */
4605 found_tag, /* point is after a potential tag */
4606 inparms, /* point is within parameter-list */
4607 verify_tag; /* point has passed the parm-list, so the
4608 next token will determine whether this
4609 is a FORWARD/EXTERN to be ignored, or
4610 whether it is a real tag */
4612 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4613 name = NULL; /* keep compiler quiet */
4614 dbp = lb.buffer;
4615 *dbp = '\0';
4616 linebuffer_init (&tline);
4618 incomment = inquote = FALSE;
4619 found_tag = FALSE; /* have a proc name; check if extern */
4620 get_tagname = FALSE; /* found "procedure" keyword */
4621 inparms = FALSE; /* found '(' after "proc" */
4622 verify_tag = FALSE; /* check if "extern" is ahead */
4625 while (!feof (inf)) /* long main loop to get next char */
4627 c = *dbp++;
4628 if (c == '\0') /* if end of line */
4630 readline (&lb, inf);
4631 dbp = lb.buffer;
4632 if (*dbp == '\0')
4633 continue;
4634 if (!((found_tag && verify_tag)
4635 || get_tagname))
4636 c = *dbp++; /* only if don't need *dbp pointing
4637 to the beginning of the name of
4638 the procedure or function */
4640 if (incomment)
4642 if (c == '}') /* within { } comments */
4643 incomment = FALSE;
4644 else if (c == '*' && *dbp == ')') /* within (* *) comments */
4646 dbp++;
4647 incomment = FALSE;
4649 continue;
4651 else if (inquote)
4653 if (c == '\'')
4654 inquote = FALSE;
4655 continue;
4657 else
4658 switch (c)
4660 case '\'':
4661 inquote = TRUE; /* found first quote */
4662 continue;
4663 case '{': /* found open { comment */
4664 incomment = TRUE;
4665 continue;
4666 case '(':
4667 if (*dbp == '*') /* found open (* comment */
4669 incomment = TRUE;
4670 dbp++;
4672 else if (found_tag) /* found '(' after tag, i.e., parm-list */
4673 inparms = TRUE;
4674 continue;
4675 case ')': /* end of parms list */
4676 if (inparms)
4677 inparms = FALSE;
4678 continue;
4679 case ';':
4680 if (found_tag && !inparms) /* end of proc or fn stmt */
4682 verify_tag = TRUE;
4683 break;
4685 continue;
4687 if (found_tag && verify_tag && (*dbp != ' '))
4689 /* Check if this is an "extern" declaration. */
4690 if (*dbp == '\0')
4691 continue;
4692 if (lowcase (*dbp == 'e'))
4694 if (nocase_tail ("extern")) /* superfluous, really! */
4696 found_tag = FALSE;
4697 verify_tag = FALSE;
4700 else if (lowcase (*dbp) == 'f')
4702 if (nocase_tail ("forward")) /* check for forward reference */
4704 found_tag = FALSE;
4705 verify_tag = FALSE;
4708 if (found_tag && verify_tag) /* not external proc, so make tag */
4710 found_tag = FALSE;
4711 verify_tag = FALSE;
4712 make_tag (name, namelen, TRUE,
4713 tline.buffer, taglen, save_lineno, save_lcno);
4714 continue;
4717 if (get_tagname) /* grab name of proc or fn */
4719 char *cp;
4721 if (*dbp == '\0')
4722 continue;
4724 /* Find block name. */
4725 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
4726 continue;
4728 /* Save all values for later tagging. */
4729 linebuffer_setlen (&tline, lb.len);
4730 strcpy (tline.buffer, lb.buffer);
4731 save_lineno = lineno;
4732 save_lcno = linecharno;
4733 name = tline.buffer + (dbp - lb.buffer);
4734 namelen = cp - dbp;
4735 taglen = cp - lb.buffer + 1;
4737 dbp = cp; /* set dbp to e-o-token */
4738 get_tagname = FALSE;
4739 found_tag = TRUE;
4740 continue;
4742 /* And proceed to check for "extern". */
4744 else if (!incomment && !inquote && !found_tag)
4746 /* Check for proc/fn keywords. */
4747 switch (lowcase (c))
4749 case 'p':
4750 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
4751 get_tagname = TRUE;
4752 continue;
4753 case 'f':
4754 if (nocase_tail ("unction"))
4755 get_tagname = TRUE;
4756 continue;
4759 } /* while not eof */
4761 free (tline.buffer);
4766 * Lisp tag functions
4767 * look for (def or (DEF, quote or QUOTE
4770 static void L_getit (void);
4772 static void
4773 L_getit (void)
4775 if (*dbp == '\'') /* Skip prefix quote */
4776 dbp++;
4777 else if (*dbp == '(')
4779 dbp++;
4780 /* Try to skip "(quote " */
4781 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
4782 /* Ok, then skip "(" before name in (defstruct (foo)) */
4783 dbp = skip_spaces (dbp);
4785 get_tag (dbp, NULL);
4788 static void
4789 Lisp_functions (FILE *inf)
4791 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4793 if (dbp[0] != '(')
4794 continue;
4796 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
4798 dbp = skip_non_spaces (dbp);
4799 dbp = skip_spaces (dbp);
4800 L_getit ();
4802 else
4804 /* Check for (foo::defmumble name-defined ... */
4806 dbp++;
4807 while (!notinname (*dbp) && *dbp != ':');
4808 if (*dbp == ':')
4811 dbp++;
4812 while (*dbp == ':');
4814 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
4816 dbp = skip_non_spaces (dbp);
4817 dbp = skip_spaces (dbp);
4818 L_getit ();
4827 * Lua script language parsing
4828 * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
4830 * "function" and "local function" are tags if they start at column 1.
4832 static void
4833 Lua_functions (FILE *inf)
4835 register char *bp;
4837 LOOP_ON_INPUT_LINES (inf, lb, bp)
4839 if (bp[0] != 'f' && bp[0] != 'l')
4840 continue;
4842 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
4844 if (LOOKING_AT (bp, "function"))
4845 get_tag (bp, NULL);
4851 * Postscript tags
4852 * Just look for lines where the first character is '/'
4853 * Also look at "defineps" for PSWrap
4854 * Ideas by:
4855 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
4856 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
4858 static void
4859 PS_functions (FILE *inf)
4861 register char *bp, *ep;
4863 LOOP_ON_INPUT_LINES (inf, lb, bp)
4865 if (bp[0] == '/')
4867 for (ep = bp+1;
4868 *ep != '\0' && *ep != ' ' && *ep != '{';
4869 ep++)
4870 continue;
4871 make_tag (bp, ep - bp, TRUE,
4872 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4874 else if (LOOKING_AT (bp, "defineps"))
4875 get_tag (bp, NULL);
4881 * Forth tags
4882 * Ignore anything after \ followed by space or in ( )
4883 * Look for words defined by :
4884 * Look for constant, code, create, defer, value, and variable
4885 * OBP extensions: Look for buffer:, field,
4886 * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
4888 static void
4889 Forth_words (FILE *inf)
4891 register char *bp;
4893 LOOP_ON_INPUT_LINES (inf, lb, bp)
4894 while ((bp = skip_spaces (bp))[0] != '\0')
4895 if (bp[0] == '\\' && iswhite(bp[1]))
4896 break; /* read next line */
4897 else if (bp[0] == '(' && iswhite(bp[1]))
4898 do /* skip to ) or eol */
4899 bp++;
4900 while (*bp != ')' && *bp != '\0');
4901 else if ((bp[0] == ':' && iswhite(bp[1]) && bp++)
4902 || LOOKING_AT_NOCASE (bp, "constant")
4903 || LOOKING_AT_NOCASE (bp, "code")
4904 || LOOKING_AT_NOCASE (bp, "create")
4905 || LOOKING_AT_NOCASE (bp, "defer")
4906 || LOOKING_AT_NOCASE (bp, "value")
4907 || LOOKING_AT_NOCASE (bp, "variable")
4908 || LOOKING_AT_NOCASE (bp, "buffer:")
4909 || LOOKING_AT_NOCASE (bp, "field"))
4910 get_tag (skip_spaces (bp), NULL); /* Yay! A definition! */
4911 else
4912 bp = skip_non_spaces (bp);
4917 * Scheme tag functions
4918 * look for (def... xyzzy
4919 * (def... (xyzzy
4920 * (def ... ((...(xyzzy ....
4921 * (set! xyzzy
4922 * Original code by Ken Haase (1985?)
4924 static void
4925 Scheme_functions (FILE *inf)
4927 register char *bp;
4929 LOOP_ON_INPUT_LINES (inf, lb, bp)
4931 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
4933 bp = skip_non_spaces (bp+4);
4934 /* Skip over open parens and white space. Don't continue past
4935 '\0'. */
4936 while (*bp && notinname (*bp))
4937 bp++;
4938 get_tag (bp, NULL);
4940 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
4941 get_tag (bp, NULL);
4946 /* Find tags in TeX and LaTeX input files. */
4948 /* TEX_toktab is a table of TeX control sequences that define tags.
4949 * Each entry records one such control sequence.
4951 * Original code from who knows whom.
4952 * Ideas by:
4953 * Stefan Monnier (2002)
4956 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
4958 /* Default set of control sequences to put into TEX_toktab.
4959 The value of environment var TEXTAGS is prepended to this. */
4960 static const char *TEX_defenv = "\
4961 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
4962 :part:appendix:entry:index:def\
4963 :newcommand:renewcommand:newenvironment:renewenvironment";
4965 static void TEX_mode (FILE *);
4966 static void TEX_decode_env (const char *, const char *);
4968 static char TEX_esc = '\\';
4969 static char TEX_opgrp = '{';
4970 static char TEX_clgrp = '}';
4973 * TeX/LaTeX scanning loop.
4975 static void
4976 TeX_commands (FILE *inf)
4978 char *cp;
4979 linebuffer *key;
4981 /* Select either \ or ! as escape character. */
4982 TEX_mode (inf);
4984 /* Initialize token table once from environment. */
4985 if (TEX_toktab == NULL)
4986 TEX_decode_env ("TEXTAGS", TEX_defenv);
4988 LOOP_ON_INPUT_LINES (inf, lb, cp)
4990 /* Look at each TEX keyword in line. */
4991 for (;;)
4993 /* Look for a TEX escape. */
4994 while (*cp++ != TEX_esc)
4995 if (cp[-1] == '\0' || cp[-1] == '%')
4996 goto tex_next_line;
4998 for (key = TEX_toktab; key->buffer != NULL; key++)
4999 if (strneq (cp, key->buffer, key->len))
5001 register char *p;
5002 int namelen, linelen;
5003 bool opgrp = FALSE;
5005 cp = skip_spaces (cp + key->len);
5006 if (*cp == TEX_opgrp)
5008 opgrp = TRUE;
5009 cp++;
5011 for (p = cp;
5012 (!iswhite (*p) && *p != '#' &&
5013 *p != TEX_opgrp && *p != TEX_clgrp);
5014 p++)
5015 continue;
5016 namelen = p - cp;
5017 linelen = lb.len;
5018 if (!opgrp || *p == TEX_clgrp)
5020 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
5021 p++;
5022 linelen = p - lb.buffer + 1;
5024 make_tag (cp, namelen, TRUE,
5025 lb.buffer, linelen, lineno, linecharno);
5026 goto tex_next_line; /* We only tag a line once */
5029 tex_next_line:
5034 #define TEX_LESC '\\'
5035 #define TEX_SESC '!'
5037 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5038 chars accordingly. */
5039 static void
5040 TEX_mode (FILE *inf)
5042 int c;
5044 while ((c = getc (inf)) != EOF)
5046 /* Skip to next line if we hit the TeX comment char. */
5047 if (c == '%')
5048 while (c != '\n' && c != EOF)
5049 c = getc (inf);
5050 else if (c == TEX_LESC || c == TEX_SESC )
5051 break;
5054 if (c == TEX_LESC)
5056 TEX_esc = TEX_LESC;
5057 TEX_opgrp = '{';
5058 TEX_clgrp = '}';
5060 else
5062 TEX_esc = TEX_SESC;
5063 TEX_opgrp = '<';
5064 TEX_clgrp = '>';
5066 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5067 No attempt is made to correct the situation. */
5068 rewind (inf);
5071 /* Read environment and prepend it to the default string.
5072 Build token table. */
5073 static void
5074 TEX_decode_env (const char *evarname, const char *defenv)
5076 register const char *env, *p;
5077 int i, len;
5079 /* Append default string to environment. */
5080 env = getenv (evarname);
5081 if (!env)
5082 env = defenv;
5083 else
5084 env = concat (env, defenv, "");
5086 /* Allocate a token table */
5087 for (len = 1, p = env; p;)
5088 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5089 len++;
5090 TEX_toktab = xnew (len, linebuffer);
5092 /* Unpack environment string into token table. Be careful about */
5093 /* zero-length strings (leading ':', "::" and trailing ':') */
5094 for (i = 0; *env != '\0';)
5096 p = etags_strchr (env, ':');
5097 if (!p) /* End of environment string. */
5098 p = env + strlen (env);
5099 if (p - env > 0)
5100 { /* Only non-zero strings. */
5101 TEX_toktab[i].buffer = savenstr (env, p - env);
5102 TEX_toktab[i].len = p - env;
5103 i++;
5105 if (*p)
5106 env = p + 1;
5107 else
5109 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5110 TEX_toktab[i].len = 0;
5111 break;
5117 /* Texinfo support. Dave Love, Mar. 2000. */
5118 static void
5119 Texinfo_nodes (FILE *inf)
5121 char *cp, *start;
5122 LOOP_ON_INPUT_LINES (inf, lb, cp)
5123 if (LOOKING_AT (cp, "@node"))
5125 start = cp;
5126 while (*cp != '\0' && *cp != ',')
5127 cp++;
5128 make_tag (start, cp - start, TRUE,
5129 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5135 * HTML support.
5136 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5137 * Contents of <a name=xxx> are tags with name xxx.
5139 * Francesco Potortì, 2002.
5141 static void
5142 HTML_labels (FILE *inf)
5144 bool getnext = FALSE; /* next text outside of HTML tags is a tag */
5145 bool skiptag = FALSE; /* skip to the end of the current HTML tag */
5146 bool intag = FALSE; /* inside an html tag, looking for ID= */
5147 bool inanchor = FALSE; /* when INTAG, is an anchor, look for NAME= */
5148 char *end;
5151 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5153 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5154 for (;;) /* loop on the same line */
5156 if (skiptag) /* skip HTML tag */
5158 while (*dbp != '\0' && *dbp != '>')
5159 dbp++;
5160 if (*dbp == '>')
5162 dbp += 1;
5163 skiptag = FALSE;
5164 continue; /* look on the same line */
5166 break; /* go to next line */
5169 else if (intag) /* look for "name=" or "id=" */
5171 while (*dbp != '\0' && *dbp != '>'
5172 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5173 dbp++;
5174 if (*dbp == '\0')
5175 break; /* go to next line */
5176 if (*dbp == '>')
5178 dbp += 1;
5179 intag = FALSE;
5180 continue; /* look on the same line */
5182 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5183 || LOOKING_AT_NOCASE (dbp, "id="))
5185 bool quoted = (dbp[0] == '"');
5187 if (quoted)
5188 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5189 continue;
5190 else
5191 for (end = dbp; *end != '\0' && intoken (*end); end++)
5192 continue;
5193 linebuffer_setlen (&token_name, end - dbp);
5194 strncpy (token_name.buffer, dbp, end - dbp);
5195 token_name.buffer[end - dbp] = '\0';
5197 dbp = end;
5198 intag = FALSE; /* we found what we looked for */
5199 skiptag = TRUE; /* skip to the end of the tag */
5200 getnext = TRUE; /* then grab the text */
5201 continue; /* look on the same line */
5203 dbp += 1;
5206 else if (getnext) /* grab next tokens and tag them */
5208 dbp = skip_spaces (dbp);
5209 if (*dbp == '\0')
5210 break; /* go to next line */
5211 if (*dbp == '<')
5213 intag = TRUE;
5214 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5215 continue; /* look on the same line */
5218 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5219 continue;
5220 make_tag (token_name.buffer, token_name.len, TRUE,
5221 dbp, end - dbp, lineno, linecharno);
5222 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5223 getnext = FALSE;
5224 break; /* go to next line */
5227 else /* look for an interesting HTML tag */
5229 while (*dbp != '\0' && *dbp != '<')
5230 dbp++;
5231 if (*dbp == '\0')
5232 break; /* go to next line */
5233 intag = TRUE;
5234 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5236 inanchor = TRUE;
5237 continue; /* look on the same line */
5239 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5240 || LOOKING_AT_NOCASE (dbp, "<h1>")
5241 || LOOKING_AT_NOCASE (dbp, "<h2>")
5242 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5244 intag = FALSE;
5245 getnext = TRUE;
5246 continue; /* look on the same line */
5248 dbp += 1;
5255 * Prolog support
5257 * Assumes that the predicate or rule starts at column 0.
5258 * Only the first clause of a predicate or rule is added.
5259 * Original code by Sunichirou Sugou (1989)
5260 * Rewritten by Anders Lindgren (1996)
5262 static int prolog_pr (char *, char *);
5263 static void prolog_skip_comment (linebuffer *, FILE *);
5264 static int prolog_atom (char *, int);
5266 static void
5267 Prolog_functions (FILE *inf)
5269 char *cp, *last;
5270 int len;
5271 int allocated;
5273 allocated = 0;
5274 len = 0;
5275 last = NULL;
5277 LOOP_ON_INPUT_LINES (inf, lb, cp)
5279 if (cp[0] == '\0') /* Empty line */
5280 continue;
5281 else if (iswhite (cp[0])) /* Not a predicate */
5282 continue;
5283 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5284 prolog_skip_comment (&lb, inf);
5285 else if ((len = prolog_pr (cp, last)) > 0)
5287 /* Predicate or rule. Store the function name so that we
5288 only generate a tag for the first clause. */
5289 if (last == NULL)
5290 last = xnew(len + 1, char);
5291 else if (len + 1 > allocated)
5292 xrnew (last, len + 1, char);
5293 allocated = len + 1;
5294 strncpy (last, cp, len);
5295 last[len] = '\0';
5298 free (last);
5302 static void
5303 prolog_skip_comment (linebuffer *plb, FILE *inf)
5305 char *cp;
5309 for (cp = plb->buffer; *cp != '\0'; cp++)
5310 if (cp[0] == '*' && cp[1] == '/')
5311 return;
5312 readline (plb, inf);
5314 while (!feof(inf));
5318 * A predicate or rule definition is added if it matches:
5319 * <beginning of line><Prolog Atom><whitespace>(
5320 * or <beginning of line><Prolog Atom><whitespace>:-
5322 * It is added to the tags database if it doesn't match the
5323 * name of the previous clause header.
5325 * Return the size of the name of the predicate or rule, or 0 if no
5326 * header was found.
5328 static int
5329 prolog_pr (char *s, char *last)
5331 /* Name of last clause. */
5333 int pos;
5334 int len;
5336 pos = prolog_atom (s, 0);
5337 if (pos < 1)
5338 return 0;
5340 len = pos;
5341 pos = skip_spaces (s + pos) - s;
5343 if ((s[pos] == '.'
5344 || (s[pos] == '(' && (pos += 1))
5345 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5346 && (last == NULL /* save only the first clause */
5347 || len != (int)strlen (last)
5348 || !strneq (s, last, len)))
5350 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5351 return len;
5353 else
5354 return 0;
5358 * Consume a Prolog atom.
5359 * Return the number of bytes consumed, or -1 if there was an error.
5361 * A prolog atom, in this context, could be one of:
5362 * - An alphanumeric sequence, starting with a lower case letter.
5363 * - A quoted arbitrary string. Single quotes can escape themselves.
5364 * Backslash quotes everything.
5366 static int
5367 prolog_atom (char *s, int pos)
5369 int origpos;
5371 origpos = pos;
5373 if (ISLOWER(s[pos]) || (s[pos] == '_'))
5375 /* The atom is unquoted. */
5376 pos++;
5377 while (ISALNUM(s[pos]) || (s[pos] == '_'))
5379 pos++;
5381 return pos - origpos;
5383 else if (s[pos] == '\'')
5385 pos++;
5387 for (;;)
5389 if (s[pos] == '\'')
5391 pos++;
5392 if (s[pos] != '\'')
5393 break;
5394 pos++; /* A double quote */
5396 else if (s[pos] == '\0')
5397 /* Multiline quoted atoms are ignored. */
5398 return -1;
5399 else if (s[pos] == '\\')
5401 if (s[pos+1] == '\0')
5402 return -1;
5403 pos += 2;
5405 else
5406 pos++;
5408 return pos - origpos;
5410 else
5411 return -1;
5416 * Support for Erlang
5418 * Generates tags for functions, defines, and records.
5419 * Assumes that Erlang functions start at column 0.
5420 * Original code by Anders Lindgren (1996)
5422 static int erlang_func (char *, char *);
5423 static void erlang_attribute (char *);
5424 static int erlang_atom (char *);
5426 static void
5427 Erlang_functions (FILE *inf)
5429 char *cp, *last;
5430 int len;
5431 int allocated;
5433 allocated = 0;
5434 len = 0;
5435 last = NULL;
5437 LOOP_ON_INPUT_LINES (inf, lb, cp)
5439 if (cp[0] == '\0') /* Empty line */
5440 continue;
5441 else if (iswhite (cp[0])) /* Not function nor attribute */
5442 continue;
5443 else if (cp[0] == '%') /* comment */
5444 continue;
5445 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5446 continue;
5447 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5449 erlang_attribute (cp);
5450 if (last != NULL)
5452 free (last);
5453 last = NULL;
5456 else if ((len = erlang_func (cp, last)) > 0)
5459 * Function. Store the function name so that we only
5460 * generates a tag for the first clause.
5462 if (last == NULL)
5463 last = xnew (len + 1, char);
5464 else if (len + 1 > allocated)
5465 xrnew (last, len + 1, char);
5466 allocated = len + 1;
5467 strncpy (last, cp, len);
5468 last[len] = '\0';
5471 free (last);
5476 * A function definition is added if it matches:
5477 * <beginning of line><Erlang Atom><whitespace>(
5479 * It is added to the tags database if it doesn't match the
5480 * name of the previous clause header.
5482 * Return the size of the name of the function, or 0 if no function
5483 * was found.
5485 static int
5486 erlang_func (char *s, char *last)
5488 /* Name of last clause. */
5490 int pos;
5491 int len;
5493 pos = erlang_atom (s);
5494 if (pos < 1)
5495 return 0;
5497 len = pos;
5498 pos = skip_spaces (s + pos) - s;
5500 /* Save only the first clause. */
5501 if (s[pos++] == '('
5502 && (last == NULL
5503 || len != (int)strlen (last)
5504 || !strneq (s, last, len)))
5506 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5507 return len;
5510 return 0;
5515 * Handle attributes. Currently, tags are generated for defines
5516 * and records.
5518 * They are on the form:
5519 * -define(foo, bar).
5520 * -define(Foo(M, N), M+N).
5521 * -record(graph, {vtab = notable, cyclic = true}).
5523 static void
5524 erlang_attribute (char *s)
5526 char *cp = s;
5528 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5529 && *cp++ == '(')
5531 int len = erlang_atom (skip_spaces (cp));
5532 if (len > 0)
5533 make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5535 return;
5540 * Consume an Erlang atom (or variable).
5541 * Return the number of bytes consumed, or -1 if there was an error.
5543 static int
5544 erlang_atom (char *s)
5546 int pos = 0;
5548 if (ISALPHA (s[pos]) || s[pos] == '_')
5550 /* The atom is unquoted. */
5552 pos++;
5553 while (ISALNUM (s[pos]) || s[pos] == '_');
5555 else if (s[pos] == '\'')
5557 for (pos++; s[pos] != '\''; pos++)
5558 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5559 || (s[pos] == '\\' && s[++pos] == '\0'))
5560 return 0;
5561 pos++;
5564 return pos;
5568 static char *scan_separators (char *);
5569 static void add_regex (char *, language *);
5570 static char *substitute (char *, char *, struct re_registers *);
5573 * Take a string like "/blah/" and turn it into "blah", verifying
5574 * that the first and last characters are the same, and handling
5575 * quoted separator characters. Actually, stops on the occurrence of
5576 * an unquoted separator. Also process \t, \n, etc. and turn into
5577 * appropriate characters. Works in place. Null terminates name string.
5578 * Returns pointer to terminating separator, or NULL for
5579 * unterminated regexps.
5581 static char *
5582 scan_separators (char *name)
5584 char sep = name[0];
5585 char *copyto = name;
5586 bool quoted = FALSE;
5588 for (++name; *name != '\0'; ++name)
5590 if (quoted)
5592 switch (*name)
5594 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
5595 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
5596 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
5597 case 'e': *copyto++ = 033; break; /* ESC (delete) */
5598 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
5599 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
5600 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
5601 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
5602 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
5603 default:
5604 if (*name == sep)
5605 *copyto++ = sep;
5606 else
5608 /* Something else is quoted, so preserve the quote. */
5609 *copyto++ = '\\';
5610 *copyto++ = *name;
5612 break;
5614 quoted = FALSE;
5616 else if (*name == '\\')
5617 quoted = TRUE;
5618 else if (*name == sep)
5619 break;
5620 else
5621 *copyto++ = *name;
5623 if (*name != sep)
5624 name = NULL; /* signal unterminated regexp */
5626 /* Terminate copied string. */
5627 *copyto = '\0';
5628 return name;
5631 /* Look at the argument of --regex or --no-regex and do the right
5632 thing. Same for each line of a regexp file. */
5633 static void
5634 analyse_regex (char *regex_arg)
5636 if (regex_arg == NULL)
5638 free_regexps (); /* --no-regex: remove existing regexps */
5639 return;
5642 /* A real --regexp option or a line in a regexp file. */
5643 switch (regex_arg[0])
5645 /* Comments in regexp file or null arg to --regex. */
5646 case '\0':
5647 case ' ':
5648 case '\t':
5649 break;
5651 /* Read a regex file. This is recursive and may result in a
5652 loop, which will stop when the file descriptors are exhausted. */
5653 case '@':
5655 FILE *regexfp;
5656 linebuffer regexbuf;
5657 char *regexfile = regex_arg + 1;
5659 /* regexfile is a file containing regexps, one per line. */
5660 regexfp = fopen (regexfile, "r");
5661 if (regexfp == NULL)
5663 pfatal (regexfile);
5664 return;
5666 linebuffer_init (&regexbuf);
5667 while (readline_internal (&regexbuf, regexfp) > 0)
5668 analyse_regex (regexbuf.buffer);
5669 free (regexbuf.buffer);
5670 fclose (regexfp);
5672 break;
5674 /* Regexp to be used for a specific language only. */
5675 case '{':
5677 language *lang;
5678 char *lang_name = regex_arg + 1;
5679 char *cp;
5681 for (cp = lang_name; *cp != '}'; cp++)
5682 if (*cp == '\0')
5684 error ("unterminated language name in regex: %s", regex_arg);
5685 return;
5687 *cp++ = '\0';
5688 lang = get_language_from_langname (lang_name);
5689 if (lang == NULL)
5690 return;
5691 add_regex (cp, lang);
5693 break;
5695 /* Regexp to be used for any language. */
5696 default:
5697 add_regex (regex_arg, NULL);
5698 break;
5702 /* Separate the regexp pattern, compile it,
5703 and care for optional name and modifiers. */
5704 static void
5705 add_regex (char *regexp_pattern, language *lang)
5707 static struct re_pattern_buffer zeropattern;
5708 char sep, *pat, *name, *modifiers;
5709 char empty[] = "";
5710 const char *err;
5711 struct re_pattern_buffer *patbuf;
5712 regexp *rp;
5713 bool
5714 force_explicit_name = TRUE, /* do not use implicit tag names */
5715 ignore_case = FALSE, /* case is significant */
5716 multi_line = FALSE, /* matches are done one line at a time */
5717 single_line = FALSE; /* dot does not match newline */
5720 if (strlen(regexp_pattern) < 3)
5722 error ("null regexp", (char *)NULL);
5723 return;
5725 sep = regexp_pattern[0];
5726 name = scan_separators (regexp_pattern);
5727 if (name == NULL)
5729 error ("%s: unterminated regexp", regexp_pattern);
5730 return;
5732 if (name[1] == sep)
5734 error ("null name for regexp \"%s\"", regexp_pattern);
5735 return;
5737 modifiers = scan_separators (name);
5738 if (modifiers == NULL) /* no terminating separator --> no name */
5740 modifiers = name;
5741 name = empty;
5743 else
5744 modifiers += 1; /* skip separator */
5746 /* Parse regex modifiers. */
5747 for (; modifiers[0] != '\0'; modifiers++)
5748 switch (modifiers[0])
5750 case 'N':
5751 if (modifiers == name)
5752 error ("forcing explicit tag name but no name, ignoring", NULL);
5753 force_explicit_name = TRUE;
5754 break;
5755 case 'i':
5756 ignore_case = TRUE;
5757 break;
5758 case 's':
5759 single_line = TRUE;
5760 /* FALLTHRU */
5761 case 'm':
5762 multi_line = TRUE;
5763 need_filebuf = TRUE;
5764 break;
5765 default:
5767 char wrongmod [2];
5768 wrongmod[0] = modifiers[0];
5769 wrongmod[1] = '\0';
5770 error ("invalid regexp modifier `%s', ignoring", wrongmod);
5772 break;
5775 patbuf = xnew (1, struct re_pattern_buffer);
5776 *patbuf = zeropattern;
5777 if (ignore_case)
5779 static char lc_trans[CHARS];
5780 int i;
5781 for (i = 0; i < CHARS; i++)
5782 lc_trans[i] = lowcase (i);
5783 patbuf->translate = lc_trans; /* translation table to fold case */
5786 if (multi_line)
5787 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
5788 else
5789 pat = regexp_pattern;
5791 if (single_line)
5792 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
5793 else
5794 re_set_syntax (RE_SYNTAX_EMACS);
5796 err = re_compile_pattern (pat, strlen (pat), patbuf);
5797 if (multi_line)
5798 free (pat);
5799 if (err != NULL)
5801 error ("%s while compiling pattern", err);
5802 return;
5805 rp = p_head;
5806 p_head = xnew (1, regexp);
5807 p_head->pattern = savestr (regexp_pattern);
5808 p_head->p_next = rp;
5809 p_head->lang = lang;
5810 p_head->pat = patbuf;
5811 p_head->name = savestr (name);
5812 p_head->error_signaled = FALSE;
5813 p_head->force_explicit_name = force_explicit_name;
5814 p_head->ignore_case = ignore_case;
5815 p_head->multi_line = multi_line;
5819 * Do the substitutions indicated by the regular expression and
5820 * arguments.
5822 static char *
5823 substitute (char *in, char *out, struct re_registers *regs)
5825 char *result, *t;
5826 int size, dig, diglen;
5828 result = NULL;
5829 size = strlen (out);
5831 /* Pass 1: figure out how much to allocate by finding all \N strings. */
5832 if (out[size - 1] == '\\')
5833 fatal ("pattern error in \"%s\"", out);
5834 for (t = etags_strchr (out, '\\');
5835 t != NULL;
5836 t = etags_strchr (t + 2, '\\'))
5837 if (ISDIGIT (t[1]))
5839 dig = t[1] - '0';
5840 diglen = regs->end[dig] - regs->start[dig];
5841 size += diglen - 2;
5843 else
5844 size -= 1;
5846 /* Allocate space and do the substitutions. */
5847 assert (size >= 0);
5848 result = xnew (size + 1, char);
5850 for (t = result; *out != '\0'; out++)
5851 if (*out == '\\' && ISDIGIT (*++out))
5853 dig = *out - '0';
5854 diglen = regs->end[dig] - regs->start[dig];
5855 strncpy (t, in + regs->start[dig], diglen);
5856 t += diglen;
5858 else
5859 *t++ = *out;
5860 *t = '\0';
5862 assert (t <= result + size);
5863 assert (t - result == (int)strlen (result));
5865 return result;
5868 /* Deallocate all regexps. */
5869 static void
5870 free_regexps (void)
5872 regexp *rp;
5873 while (p_head != NULL)
5875 rp = p_head->p_next;
5876 free (p_head->pattern);
5877 free (p_head->name);
5878 free (p_head);
5879 p_head = rp;
5881 return;
5885 * Reads the whole file as a single string from `filebuf' and looks for
5886 * multi-line regular expressions, creating tags on matches.
5887 * readline already dealt with normal regexps.
5889 * Idea by Ben Wing <ben@666.com> (2002).
5891 static void
5892 regex_tag_multiline (void)
5894 char *buffer = filebuf.buffer;
5895 regexp *rp;
5896 char *name;
5898 for (rp = p_head; rp != NULL; rp = rp->p_next)
5900 int match = 0;
5902 if (!rp->multi_line)
5903 continue; /* skip normal regexps */
5905 /* Generic initialisations before parsing file from memory. */
5906 lineno = 1; /* reset global line number */
5907 charno = 0; /* reset global char number */
5908 linecharno = 0; /* reset global char number of line start */
5910 /* Only use generic regexps or those for the current language. */
5911 if (rp->lang != NULL && rp->lang != curfdp->lang)
5912 continue;
5914 while (match >= 0 && match < filebuf.len)
5916 match = re_search (rp->pat, buffer, filebuf.len, charno,
5917 filebuf.len - match, &rp->regs);
5918 switch (match)
5920 case -2:
5921 /* Some error. */
5922 if (!rp->error_signaled)
5924 error ("regexp stack overflow while matching \"%s\"",
5925 rp->pattern);
5926 rp->error_signaled = TRUE;
5928 break;
5929 case -1:
5930 /* No match. */
5931 break;
5932 default:
5933 if (match == rp->regs.end[0])
5935 if (!rp->error_signaled)
5937 error ("regexp matches the empty string: \"%s\"",
5938 rp->pattern);
5939 rp->error_signaled = TRUE;
5941 match = -3; /* exit from while loop */
5942 break;
5945 /* Match occurred. Construct a tag. */
5946 while (charno < rp->regs.end[0])
5947 if (buffer[charno++] == '\n')
5948 lineno++, linecharno = charno;
5949 name = rp->name;
5950 if (name[0] == '\0')
5951 name = NULL;
5952 else /* make a named tag */
5953 name = substitute (buffer, rp->name, &rp->regs);
5954 if (rp->force_explicit_name)
5955 /* Force explicit tag name, if a name is there. */
5956 pfnote (name, TRUE, buffer + linecharno,
5957 charno - linecharno + 1, lineno, linecharno);
5958 else
5959 make_tag (name, strlen (name), TRUE, buffer + linecharno,
5960 charno - linecharno + 1, lineno, linecharno);
5961 break;
5968 static bool
5969 nocase_tail (const char *cp)
5971 register int len = 0;
5973 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
5974 cp++, len++;
5975 if (*cp == '\0' && !intoken (dbp[len]))
5977 dbp += len;
5978 return TRUE;
5980 return FALSE;
5983 static void
5984 get_tag (register char *bp, char **namepp)
5986 register char *cp = bp;
5988 if (*bp != '\0')
5990 /* Go till you get to white space or a syntactic break */
5991 for (cp = bp + 1; !notinname (*cp); cp++)
5992 continue;
5993 make_tag (bp, cp - bp, TRUE,
5994 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5997 if (namepp != NULL)
5998 *namepp = savenstr (bp, cp - bp);
6002 * Read a line of text from `stream' into `lbp', excluding the
6003 * newline or CR-NL, if any. Return the number of characters read from
6004 * `stream', which is the length of the line including the newline.
6006 * On DOS or Windows we do not count the CR character, if any before the
6007 * NL, in the returned length; this mirrors the behavior of Emacs on those
6008 * platforms (for text files, it translates CR-NL to NL as it reads in the
6009 * file).
6011 * If multi-line regular expressions are requested, each line read is
6012 * appended to `filebuf'.
6014 static long
6015 readline_internal (linebuffer *lbp, register FILE *stream)
6017 char *buffer = lbp->buffer;
6018 register char *p = lbp->buffer;
6019 register char *pend;
6020 int chars_deleted;
6022 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
6024 for (;;)
6026 register int c = getc (stream);
6027 if (p == pend)
6029 /* We're at the end of linebuffer: expand it. */
6030 lbp->size *= 2;
6031 xrnew (buffer, lbp->size, char);
6032 p += buffer - lbp->buffer;
6033 pend = buffer + lbp->size;
6034 lbp->buffer = buffer;
6036 if (c == EOF)
6038 *p = '\0';
6039 chars_deleted = 0;
6040 break;
6042 if (c == '\n')
6044 if (p > buffer && p[-1] == '\r')
6046 p -= 1;
6047 #ifdef DOS_NT
6048 /* Assume CRLF->LF translation will be performed by Emacs
6049 when loading this file, so CRs won't appear in the buffer.
6050 It would be cleaner to compensate within Emacs;
6051 however, Emacs does not know how many CRs were deleted
6052 before any given point in the file. */
6053 chars_deleted = 1;
6054 #else
6055 chars_deleted = 2;
6056 #endif
6058 else
6060 chars_deleted = 1;
6062 *p = '\0';
6063 break;
6065 *p++ = c;
6067 lbp->len = p - buffer;
6069 if (need_filebuf /* we need filebuf for multi-line regexps */
6070 && chars_deleted > 0) /* not at EOF */
6072 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6074 /* Expand filebuf. */
6075 filebuf.size *= 2;
6076 xrnew (filebuf.buffer, filebuf.size, char);
6078 strncpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6079 filebuf.len += lbp->len;
6080 filebuf.buffer[filebuf.len++] = '\n';
6081 filebuf.buffer[filebuf.len] = '\0';
6084 return lbp->len + chars_deleted;
6088 * Like readline_internal, above, but in addition try to match the
6089 * input line against relevant regular expressions and manage #line
6090 * directives.
6092 static void
6093 readline (linebuffer *lbp, FILE *stream)
6095 long result;
6097 linecharno = charno; /* update global char number of line start */
6098 result = readline_internal (lbp, stream); /* read line */
6099 lineno += 1; /* increment global line number */
6100 charno += result; /* increment global char number */
6102 /* Honour #line directives. */
6103 if (!no_line_directive)
6105 static bool discard_until_line_directive;
6107 /* Check whether this is a #line directive. */
6108 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6110 unsigned int lno;
6111 int start = 0;
6113 if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6114 && start > 0) /* double quote character found */
6116 char *endp = lbp->buffer + start;
6118 while ((endp = etags_strchr (endp, '"')) != NULL
6119 && endp[-1] == '\\')
6120 endp++;
6121 if (endp != NULL)
6122 /* Ok, this is a real #line directive. Let's deal with it. */
6124 char *taggedabsname; /* absolute name of original file */
6125 char *taggedfname; /* name of original file as given */
6126 char *name; /* temp var */
6128 discard_until_line_directive = FALSE; /* found it */
6129 name = lbp->buffer + start;
6130 *endp = '\0';
6131 canonicalize_filename (name);
6132 taggedabsname = absolute_filename (name, tagfiledir);
6133 if (filename_is_absolute (name)
6134 || filename_is_absolute (curfdp->infname))
6135 taggedfname = savestr (taggedabsname);
6136 else
6137 taggedfname = relative_filename (taggedabsname,tagfiledir);
6139 if (streq (curfdp->taggedfname, taggedfname))
6140 /* The #line directive is only a line number change. We
6141 deal with this afterwards. */
6142 free (taggedfname);
6143 else
6144 /* The tags following this #line directive should be
6145 attributed to taggedfname. In order to do this, set
6146 curfdp accordingly. */
6148 fdesc *fdp; /* file description pointer */
6150 /* Go look for a file description already set up for the
6151 file indicated in the #line directive. If there is
6152 one, use it from now until the next #line
6153 directive. */
6154 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6155 if (streq (fdp->infname, curfdp->infname)
6156 && streq (fdp->taggedfname, taggedfname))
6157 /* If we remove the second test above (after the &&)
6158 then all entries pertaining to the same file are
6159 coalesced in the tags file. If we use it, then
6160 entries pertaining to the same file but generated
6161 from different files (via #line directives) will
6162 go into separate sections in the tags file. These
6163 alternatives look equivalent. The first one
6164 destroys some apparently useless information. */
6166 curfdp = fdp;
6167 free (taggedfname);
6168 break;
6170 /* Else, if we already tagged the real file, skip all
6171 input lines until the next #line directive. */
6172 if (fdp == NULL) /* not found */
6173 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6174 if (streq (fdp->infabsname, taggedabsname))
6176 discard_until_line_directive = TRUE;
6177 free (taggedfname);
6178 break;
6180 /* Else create a new file description and use that from
6181 now on, until the next #line directive. */
6182 if (fdp == NULL) /* not found */
6184 fdp = fdhead;
6185 fdhead = xnew (1, fdesc);
6186 *fdhead = *curfdp; /* copy curr. file description */
6187 fdhead->next = fdp;
6188 fdhead->infname = savestr (curfdp->infname);
6189 fdhead->infabsname = savestr (curfdp->infabsname);
6190 fdhead->infabsdir = savestr (curfdp->infabsdir);
6191 fdhead->taggedfname = taggedfname;
6192 fdhead->usecharno = FALSE;
6193 fdhead->prop = NULL;
6194 fdhead->written = FALSE;
6195 curfdp = fdhead;
6198 free (taggedabsname);
6199 lineno = lno - 1;
6200 readline (lbp, stream);
6201 return;
6202 } /* if a real #line directive */
6203 } /* if #line is followed by a number */
6204 } /* if line begins with "#line " */
6206 /* If we are here, no #line directive was found. */
6207 if (discard_until_line_directive)
6209 if (result > 0)
6211 /* Do a tail recursion on ourselves, thus discarding the contents
6212 of the line buffer. */
6213 readline (lbp, stream);
6214 return;
6216 /* End of file. */
6217 discard_until_line_directive = FALSE;
6218 return;
6220 } /* if #line directives should be considered */
6223 int match;
6224 regexp *rp;
6225 char *name;
6227 /* Match against relevant regexps. */
6228 if (lbp->len > 0)
6229 for (rp = p_head; rp != NULL; rp = rp->p_next)
6231 /* Only use generic regexps or those for the current language.
6232 Also do not use multiline regexps, which is the job of
6233 regex_tag_multiline. */
6234 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6235 || rp->multi_line)
6236 continue;
6238 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6239 switch (match)
6241 case -2:
6242 /* Some error. */
6243 if (!rp->error_signaled)
6245 error ("regexp stack overflow while matching \"%s\"",
6246 rp->pattern);
6247 rp->error_signaled = TRUE;
6249 break;
6250 case -1:
6251 /* No match. */
6252 break;
6253 case 0:
6254 /* Empty string matched. */
6255 if (!rp->error_signaled)
6257 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6258 rp->error_signaled = TRUE;
6260 break;
6261 default:
6262 /* Match occurred. Construct a tag. */
6263 name = rp->name;
6264 if (name[0] == '\0')
6265 name = NULL;
6266 else /* make a named tag */
6267 name = substitute (lbp->buffer, rp->name, &rp->regs);
6268 if (rp->force_explicit_name)
6269 /* Force explicit tag name, if a name is there. */
6270 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6271 else
6272 make_tag (name, strlen (name), TRUE,
6273 lbp->buffer, match, lineno, linecharno);
6274 break;
6282 * Return a pointer to a space of size strlen(cp)+1 allocated
6283 * with xnew where the string CP has been copied.
6285 static char *
6286 savestr (const char *cp)
6288 return savenstr (cp, strlen (cp));
6292 * Return a pointer to a space of size LEN+1 allocated with xnew where
6293 * the string CP has been copied for at most the first LEN characters.
6295 static char *
6296 savenstr (const char *cp, int len)
6298 register char *dp;
6300 dp = xnew (len + 1, char);
6301 strncpy (dp, cp, len);
6302 dp[len] = '\0';
6303 return dp;
6307 * Return the ptr in sp at which the character c last
6308 * appears; NULL if not found
6310 * Identical to POSIX strrchr, included for portability.
6312 static char *
6313 etags_strrchr (register const char *sp, register int c)
6315 register const char *r;
6317 r = NULL;
6320 if (*sp == c)
6321 r = sp;
6322 } while (*sp++);
6323 return (char *)r;
6327 * Return the ptr in sp at which the character c first
6328 * appears; NULL if not found
6330 * Identical to POSIX strchr, included for portability.
6332 static char *
6333 etags_strchr (register const char *sp, register int c)
6337 if (*sp == c)
6338 return (char *)sp;
6339 } while (*sp++);
6340 return NULL;
6344 * Compare two strings, ignoring case for alphabetic characters.
6346 * Same as BSD's strcasecmp, included for portability.
6348 static int
6349 etags_strcasecmp (register const char *s1, register const char *s2)
6351 while (*s1 != '\0'
6352 && (ISALPHA (*s1) && ISALPHA (*s2)
6353 ? lowcase (*s1) == lowcase (*s2)
6354 : *s1 == *s2))
6355 s1++, s2++;
6357 return (ISALPHA (*s1) && ISALPHA (*s2)
6358 ? lowcase (*s1) - lowcase (*s2)
6359 : *s1 - *s2);
6363 * Compare two strings, ignoring case for alphabetic characters.
6364 * Stop after a given number of characters
6366 * Same as BSD's strncasecmp, included for portability.
6368 static int
6369 etags_strncasecmp (register const char *s1, register const char *s2, register int n)
6371 while (*s1 != '\0' && n-- > 0
6372 && (ISALPHA (*s1) && ISALPHA (*s2)
6373 ? lowcase (*s1) == lowcase (*s2)
6374 : *s1 == *s2))
6375 s1++, s2++;
6377 if (n < 0)
6378 return 0;
6379 else
6380 return (ISALPHA (*s1) && ISALPHA (*s2)
6381 ? lowcase (*s1) - lowcase (*s2)
6382 : *s1 - *s2);
6385 /* Skip spaces (end of string is not space), return new pointer. */
6386 static char *
6387 skip_spaces (char *cp)
6389 while (iswhite (*cp))
6390 cp++;
6391 return cp;
6394 /* Skip non spaces, except end of string, return new pointer. */
6395 static char *
6396 skip_non_spaces (char *cp)
6398 while (*cp != '\0' && !iswhite (*cp))
6399 cp++;
6400 return cp;
6403 /* Print error message and exit. */
6404 void
6405 fatal (const char *s1, const char *s2)
6407 error (s1, s2);
6408 exit (EXIT_FAILURE);
6411 static void
6412 pfatal (const char *s1)
6414 perror (s1);
6415 exit (EXIT_FAILURE);
6418 static void
6419 suggest_asking_for_help (void)
6421 fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6422 progname, NO_LONG_OPTIONS ? "-h" : "--help");
6423 exit (EXIT_FAILURE);
6426 /* Print error message. `s1' is printf control string, `s2' is arg for it. */
6427 static void
6428 error (const char *s1, const char *s2)
6430 fprintf (stderr, "%s: ", progname);
6431 fprintf (stderr, s1, s2);
6432 fprintf (stderr, "\n");
6435 /* Return a newly-allocated string whose contents
6436 concatenate those of s1, s2, s3. */
6437 static char *
6438 concat (const char *s1, const char *s2, const char *s3)
6440 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6441 char *result = xnew (len1 + len2 + len3 + 1, char);
6443 strcpy (result, s1);
6444 strcpy (result + len1, s2);
6445 strcpy (result + len1 + len2, s3);
6446 result[len1 + len2 + len3] = '\0';
6448 return result;
6452 /* Does the same work as the system V getcwd, but does not need to
6453 guess the buffer size in advance. */
6454 static char *
6455 etags_getcwd (void)
6457 #ifdef HAVE_GETCWD
6458 int bufsize = 200;
6459 char *path = xnew (bufsize, char);
6461 while (getcwd (path, bufsize) == NULL)
6463 if (errno != ERANGE)
6464 pfatal ("getcwd");
6465 bufsize *= 2;
6466 free (path);
6467 path = xnew (bufsize, char);
6470 canonicalize_filename (path);
6471 return path;
6473 #else /* not HAVE_GETCWD */
6474 #if MSDOS
6476 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
6478 getwd (path);
6480 for (p = path; *p != '\0'; p++)
6481 if (*p == '\\')
6482 *p = '/';
6483 else
6484 *p = lowcase (*p);
6486 return strdup (path);
6487 #else /* not MSDOS */
6488 linebuffer path;
6489 FILE *pipe;
6491 linebuffer_init (&path);
6492 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6493 if (pipe == NULL || readline_internal (&path, pipe) == 0)
6494 pfatal ("pwd");
6495 pclose (pipe);
6497 return path.buffer;
6498 #endif /* not MSDOS */
6499 #endif /* not HAVE_GETCWD */
6502 /* Return a newly allocated string containing the file name of FILE
6503 relative to the absolute directory DIR (which should end with a slash). */
6504 static char *
6505 relative_filename (char *file, char *dir)
6507 char *fp, *dp, *afn, *res;
6508 int i;
6510 /* Find the common root of file and dir (with a trailing slash). */
6511 afn = absolute_filename (file, cwd);
6512 fp = afn;
6513 dp = dir;
6514 while (*fp++ == *dp++)
6515 continue;
6516 fp--, dp--; /* back to the first differing char */
6517 #ifdef DOS_NT
6518 if (fp == afn && afn[0] != '/') /* cannot build a relative name */
6519 return afn;
6520 #endif
6521 do /* look at the equal chars until '/' */
6522 fp--, dp--;
6523 while (*fp != '/');
6525 /* Build a sequence of "../" strings for the resulting relative file name. */
6526 i = 0;
6527 while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6528 i += 1;
6529 res = xnew (3*i + strlen (fp + 1) + 1, char);
6530 res[0] = '\0';
6531 while (i-- > 0)
6532 strcat (res, "../");
6534 /* Add the file name relative to the common root of file and dir. */
6535 strcat (res, fp + 1);
6536 free (afn);
6538 return res;
6541 /* Return a newly allocated string containing the absolute file name
6542 of FILE given DIR (which should end with a slash). */
6543 static char *
6544 absolute_filename (char *file, char *dir)
6546 char *slashp, *cp, *res;
6548 if (filename_is_absolute (file))
6549 res = savestr (file);
6550 #ifdef DOS_NT
6551 /* We don't support non-absolute file names with a drive
6552 letter, like `d:NAME' (it's too much hassle). */
6553 else if (file[1] == ':')
6554 fatal ("%s: relative file names with drive letters not supported", file);
6555 #endif
6556 else
6557 res = concat (dir, file, "");
6559 /* Delete the "/dirname/.." and "/." substrings. */
6560 slashp = etags_strchr (res, '/');
6561 while (slashp != NULL && slashp[0] != '\0')
6563 if (slashp[1] == '.')
6565 if (slashp[2] == '.'
6566 && (slashp[3] == '/' || slashp[3] == '\0'))
6568 cp = slashp;
6570 cp--;
6571 while (cp >= res && !filename_is_absolute (cp));
6572 if (cp < res)
6573 cp = slashp; /* the absolute name begins with "/.." */
6574 #ifdef DOS_NT
6575 /* Under MSDOS and NT we get `d:/NAME' as absolute
6576 file name, so the luser could say `d:/../NAME'.
6577 We silently treat this as `d:/NAME'. */
6578 else if (cp[0] != '/')
6579 cp = slashp;
6580 #endif
6581 #ifdef HAVE_MEMMOVE
6582 memmove (cp, slashp + 3, strlen (slashp + 2));
6583 #else
6584 /* Overlapping copy isn't really okay */
6585 strcpy (cp, slashp + 3);
6586 #endif
6587 slashp = cp;
6588 continue;
6590 else if (slashp[2] == '/' || slashp[2] == '\0')
6592 #ifdef HAVE_MEMMOVE
6593 memmove (slashp, slashp + 2, strlen (slashp + 1));
6594 #else
6595 strcpy (slashp, slashp + 2);
6596 #endif
6597 continue;
6601 slashp = etags_strchr (slashp + 1, '/');
6604 if (res[0] == '\0') /* just a safety net: should never happen */
6606 free (res);
6607 return savestr ("/");
6609 else
6610 return res;
6613 /* Return a newly allocated string containing the absolute
6614 file name of dir where FILE resides given DIR (which should
6615 end with a slash). */
6616 static char *
6617 absolute_dirname (char *file, char *dir)
6619 char *slashp, *res;
6620 char save;
6622 slashp = etags_strrchr (file, '/');
6623 if (slashp == NULL)
6624 return savestr (dir);
6625 save = slashp[1];
6626 slashp[1] = '\0';
6627 res = absolute_filename (file, dir);
6628 slashp[1] = save;
6630 return res;
6633 /* Whether the argument string is an absolute file name. The argument
6634 string must have been canonicalized with canonicalize_filename. */
6635 static bool
6636 filename_is_absolute (char *fn)
6638 return (fn[0] == '/'
6639 #ifdef DOS_NT
6640 || (ISALPHA(fn[0]) && fn[1] == ':' && fn[2] == '/')
6641 #endif
6645 /* Upcase DOS drive letter and collapse separators into single slashes.
6646 Works in place. */
6647 static void
6648 canonicalize_filename (register char *fn)
6650 register char* cp;
6651 char sep = '/';
6653 #ifdef DOS_NT
6654 /* Canonicalize drive letter case. */
6655 if (fn[0] != '\0' && fn[1] == ':' && ISLOWER (fn[0]))
6656 fn[0] = upcase (fn[0]);
6658 sep = '\\';
6659 #endif
6661 /* Collapse multiple separators into a single slash. */
6662 for (cp = fn; *cp != '\0'; cp++, fn++)
6663 if (*cp == sep)
6665 *fn = '/';
6666 while (cp[1] == sep)
6667 cp++;
6669 else
6670 *fn = *cp;
6671 *fn = '\0';
6675 /* Initialize a linebuffer for use. */
6676 static void
6677 linebuffer_init (linebuffer *lbp)
6679 lbp->size = (DEBUG) ? 3 : 200;
6680 lbp->buffer = xnew (lbp->size, char);
6681 lbp->buffer[0] = '\0';
6682 lbp->len = 0;
6685 /* Set the minimum size of a string contained in a linebuffer. */
6686 static void
6687 linebuffer_setlen (linebuffer *lbp, int toksize)
6689 while (lbp->size <= toksize)
6691 lbp->size *= 2;
6692 xrnew (lbp->buffer, lbp->size, char);
6694 lbp->len = toksize;
6697 /* Like malloc but get fatal error if memory is exhausted. */
6698 static PTR
6699 xmalloc (unsigned int size)
6701 PTR result = (PTR) malloc (size);
6702 if (result == NULL)
6703 fatal ("virtual memory exhausted", (char *)NULL);
6704 return result;
6707 static PTR
6708 xrealloc (char *ptr, unsigned int size)
6710 PTR result = (PTR) realloc (ptr, size);
6711 if (result == NULL)
6712 fatal ("virtual memory exhausted", (char *)NULL);
6713 return result;
6717 * Local Variables:
6718 * indent-tabs-mode: t
6719 * tab-width: 8
6720 * fill-column: 79
6721 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
6722 * c-file-style: "gnu"
6723 * End:
6726 /* etags.c ends here */