Coverity: CID 610-DEAD CODE 611-UNUSED VALUE
[sxemacs] / lib-src / etags.c
1 /* Tags file maker to go with GNU Emacs           -*- coding: latin-1 -*-
2
3 Copyright (C) 1984 The Regents of the University of California
4
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.
17
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.
29
30
31 Copyright (C) 1984, 1987, 1988, 1989, 1993, 1994, 1995, 1998, 1999,
32   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
33   Free Software Foundation, Inc.
34
35 This file is not considered part of GNU Emacs.
36
37 This program is free software: you can redistribute it and/or modify
38 it under the terms of the GNU General Public License as published by
39 the Free Software Foundation, either version 3 of the License, or
40 (at your option) any later version.
41
42 This program is distributed in the hope that it will be useful,
43 but WITHOUT ANY WARRANTY; without even the implied warranty of
44 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45 GNU General Public License for more details.
46
47 You should have received a copy of the GNU General Public License
48 along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
49
50
51 /* NB To comply with the above BSD license, copyright information is
52 reproduced in etc/ETAGS.README.  That file should be updated when the
53 above notices are.
54
55 To the best of our knowledge, this code was originally based on the
56 ctags.c distributed with BSD4.2, which was copyrighted by the
57 University of California, as described above. */
58
59
60 /*
61  * Authors:
62  * 1983 Ctags originally by Ken Arnold.
63  * 1984 Fortran added by Jim Kleckner.
64  * 1984 Ed Pelegri-Llopart added C typedefs.
65  * 1985 Emacs TAGS format by Richard Stallman.
66  * 1989 Sam Kendall added C++.
67  * 1992 Joseph B. Wells improved C and C++ parsing.
68  * 1993 Francesco Potortì reorganized C and C++.
69  * 1994 Line-by-line regexp tags by Tom Tromey.
70  * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba).
71  * 2002 #line directives by Francesco Potortì.
72  *
73  * Francesco Potortì <pot@gnu.org> has maintained and improved it since 1993.
74  */
75
76 /*
77  * If you want to add support for a new language, start by looking at the LUA
78  * language, which is the simplest.  Alternatively, consider distributing etags
79  * together with a configuration file containing regexp definitions for etags.
80  */
81
82 char pot_etags_version[] = "@(#) pot revision number is 17.38.1.4";
83
84 #define TRUE    1
85 #define FALSE   0
86
87 #ifdef DEBUG
88 #  undef DEBUG
89 #  define DEBUG TRUE
90 #else
91 #  define DEBUG  FALSE
92 #  define NDEBUG                /* disable assert */
93 #endif
94
95 #ifdef HAVE_CONFIG_H
96 # include "config.h"
97 /* On some systems, Emacs defines static as nothing for the sake
98    of unexec.  We don't want that here since we don't use unexec. */
99 # undef static
100 # ifndef PTR                    /* for XEmacs */
101 #   define PTR void *
102 # endif
103 # ifndef __P                    /* for XEmacs */
104 #   define __P(args) args
105 # endif
106 #else  /* no config.h */
107 # if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
108 #   define __P(args) args       /* use prototypes */
109 #   define PTR void *           /* for generic pointers */
110 # else /* not standard C */
111 #   define __P(args) ()         /* no prototypes */
112 #   define const                /* remove const for old compilers' sake */
113 #   define PTR long *           /* don't use void* */
114 # endif
115 #endif /* !HAVE_CONFIG_H */
116
117 #ifndef _GNU_SOURCE
118 # define _GNU_SOURCE 1          /* enables some compiler checks on GNU */
119 #endif
120
121 #define MSDOS FALSE
122
123 #ifdef STDC_HEADERS
124 # include <stdlib.h>
125 # include <string.h>
126 #else /* no standard C headers */
127 extern char *getenv __P((const char *));
128 extern char *strcpy __P((char *, const char *));
129 extern char *strncpy __P((char *, const char *, unsigned long));
130 extern char *strcat __P((char *, const char *));
131 extern char *strncat __P((char *, const char *, unsigned long));
132 extern int strcmp __P((const char *, const char *));
133 extern int strncmp __P((const char *, const char *, unsigned long));
134 extern int system __P((const char *));
135 extern unsigned long strlen __P((const char *));
136 extern void *malloc __P((unsigned long));
137 extern void *realloc __P((void *, unsigned long));
138 extern void exit __P((int));
139 extern void free __P((void *));
140 extern void *memmove __P((void *, const void *, unsigned long));
141 # define EXIT_SUCCESS   0
142 # define EXIT_FAILURE   1
143 #endif  /* STDC_HEADERS */
144
145 #ifdef HAVE_UNISTD_H
146 # include <unistd.h>
147 #else
148 # ifdef HAVE_GETCWD
149 extern char *getcwd (char *buf, size_t size);
150 # endif
151 #endif /* HAVE_UNISTD_H */
152
153 #include <stdio.h>
154 #include <ctype.h>
155 #include <errno.h>
156 #ifndef errno
157 extern int errno;
158 #endif
159 #include <sys/types.h>
160 #include <sys/stat.h>
161
162 #include <assert.h>
163 #ifdef NDEBUG
164 # undef  assert                 /* some systems have a buggy assert.h */
165 # define assert(x) ((void) 0)
166 #endif
167
168 #if !defined (S_ISREG) && defined (S_IFREG)
169 # define S_ISREG(m)     (((m) & S_IFMT) == S_IFREG)
170 #endif
171
172 #ifndef HAVE_GETOPT_LONG
173 # define NO_LONG_OPTIONS TRUE
174 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
175 extern char *optarg;
176 extern int optind, opterr;
177 #else
178 # define NO_LONG_OPTIONS FALSE
179 # include <getopt.h>
180 #endif /* HAVE_GETOPT_LONG */
181
182 #include <regex.h>
183
184 /* Define CTAGS to make the program "ctags" compatible with the usual one.
185    Leave it undefined to make the program "etags", which makes emacs-style
186    tag tables and tags typedefs, #defines and struct/union/enum by default. */
187 #ifdef CTAGS
188 # undef  CTAGS
189 # define CTAGS TRUE
190 #else
191 # define CTAGS FALSE
192 #endif
193
194 #define streq(s,t)      (assert((s)!=NULL || (t)!=NULL), !strcmp (s, t))
195 #define strcaseeq(s,t)  (assert((s)!=NULL && (t)!=NULL), !etags_strcasecmp (s, t))
196 #define strneq(s,t,n)   (assert((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
197 #define strncaseeq(s,t,n) (assert((s)!=NULL && (t)!=NULL), !etags_strncasecmp (s, t, n))
198
199 #define CHARS 256               /* 2^sizeof(char) */
200 #define CHAR(x)         ((unsigned int)(x) & (CHARS - 1))
201 #define iswhite(c)      (_wht[CHAR(c)]) /* c is white (see white) */
202 #define notinname(c)    (_nin[CHAR(c)]) /* c is not in a name (see nonam) */
203 #define begtoken(c)     (_btk[CHAR(c)]) /* c can start token (see begtk) */
204 #define intoken(c)      (_itk[CHAR(c)]) /* c can be in token (see midtk) */
205 #define endtoken(c)     (_etk[CHAR(c)]) /* c ends tokens (see endtk) */
206
207 #define ISALNUM(c)      isalnum (CHAR(c))
208 #define ISALPHA(c)      isalpha (CHAR(c))
209 #define ISDIGIT(c)      isdigit (CHAR(c))
210 #define ISLOWER(c)      islower (CHAR(c))
211
212 #define lowcase(c)      tolower (CHAR(c))
213 #define upcase(c)       toupper (CHAR(c))
214
215
216 /*
217  *      xnew, xrnew -- allocate, reallocate storage
218  *
219  * SYNOPSIS:    Type *xnew (int n, Type);
220  *              void xrnew (OldPointer, int n, Type);
221  */
222 #if DEBUG
223 # include "chkmalloc.h"
224 # define xnew(n,Type)     ((Type *) trace_malloc (__FILE__, __LINE__,   \
225                                                   (n) * sizeof (Type)))
226 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
227                                                           (char *) (op), (n) * sizeof (Type)))
228 #else
229 # define xnew(n,Type)     ((Type *) xmalloc ((n) * sizeof (Type)))
230 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc (                   \
231                                    (char *) (op), (n) * sizeof (Type)))
232 #endif
233
234 #define bool int
235
236 typedef void Lang_function __P((FILE *));
237
238 typedef struct
239 {
240         char *suffix;                   /* file name suffix for this compressor */
241         char *command;          /* takes one arg and decompresses to stdout */
242 } compressor;
243
244 typedef struct
245 {
246         char *name;                     /* language name */
247         char *help;                   /* detailed help for the language */
248         Lang_function *function;        /* parse function */
249         char **suffixes;                /* name suffixes of this language's files */
250         char **filenames;               /* names of this language's files */
251         char **interpreters;            /* interpreters for this language */
252         bool metasource;                /* source used to generate other sources */
253 } language;
254
255 typedef struct fdesc
256 {
257         struct fdesc *next;             /* for the linked list */
258         char *infname;          /* uncompressed input file name */
259         char *infabsname;               /* absolute uncompressed input file name */
260         char *infabsdir;                /* absolute dir of input file */
261         char *taggedfname;              /* file name to write in tagfile */
262         language *lang;         /* language of file */
263         char *prop;                     /* file properties to write in tagfile */
264         bool usecharno;         /* etags tags shall contain char number */
265         bool written;                   /* entry written in the tags file */
266 } fdesc;
267
268 typedef struct node_st
269 {                               /* sorting structure */
270         struct node_st *left, *right;   /* left and right sons */
271         fdesc *fdp;                     /* description of file to whom tag belongs */
272         char *name;                     /* tag name */
273         char *regex;                    /* search regexp */
274         bool valid;                     /* write this tag on the tag file */
275         bool is_func;                   /* function tag: use regexp in CTAGS mode */
276         bool been_warned;               /* warning already given for duplicated tag */
277         int lno;                        /* line number tag is on */
278         long cno;                       /* character number line starts on */
279 } node;
280
281 /*
282  * A `linebuffer' is a structure which holds a line of text.
283  * `readline_internal' reads a line from a stream into a linebuffer
284  * and works regardless of the length of the line.
285  * SIZE is the size of BUFFER, LEN is the length of the string in
286  * BUFFER after readline reads it.
287  */
288 typedef struct
289 {
290         long size;
291         int len;
292         char *buffer;
293 } linebuffer;
294
295 /* Used to support mixing of --lang and file names. */
296 typedef struct
297 {
298         enum {
299                 at_language,            /* a language specification */
300                 at_regexp,                      /* a regular expression */
301                 at_filename,            /* a file name */
302                 at_stdin,                       /* read from stdin here */
303                 at_end                  /* stop parsing the list */
304         } arg_type;                     /* argument type */
305         language *lang;         /* language associated with the argument */
306         char *what;                     /* the argument itself */
307 } argument;
308
309 /* Structure defining a regular expression. */
310 typedef struct regexp
311 {
312         struct regexp *p_next;  /* pointer to next in list */
313         language *lang;         /* if set, use only for this language */
314         char *pattern;          /* the regexp pattern */
315         char *name;                     /* tag name */
316         struct re_pattern_buffer *pat; /* the compiled pattern */
317         struct re_registers regs;       /* re registers */
318         bool error_signaled;            /* already signaled for this regexp */
319         bool force_explicit_name;       /* do not allow implict tag name */
320         bool ignore_case;               /* ignore case when matching */
321         bool multi_line;                /* do a multi-line match on the whole file */
322 } regexp;
323
324
325 /* Many compilers barf on this:
326    Lang_function Ada_funcs;
327    so let's write it this way */
328 static void Ada_funcs __P((FILE *));
329 static void Asm_labels __P((FILE *));
330 static void C_entries __P((int c_ext, FILE *));
331 static void default_C_entries __P((FILE *));
332 static void plain_C_entries __P((FILE *));
333 static void Cjava_entries __P((FILE *));
334 static void Cobol_paragraphs __P((FILE *));
335 static void Cplusplus_entries __P((FILE *));
336 static void Cstar_entries __P((FILE *));
337 static void Erlang_functions __P((FILE *));
338 static void Forth_words __P((FILE *));
339 static void Fortran_functions __P((FILE *));
340 static void HTML_labels __P((FILE *));
341 static void Lisp_functions __P((FILE *));
342 static void Lua_functions __P((FILE *));
343 static void Makefile_targets __P((FILE *));
344 static void Pascal_functions __P((FILE *));
345 static void Perl_functions __P((FILE *));
346 static void PHP_functions __P((FILE *));
347 static void PS_functions __P((FILE *));
348 static void Prolog_functions __P((FILE *));
349 static void Python_functions __P((FILE *));
350 static void Scheme_functions __P((FILE *));
351 static void TeX_commands __P((FILE *));
352 static void Texinfo_nodes __P((FILE *));
353 static void Yacc_entries __P((FILE *));
354 static void just_read_file __P((FILE *));
355
356 static void print_language_names __P((void));
357 static void print_version __P((void));
358 static void print_help __P((argument *));
359 int main __P((int, char **));
360
361 static compressor *get_compressor_from_suffix __P((char *, char **));
362 static language *get_language_from_langname __P((const char *));
363 static language *get_language_from_interpreter __P((char *));
364 static language *get_language_from_filename __P((char *, bool));
365 static void readline __P((linebuffer *, FILE *));
366 static long readline_internal __P((linebuffer *, FILE *));
367 static bool nocase_tail __P((char *));
368 static void get_tag __P((char *, char **));
369
370 static void analyse_regex __P((char *));
371 static void free_regexps __P((void));
372 static void regex_tag_multiline __P((void));
373 static void error __P((const char *, const char *));
374 static void suggest_asking_for_help __P((void));
375 void fatal __P((char *, char *));
376 static void pfatal __P((char *));
377 static void add_node __P((node *, node **));
378
379 static void init __P((void));
380 static void process_file_name __P((char *, language *));
381 static void process_file __P((FILE *, char *, language *));
382 static void find_entries __P((FILE *));
383 static void free_tree __P((node *));
384 static void free_fdesc __P((fdesc *));
385 static void pfnote __P((char *, bool, char *, int, int, long));
386 static void make_tag __P((char *, int, bool, char *, int, int, long));
387 static void invalidate_nodes __P((fdesc *, node **));
388 static void put_entries __P((node *));
389
390 static char *concat __P((char *, char *, char *));
391 static char *skip_spaces __P((char *));
392 static char *skip_non_spaces __P((char *));
393 static char *savenstr __P((char *, int));
394 static char *savestr __P((char *));
395 static char *etags_strchr __P((const char *, int));
396 static char *etags_strrchr __P((const char *, int));
397 static int etags_strcasecmp __P((const char *, const char *));
398 static int etags_strncasecmp __P((const char *, const char *, int));
399 static char *etags_getcwd __P((void));
400 static char *relative_filename __P((char *, char *));
401 static char *absolute_filename __P((char *, char *));
402 static char *absolute_dirname __P((char *, char *));
403 static bool filename_is_absolute __P((char *f));
404 static void canonicalize_filename __P((char *));
405 static void linebuffer_init __P((linebuffer *));
406 static void linebuffer_setlen __P((linebuffer *, int));
407 static PTR xmalloc __P((unsigned int));
408 static PTR xrealloc __P((char *, unsigned int));
409
410 \f
411 static char searchar = '/';     /* use /.../ searches */
412
413 static char *tagfile;           /* output file */
414 static char *progname;          /* name this program was invoked with */
415 static char *cwd;               /* current working directory */
416 static char *tagfiledir;        /* directory of tagfile */
417 static FILE *tagf;              /* ioptr for tags file */
418
419 static fdesc *fdhead;           /* head of file description list */
420 static fdesc *curfdp;           /* current file description */
421 static int lineno;              /* line number of current line */
422 static long charno;             /* current character number */
423 static long linecharno;         /* charno of start of current line */
424 static char *dbp;               /* pointer to start of current tag */
425
426 static const int invalidcharno = -1;
427
428 static node *nodehead;          /* the head of the binary tree of tags */
429 static node *last_node;         /* the last node created */
430
431 static linebuffer lb;           /* the current line */
432 static linebuffer filebuf;      /* a buffer containing the whole file */
433 static linebuffer token_name;   /* a buffer containing a tag name */
434
435 /* boolean "functions" (see init)       */
436 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
437 static char
438 /* white chars */
439 *white = " \f\t\n\r\v",
440 /* not in a name */
441         *nonam = " \f\t\n\r()=,;",      /* look at make_tag before modifying! */
442 /* token ending chars */
443         *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
444 /* token starting chars */
445         *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
446 /* valid in-token chars */
447         *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
448
449 static bool append_to_tagfile;  /* -a: append to tags */
450 /* The next five default to TRUE in C and derived languages.  */
451 static bool typedefs;           /* -t: create tags for C and Ada typedefs */
452 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
453 /* 0 struct/enum/union decls, and C++ */
454 /* member functions. */
455 static bool constantypedefs;    /* -d: create tags for C #define, enum */
456                                 /* constants and variables. */
457                                 /* -D: opposite of -d.  Default under ctags. */
458 static bool globals;            /* create tags for global variables */
459 static bool members;            /* create tags for C member variables */
460 static bool declarations;       /* --declarations: tag them and extern in C&Co*/
461 static bool no_line_directive;  /* ignore #line directives (undocumented) */
462 static bool no_duplicates;      /* no duplicate tags for ctags (undocumented) */
463 static bool update;             /* -u: update tags */
464 static bool vgrind_style;       /* -v: create vgrind style index output */
465 static bool no_warnings;        /* -w: suppress warnings (undocumented) */
466 static bool cxref_style;        /* -x: create cxref style output */
467 static bool cplusplus;          /* .[hc] means C++, not C (undocumented) */
468 static bool ignoreindent;       /* -I: ignore indentation in C */
469 static bool packages_only;      /* --packages-only: in Ada, only tag packages*/
470
471 /* STDIN is defined in LynxOS system headers */
472 #ifdef STDIN
473 # undef STDIN
474 #endif
475
476 #define STDIN 0x1001            /* returned by getopt_long on --parse-stdin */
477 static bool parsing_stdin;      /* --parse-stdin used */
478
479 static regexp *p_head;          /* list of all regexps */
480 static bool need_filebuf;       /* some regexes are multi-line */
481
482 #if NO_LONG_OPTIONS == FALSE
483 static struct option longopts[] =
484 {
485         { "append",             no_argument,       NULL,               'a'   },
486         { "packages-only",      no_argument,       &packages_only,     TRUE  },
487         { "c++",                no_argument,       NULL,               'C'   },
488         { "declarations",       no_argument,       &declarations,      TRUE  },
489         { "no-line-directive",  no_argument,       &no_line_directive, TRUE  },
490         { "no-duplicates",      no_argument,       &no_duplicates,     TRUE  },
491         { "help",               no_argument,       NULL,               'h'   },
492         { "help",               no_argument,       NULL,               'H'   },
493         { "ignore-indentation", no_argument,       NULL,               'I'   },
494         { "language",           required_argument, NULL,               'l'   },
495         { "members",            no_argument,       &members,           TRUE  },
496         { "no-members",         no_argument,       &members,           FALSE },
497         { "output",             required_argument, NULL,               'o'   },
498         { "regex",              required_argument, NULL,               'r'   },
499         { "no-regex",           no_argument,       NULL,               'R'   },
500         { "ignore-case-regex",  required_argument, NULL,               'c'   },
501         { "parse-stdin",        required_argument, NULL,               STDIN },
502         { "version",            no_argument,       NULL,               'V'   },
503
504 #if CTAGS /* Ctags options */
505         { "backward-search",    no_argument,       NULL,               'B'   },
506         { "cxref",              no_argument,       NULL,               'x'   },
507         { "defines",            no_argument,       NULL,               'd'   },
508         { "globals",            no_argument,       &globals,           TRUE  },
509         { "typedefs",           no_argument,       NULL,               't'   },
510         { "typedefs-and-c++",   no_argument,       NULL,               'T'   },
511         { "update",             no_argument,       NULL,               'u'   },
512         { "vgrind",             no_argument,       NULL,               'v'   },
513         { "no-warn",            no_argument,       NULL,               'w'   },
514
515 #else /* Etags options */
516         { "no-defines",         no_argument,       NULL,               'D'   },
517         { "no-globals",         no_argument,       &globals,           FALSE },
518         { "include",            required_argument, NULL,               'i'   },
519 #endif
520         { NULL }
521 };
522 #endif
523
524
525 static compressor compressors[] =
526 {
527         { "z", "gzip -d -c"},
528         { "Z", "gzip -d -c"},
529         { "gz", "gzip -d -c"},
530         { "GZ", "gzip -d -c"},
531         { "bz2", "bzip2 -d -c" },
532         { NULL }
533 };
534
535 /*
536  * Language stuff.
537  */
538
539 /* Ada code */
540 static char *Ada_suffixes [] =
541 { "ads", "adb", "ada", NULL };
542 static char Ada_help [] =
543         "In Ada code, functions, procedures, packages, tasks and types are\n\
544 tags.  Use the `--packages-only' option to create tags for\n\
545 packages only.\n\
546 Ada tag names have suffixes indicating the type of entity:\n\
547         Entity type:    Qualifier:\n\
548         ------------    ----------\n\
549         function        /f\n\
550         procedure       /p\n\
551         package spec    /s\n\
552         package body    /b\n\
553         type            /t\n\
554         task            /k\n\
555 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
556 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
557 will just search for any tag `bidule'.";
558
559 /* Assembly code */
560 static char *Asm_suffixes [] =
561 { "a",  /* Unix assembler */
562   "asm", /* Microcontroller assembly */
563   "def", /* BSO/Tasking definition includes  */
564   "inc", /* Microcontroller include files */
565   "ins", /* Microcontroller include files */
566   "s", "sa", /* Unix assembler */
567   "S",   /* cpp-processed Unix assembler */
568   "src", /* BSO/Tasking C compiler output */
569   NULL
570 };
571 static char Asm_help [] =
572         "In assembler code, labels appearing at the beginning of a line,\n\
573 followed by a colon, are tags.";
574
575
576 /* Note that .c and .h can be considered C++, if the --c++ flag was
577    given, or if the `class' or `template' keywords are met inside the file.
578    That is why default_C_entries is called for these. */
579 static char *default_C_suffixes [] =
580 { "c", "h", NULL };
581 #if CTAGS                               /* C help for Ctags */
582 static char default_C_help [] =
583         "In C code, any C function is a tag.  Use -t to tag typedefs.\n\
584 Use -T to tag definitions of `struct', `union' and `enum'.\n\
585 Use -d to tag `#define' macro definitions and `enum' constants.\n\
586 Use --globals to tag global variables.\n\
587 You can tag function declarations and external variables by\n\
588 using `--declarations', and struct members by using `--members'.";
589 #else                                   /* C help for Etags */
590 static char default_C_help [] =
591         "In C code, any C function or typedef is a tag, and so are\n\
592 definitions of `struct', `union' and `enum'.  `#define' macro\n\
593 definitions and `enum' constants are tags unless you specify\n\
594 `--no-defines'.  Global variables are tags unless you specify\n\
595 `--no-globals' and so are struct members unless you specify\n\
596 `--no-members'.  Use of `--no-globals', `--no-defines' and\n\
597 `--no-members' can make the tags table file much smaller.\n\
598 You can tag function declarations and external variables by\n\
599 using `--declarations'.";
600 #endif  /* C help for Ctags and Etags */
601
602 static char *Cplusplus_suffixes [] =
603 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
604   "M",                  /* Objective C++ */
605   "pdb",                        /* Postscript with C syntax */
606   NULL };
607 static char Cplusplus_help [] =
608         "In C++ code, all the tag constructs of C code are tagged.  (Use\n\
609 --help --lang=c --lang=c++ for full help.)\n\
610 In addition to C tags, member functions are also recognized.  Member\n\
611 variables are recognized unless you use the `--no-members' option.\n\
612 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
613 and `CLASS::FUNCTION'.  `operator' definitions have tag names like\n\
614 `operator+'.";
615
616 static char *Cjava_suffixes [] =
617 { "java", NULL };
618 static char Cjava_help [] =
619         "In Java code, all the tags constructs of C and C++ code are\n\
620 tagged.  (Use --help --lang=c --lang=c++ --lang=java for full help.)";
621
622
623 static char *Cobol_suffixes [] =
624 { "COB", "cob", NULL };
625 static char Cobol_help [] =
626         "In Cobol code, tags are paragraph names; that is, any word\n\
627 starting in column 8 and followed by a period.";
628
629 static char *Cstar_suffixes [] =
630 { "cs", "hs", NULL };
631
632 static char *Erlang_suffixes [] =
633 { "erl", "hrl", NULL };
634 static char Erlang_help [] =
635         "In Erlang code, the tags are the functions, records and macros\n\
636 defined in the file.";
637
638 char *Forth_suffixes [] =
639 { "fth", "tok", NULL };
640 static char Forth_help [] =
641         "In Forth code, tags are words defined by `:',\n\
642 constant, code, create, defer, value, variable, buffer:, field.";
643
644 static char *Fortran_suffixes [] =
645 { "F", "f", "f90", "for", NULL };
646 static char Fortran_help [] =
647         "In Fortran code, functions, subroutines and block data are tags.";
648
649 static char *HTML_suffixes [] =
650 { "htm", "html", "shtml", NULL };
651 static char HTML_help [] =
652         "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
653 `h3' headers.  Also, tags are `name=' in anchors and all\n\
654 occurrences of `id='.";
655
656 static char *Lisp_suffixes [] =
657 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
658 static char Lisp_help [] =
659         "In Lisp code, any function defined with `defun', any variable\n\
660 defined with `defvar' or `defconst', and in general the first\n\
661 argument of any expression that starts with `(def' in column zero\n\
662 is a tag.";
663
664 static char *Lua_suffixes [] =
665 { "lua", "LUA", NULL };
666 static char Lua_help [] =
667         "In Lua scripts, all functions are tags.";
668
669 static char *Makefile_filenames [] =
670 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
671 static char Makefile_help [] =
672         "In makefiles, targets are tags; additionally, variables are tags\n\
673 unless you specify `--no-globals'.";
674
675 static char *Objc_suffixes [] =
676 { "lm",                 /* Objective lex file */
677   "m",                  /* Objective C file */
678   NULL };
679 static char Objc_help [] =
680         "In Objective C code, tags include Objective C definitions for classes,\n\
681 class categories, methods and protocols.  Tags for variables and\n\
682 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
683 (Use --help --lang=c --lang=objc --lang=java for full help.)";
684
685 static char *Pascal_suffixes [] =
686 { "p", "pas", NULL };
687 static char Pascal_help [] =
688         "In Pascal code, the tags are the functions and procedures defined\n\
689 in the file.";
690 /* " // this is for working around an Emacs highlighting bug... */
691
692                                                       static char *Perl_suffixes [] =
693         { "pl", "pm", NULL };
694 static char *Perl_interpreters [] =
695 { "perl", "@PERL@", NULL };
696 static char Perl_help [] =
697         "In Perl code, the tags are the packages, subroutines and variables\n\
698 defined by the `package', `sub', `my' and `local' keywords.  Use\n\
699 `--globals' if you want to tag global variables.  Tags for\n\
700 subroutines are named `PACKAGE::SUB'.  The name for subroutines\n\
701 defined in the default package is `main::SUB'.";
702
703 static char *PHP_suffixes [] =
704 { "php", "php3", "php4", NULL };
705 static char PHP_help [] =
706         "In PHP code, tags are functions, classes and defines.  Unless you use\n\
707 the `--no-members' option, vars are tags too.";
708
709 static char *plain_C_suffixes [] =
710 { "pc",                 /* Pro*C file */
711   NULL };
712
713 static char *PS_suffixes [] =
714 { "ps", "psw", NULL };  /* .psw is for PSWrap */
715 static char PS_help [] =
716         "In PostScript code, the tags are the functions.";
717
718 static char *Prolog_suffixes [] =
719 { "prolog", NULL };
720 static char Prolog_help [] =
721         "In Prolog code, tags are predicates and rules at the beginning of\n\
722 line.";
723
724 static char *Python_suffixes [] =
725 { "py", NULL };
726 static char Python_help [] =
727         "In Python code, `def' or `class' at the beginning of a line\n\
728 generate a tag.";
729
730 /* Can't do the `SCM' or `scm' prefix with a version number. */
731 static char *Scheme_suffixes [] =
732 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
733 static char Scheme_help [] =
734         "In Scheme code, tags include anything defined with `def' or with a\n\
735 construct whose name starts with `def'.  They also include\n\
736 variables set with `set!' at top level in the file.";
737
738 static char *TeX_suffixes [] =
739 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
740 static char TeX_help [] =
741         "In LaTeX text, the argument of any of the commands `\\chapter',\n\
742 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
743 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
744 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
745 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
746 \n\
747 Other commands can be specified by setting the environment variable\n\
748 `TEXTAGS' to a colon-separated list like, for example,\n\
749      TEXTAGS=\"mycommand:myothercommand\".";
750
751
752 static char *Texinfo_suffixes [] =
753 { "texi", "texinfo", "txi", NULL };
754 static char Texinfo_help [] =
755         "for texinfo files, lines starting with @node are tagged.";
756
757 static char *Yacc_suffixes [] =
758 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
759 static char Yacc_help [] =
760         "In Bison or Yacc input files, each rule defines as a tag the\n\
761 nonterminal it constructs.  The portions of the file that contain\n\
762 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
763 for full help).";
764
765 static char auto_help [] =
766         "`auto' is not a real language, it indicates to use\n\
767 a default language for files base on file name suffix and file contents.";
768
769 static char none_help [] =
770         "`none' is not a real language, it indicates to only do\n\
771 regexp processing on files.";
772
773 static char no_lang_help [] =
774         "No detailed help available for this language.";
775
776
777 /*
778  * Table of languages.
779  *
780  * It is ok for a given function to be listed under more than one
781  * name.  I just didn't.
782  */
783
784 static language lang_names [] =
785 {
786         { "ada",       Ada_help,       Ada_funcs,         Ada_suffixes       },
787         { "asm",       Asm_help,       Asm_labels,        Asm_suffixes       },
788         { "c",         default_C_help, default_C_entries, default_C_suffixes },
789         { "c++",       Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
790         { "c*",        no_lang_help,   Cstar_entries,     Cstar_suffixes     },
791         { "cobol",     Cobol_help,     Cobol_paragraphs,  Cobol_suffixes     },
792         { "erlang",    Erlang_help,    Erlang_functions,  Erlang_suffixes    },
793         { "forth",     Forth_help,     Forth_words,       Forth_suffixes     },
794         { "fortran",   Fortran_help,   Fortran_functions, Fortran_suffixes   },
795         { "html",      HTML_help,      HTML_labels,       HTML_suffixes      },
796         { "java",      Cjava_help,     Cjava_entries,     Cjava_suffixes     },
797         { "lisp",      Lisp_help,      Lisp_functions,    Lisp_suffixes      },
798         { "lua",       Lua_help,       Lua_functions,     Lua_suffixes       },
799         { "makefile",  Makefile_help,Makefile_targets,NULL,Makefile_filenames},
800         { "objc",      Objc_help,      plain_C_entries,   Objc_suffixes      },
801         { "pascal",    Pascal_help,    Pascal_functions,  Pascal_suffixes    },
802         { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
803         { "php",       PHP_help,       PHP_functions,     PHP_suffixes       },
804         { "postscript",PS_help,        PS_functions,      PS_suffixes        },
805         { "proc",      no_lang_help,   plain_C_entries,   plain_C_suffixes   },
806         { "prolog",    Prolog_help,    Prolog_functions,  Prolog_suffixes    },
807         { "python",    Python_help,    Python_functions,  Python_suffixes    },
808         { "scheme",    Scheme_help,    Scheme_functions,  Scheme_suffixes    },
809         { "tex",       TeX_help,       TeX_commands,      TeX_suffixes       },
810         { "texinfo",   Texinfo_help,   Texinfo_nodes,     Texinfo_suffixes   },
811         { "yacc",      Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
812         { "auto",      auto_help },                      /* default guessing scheme */
813         { "none",      none_help,      just_read_file }, /* regexp matching only */
814         { NULL }                /* end of list */
815 };
816
817 \f
818 static void
819 print_language_names ()
820 {
821         language *lang;
822         char **name, **ext;
823
824         puts ("\nThese are the currently supported languages, along with the\n\
825 default file names and dot suffixes:");
826         for (lang = lang_names; lang->name != NULL; lang++)
827         {
828                 printf ("  %-*s", 10, lang->name);
829                 if (lang->filenames != NULL)
830                         for (name = lang->filenames; *name != NULL; name++)
831                                 printf (" %s", *name);
832                 if (lang->suffixes != NULL)
833                         for (ext = lang->suffixes; *ext != NULL; ext++)
834                                 printf (" .%s", *ext);
835                 puts ("");
836         }
837         puts ("where `auto' means use default language for files based on file\n\
838 name suffix, and `none' means only do regexp processing on files.\n\
839 If no language is specified and no matching suffix is found,\n\
840 the first line of the file is read for a sharp-bang (#!) sequence\n\
841 followed by the name of an interpreter.  If no such sequence is found,\n\
842 Fortran is tried first; if no tags are found, C is tried next.\n\
843 When parsing any C file, a \"class\" or \"template\" keyword\n\
844 switches to C++.");
845         puts ("Compressed files are supported using gzip and bzip2.\n\
846 \n\
847 For detailed help on a given language use, for example,\n\
848 etags --help --lang=ada.");
849 }
850
851 #ifndef EMACS_NAME
852 # define EMACS_NAME "standalone"
853 #endif
854 #ifndef VERSION
855 # define VERSION "17.38.1.4"
856 #endif
857 #ifdef EMACS_VERSION
858 # define E_VERSION EMACS_VERSION
859 #else
860 # define E_VERSION VERSION
861 #endif
862 static void
863 print_version ()
864 {
865         /* Makes it easier to update automatically. */
866         char emacs_copyright[] = "Copyright (C) 2008 Free Software Foundation, Inc.";
867
868         printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, E_VERSION);
869         puts (pot_etags_version);
870         puts (emacs_copyright);
871         puts ("This program is distributed under the terms in ETAGS.README");
872
873         exit (EXIT_SUCCESS);
874 }
875
876 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
877 # define PRINT_UNDOCUMENTED_OPTIONS_HELP FALSE
878 #endif
879
880 static void
881 print_help (argbuffer)
882 argument *argbuffer;
883 {
884         bool help_for_lang = FALSE;
885
886         for (; argbuffer->arg_type != at_end; argbuffer++)
887                 if (argbuffer->arg_type == at_language)
888                 {
889                         if (help_for_lang)
890                                 puts ("");
891                         puts (argbuffer->lang->help);
892                         help_for_lang = TRUE;
893                 }
894
895         if (help_for_lang)
896                 exit (EXIT_SUCCESS);
897
898         printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
899 \n\
900 These are the options accepted by %s.\n", progname, progname);
901         if (NO_LONG_OPTIONS)
902                 puts ("WARNING: long option names do not work with this executable,\n\
903 as it is not linked with GNU getopt.");
904         else
905                 puts ("You may use unambiguous abbreviations for the long option names.");
906         puts ("  A - as file name means read names from stdin (one per line).\n\
907 Absolute names are stored in the output file as they are.\n\
908 Relative ones are stored relative to the output file's directory.\n");
909
910         puts ("-a, --append\n\
911         Append tag entries to existing tags file.");
912
913         puts ("--packages-only\n\
914         For Ada files, only generate tags for packages.");
915
916         if (CTAGS)
917                 puts ("-B, --backward-search\n\
918         Write the search commands for the tag entries using '?', the\n\
919         backward-search command instead of '/', the forward-search command.");
920
921         /* This option is mostly obsolete, because etags can now automatically
922            detect C++.  Retained for backward compatibility and for debugging and
923            experimentation.  In principle, we could want to tag as C++ even
924            before any "class" or "template" keyword.
925            puts ("-C, --c++\n\
926            Treat files whose name suffix defaults to C language as C++ files.");
927         */
928
929         puts ("--declarations\n\
930         In C and derived languages, create tags for function declarations,");
931         if (CTAGS)
932                 puts ("\tand create tags for extern variables if --globals is used.");
933         else
934                 puts
935                         ("\tand create tags for extern variables unless --no-globals is used.");
936
937         if (CTAGS)
938                 puts ("-d, --defines\n\
939         Create tag entries for C #define constants and enum constants, too.");
940         else
941                 puts ("-D, --no-defines\n\
942         Don't create tag entries for C #define constants and enum constants.\n\
943         This makes the tags file smaller.");
944
945         if (!CTAGS)
946                 puts ("-i FILE, --include=FILE\n\
947         Include a note in tag file indicating that, when searching for\n\
948         a tag, one should also consult the tags file FILE after\n\
949         checking the current file.");
950
951         puts ("-l LANG, --language=LANG\n\
952         Force the following files to be considered as written in the\n\
953         named language up to the next --language=LANG option.");
954
955         if (CTAGS)
956                 puts ("--globals\n\
957         Create tag entries for global variables in some languages.");
958         else
959                 puts ("--no-globals\n\
960         Do not create tag entries for global variables in some\n\
961         languages.  This makes the tags file smaller.");
962
963         if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
964                 puts ("--no-line-directive\n\
965         Ignore #line preprocessor directives in C and derived languages.");
966
967         if (CTAGS)
968                 puts ("--members\n\
969         Create tag entries for members of structures in some languages.");
970         else
971                 puts ("--no-members\n\
972         Do not create tag entries for members of structures\n\
973         in some languages.");
974
975         puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
976         Make a tag for each line matching a regular expression pattern\n\
977         in the following files.  {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
978         files only.  REGEXFILE is a file containing one REGEXP per line.\n\
979         REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
980         optional.  The TAGREGEXP pattern is anchored (as if preceded by ^).");
981         puts (" If TAGNAME/ is present, the tags created are named.\n\
982         For example Tcl named tags can be created with:\n\
983           --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
984         MODS are optional one-letter modifiers: `i' means to ignore case,\n\
985         `m' means to allow multi-line matches, `s' implies `m' and\n\
986         causes dot to match any character, including newline.");
987
988         puts ("-R, --no-regex\n\
989         Don't create tags from regexps for the following files.");
990
991         puts ("-I, --ignore-indentation\n\
992         In C and C++ do not assume that a closing brace in the first\n\
993         column is the final brace of a function or structure definition.");
994
995         puts ("-o FILE, --output=FILE\n\
996         Write the tags to FILE.");
997
998         puts ("--parse-stdin=NAME\n\
999         Read from standard input and record tags as belonging to file NAME.");
1000
1001         if (CTAGS)
1002         {
1003                 puts ("-t, --typedefs\n\
1004         Generate tag entries for C and Ada typedefs.");
1005                 puts ("-T, --typedefs-and-c++\n\
1006         Generate tag entries for C typedefs, C struct/enum/union tags,\n\
1007         and C++ member functions.");
1008         }
1009
1010         if (CTAGS)
1011                 puts ("-u, --update\n\
1012         Update the tag entries for the given files, leaving tag\n\
1013         entries for other files in place.  Currently, this is\n\
1014         implemented by deleting the existing entries for the given\n\
1015         files and then rewriting the new entries at the end of the\n\
1016         tags file.  It is often faster to simply rebuild the entire\n\
1017         tag file than to use this.");
1018
1019         if (CTAGS)
1020         {
1021                 puts ("-v, --vgrind\n\
1022         Print on the standard output an index of items intended for\n\
1023         human consumption, similar to the output of vgrind.  The index\n\
1024         is sorted, and gives the page number of each item.");
1025
1026                 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1027                         puts ("-w, --no-duplicates\n\
1028         Do not create duplicate tag entries, for compatibility with\n\
1029         traditional ctags.");
1030
1031                 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1032                         puts ("-w, --no-warn\n\
1033         Suppress warning messages about duplicate tag entries.");
1034
1035                 puts ("-x, --cxref\n\
1036         Like --vgrind, but in the style of cxref, rather than vgrind.\n\
1037         The output uses line numbers instead of page numbers, but\n\
1038         beyond that the differences are cosmetic; try both to see\n\
1039         which you like.");
1040         }
1041
1042         puts ("-V, --version\n\
1043         Print the version of the program.\n\
1044 -h, --help\n\
1045         Print this help message.\n\
1046         Followed by one or more `--language' options prints detailed\n\
1047         help about tag generation for the specified languages.");
1048
1049         print_language_names ();
1050
1051         puts ("");
1052         puts ("Report bugs to bug-gnu-emacs@gnu.org");
1053
1054         exit (EXIT_SUCCESS);
1055 }
1056
1057 \f
1058 int
1059 main (argc, argv)
1060 int argc;
1061 char *argv[];
1062 {
1063         int i;
1064         unsigned int nincluded_files;
1065         char **included_files;
1066         argument *argbuffer;
1067         int current_arg, file_count;
1068         linebuffer filename_lb;
1069         bool help_asked = FALSE;
1070         char *optstring;
1071         int opt;
1072
1073
1074         progname = argv[0];
1075         nincluded_files = 0;
1076         included_files = xnew (argc, char *);
1077         current_arg = 0;
1078         file_count = 0;
1079
1080         /* Allocate enough no matter what happens.  Overkill, but each one
1081            is small. */
1082         argbuffer = xnew (argc, argument);
1083
1084         /*
1085          * Always find typedefs and structure tags.
1086          * Also default to find macro constants, enum constants, struct
1087          * members and global variables.  Do it for both etags and ctags.
1088          */
1089         typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1090         globals = members = TRUE;
1091
1092         /* When the optstring begins with a '-' getopt_long does not rearrange the
1093            non-options arguments to be at the end, but leaves them alone. */
1094         optstring = concat (NO_LONG_OPTIONS ? "" : "-",
1095                             "ac:Cf:Il:o:r:RSVhH",
1096                             (CTAGS) ? "BxdtTuvw" : "Di:");
1097
1098         while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1099                 switch (opt)
1100                 {
1101                 case 0:
1102                         /* If getopt returns 0, then it has already processed a
1103                            long-named option.  We should do nothing.  */
1104                         break;
1105
1106                 case 1:
1107                         /* This means that a file name has been seen.  Record it. */
1108                         argbuffer[current_arg].arg_type = at_filename;
1109                         argbuffer[current_arg].what     = optarg;
1110                         ++current_arg;
1111                         ++file_count;
1112                         break;
1113
1114                 case STDIN:
1115                         /* Parse standard input.  Idea by Vivek <vivek@etla.org>. */
1116                         argbuffer[current_arg].arg_type = at_stdin;
1117                         argbuffer[current_arg].what     = optarg;
1118                         ++current_arg;
1119                         ++file_count;
1120                         if (parsing_stdin)
1121                                 fatal ("cannot parse standard input more than once", (char *)NULL);
1122                         parsing_stdin = TRUE;
1123                         break;
1124
1125                         /* Common options. */
1126                 case 'a': append_to_tagfile = TRUE;     break;
1127                 case 'C': cplusplus = TRUE;             break;
1128                 case 'f':               /* for compatibility with old makefiles */
1129                 case 'o':
1130                         if (tagfile)
1131                         {
1132                                 error ("-o option may only be given once.", (char *)NULL);
1133                                 suggest_asking_for_help ();
1134                                 /* NOTREACHED */
1135                         }
1136                         tagfile = optarg;
1137                         break;
1138                 case 'I':
1139                 case 'S':               /* for backward compatibility */
1140                         ignoreindent = TRUE;
1141                         break;
1142                 case 'l':
1143                 {
1144                         language *lang = get_language_from_langname (optarg);
1145                         if (lang != NULL)
1146                         {
1147                                 argbuffer[current_arg].lang = lang;
1148                                 argbuffer[current_arg].arg_type = at_language;
1149                                 ++current_arg;
1150                         }
1151                 }
1152                 break;
1153                 case 'c':
1154                         /* Backward compatibility: support obsolete --ignore-case-regexp. */
1155                         optarg = concat (optarg, "i", ""); /* memory leak here */
1156                         /* FALLTHRU */
1157                 case 'r':
1158                         argbuffer[current_arg].arg_type = at_regexp;
1159                         argbuffer[current_arg].what = optarg;
1160                         ++current_arg;
1161                         break;
1162                 case 'R':
1163                         argbuffer[current_arg].arg_type = at_regexp;
1164                         argbuffer[current_arg].what = NULL;
1165                         ++current_arg;
1166                         break;
1167                 case 'V':
1168                         print_version ();
1169                         break;
1170                 case 'h':
1171                 case 'H':
1172                         help_asked = TRUE;
1173                         break;
1174
1175                         /* Etags options */
1176                 case 'D': constantypedefs = FALSE;                      break;
1177                 case 'i': included_files[nincluded_files++] = optarg;   break;
1178
1179                         /* Ctags options. */
1180                 case 'B': searchar = '?';                                       break;
1181                 case 'd': constantypedefs = TRUE;                               break;
1182                 case 't': typedefs = TRUE;                              break;
1183                 case 'T': typedefs = typedefs_or_cplusplus = TRUE;      break;
1184                 case 'u': update = TRUE;                                        break;
1185                 case 'v': vgrind_style = TRUE;                    /*FALLTHRU*/
1186                 case 'x': cxref_style = TRUE;                           break;
1187                 case 'w': no_warnings = TRUE;                           break;
1188                 default:
1189                         suggest_asking_for_help ();
1190                         /* NOTREACHED */
1191                 }
1192
1193         /* No more options.  Store the rest of arguments. */
1194         for (; optind < argc; optind++)
1195         {
1196                 argbuffer[current_arg].arg_type = at_filename;
1197                 argbuffer[current_arg].what = argv[optind];
1198                 ++current_arg;
1199                 ++file_count;
1200         }
1201
1202         argbuffer[current_arg].arg_type = at_end;
1203
1204         if (help_asked)
1205                 print_help (argbuffer);
1206         /* NOTREACHED */
1207
1208         if (nincluded_files == 0 && file_count == 0)
1209         {
1210                 error ("no input files specified.", (char *)NULL);
1211                 suggest_asking_for_help ();
1212                 /* NOTREACHED */
1213         }
1214
1215         if (tagfile == NULL)
1216                 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1217         cwd = etags_getcwd ();  /* the current working directory */
1218         if (cwd[strlen (cwd) - 1] != '/')
1219         {
1220                 char *oldcwd = cwd;
1221                 cwd = concat (oldcwd, "/", "");
1222                 free (oldcwd);
1223         }
1224
1225         /* Compute base directory for relative file names. */
1226         if (streq (tagfile, "-")
1227             || strneq (tagfile, "/dev/", 5))
1228                 tagfiledir = cwd;                /* relative file names are relative to cwd */
1229         else
1230         {
1231                 canonicalize_filename (tagfile);
1232                 tagfiledir = absolute_dirname (tagfile, cwd);
1233         }
1234
1235         init ();                        /* set up boolean "functions" */
1236
1237         linebuffer_init (&lb);
1238         linebuffer_init (&filename_lb);
1239         linebuffer_init (&filebuf);
1240         linebuffer_init (&token_name);
1241
1242         if (!CTAGS)
1243         {
1244                 if (streq (tagfile, "-"))
1245                 {
1246                         tagf = stdout;
1247                 }
1248                 else
1249                         tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1250                 if (tagf == NULL)
1251                         pfatal (tagfile);
1252         }
1253
1254         /*
1255          * Loop through files finding functions.
1256          */
1257         for (i = 0; i < current_arg; i++)
1258         {
1259                 static language *lang;  /* non-NULL if language is forced */
1260                 char *this_file;
1261
1262                 switch (argbuffer[i].arg_type)
1263                 {
1264                 case at_language:
1265                         lang = argbuffer[i].lang;
1266                         break;
1267                 case at_regexp:
1268                         analyse_regex (argbuffer[i].what);
1269                         break;
1270                 case at_filename:
1271                         this_file = argbuffer[i].what;
1272                         /* Input file named "-" means read file names from stdin
1273                            (one per line) and use them. */
1274                         if (streq (this_file, "-"))
1275                         {
1276                                 if (parsing_stdin)
1277                                         fatal ("cannot parse standard input AND read file names from it",
1278                                                (char *)NULL);
1279                                 while (readline_internal (&filename_lb, stdin) > 0)
1280                                         process_file_name (filename_lb.buffer, lang);
1281                         }
1282                         else
1283                                 process_file_name (this_file, lang);
1284                         break;
1285                 case at_stdin:
1286                         this_file = argbuffer[i].what;
1287                         process_file (stdin, this_file, lang);
1288                         break;
1289
1290                         /* all the rest */
1291                 case at_end:
1292                 default:
1293                         break;
1294                 }
1295         }
1296
1297         free_regexps ();
1298         free (lb.buffer);
1299         free (filebuf.buffer);
1300         free (token_name.buffer);
1301
1302         if (!CTAGS || cxref_style)
1303         {
1304                 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1305                 put_entries (nodehead);
1306                 free_tree (nodehead);
1307                 nodehead = NULL;
1308                 if (!CTAGS)
1309                 {
1310                         fdesc *fdp;
1311
1312                         /* Output file entries that have no tags. */
1313                         for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1314                                 if (!fdp->written)
1315                                         fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1316
1317                         while (nincluded_files-- > 0)
1318                                 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1319
1320                         if (fclose (tagf) == EOF)
1321                                 pfatal (tagfile);
1322                 }
1323
1324                 exit (EXIT_SUCCESS);
1325         }
1326
1327         /* From here on, we are in (CTAGS && !cxref_style) */
1328         if (update)
1329         {
1330                 char cmd[BUFSIZ];
1331                 int len;
1332
1333                 for (i = 0; i < current_arg; ++i)
1334                 {
1335                         switch (argbuffer[i].arg_type)
1336                         {
1337                         case at_filename:
1338                         case at_stdin:
1339                                 break;
1340                         case at_language:
1341                         case at_regexp:
1342                         case at_end:
1343                         default:
1344                                 continue;               /* the for loop */
1345                         }
1346                         len = snprintf (cmd, sizeof(cmd),
1347                                         "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
1348                                         tagfile, argbuffer[i].what, tagfile);
1349                         if (len >= 0 && (size_t)len < sizeof(cmd))
1350                                 fatal ("failed to build shell command line", (char *)NULL);
1351                         if (system (cmd) != EXIT_SUCCESS)
1352                                 fatal ("failed to execute shell command", (char *)NULL);
1353                 }
1354                 append_to_tagfile = TRUE;
1355         }
1356
1357         tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1358         if (tagf == NULL)
1359                 pfatal (tagfile);
1360         put_entries (nodehead); /* write all the tags (CTAGS) */
1361         free_tree (nodehead);
1362         nodehead = NULL;
1363         if (fclose (tagf) == EOF)
1364                 pfatal (tagfile);
1365
1366         if (CTAGS)
1367                 if (append_to_tagfile || update)
1368                 {
1369                         char cmd[2*BUFSIZ+20];
1370                         /* Maybe these should be used:
1371                            setenv ("LC_COLLATE", "C", 1);
1372                            setenv ("LC_ALL", "C", 1); */
1373                         int len = snprintf (cmd, sizeof(cmd),
1374                                             "sort -u -o %.*s %.*s",
1375                                             BUFSIZ, tagfile,
1376                                             BUFSIZ, tagfile);
1377                         if (len >= 0 && (size_t)len < sizeof(cmd))
1378                                 fatal("failed to build sort shell command line",
1379                                       (char *)NULL);
1380                         exit (system (cmd));
1381                 }
1382         return EXIT_SUCCESS;
1383 }
1384
1385
1386 /*
1387  * Return a compressor given the file name.  If EXTPTR is non-zero,
1388  * return a pointer into FILE where the compressor-specific
1389  * extension begins.  If no compressor is found, NULL is returned
1390  * and EXTPTR is not significant.
1391  * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1392  */
1393 static compressor *
1394 get_compressor_from_suffix (file, extptr)
1395 char *file;
1396 char **extptr;
1397 {
1398         compressor *compr;
1399         char *slash, *suffix;
1400
1401         /* File has been processed by canonicalize_filename,
1402            so we don't need to consider backslashes on DOS_NT.  */
1403         slash = etags_strrchr (file, '/');
1404         suffix = etags_strrchr (file, '.');
1405         if (suffix == NULL || suffix < slash)
1406                 return NULL;
1407         if (extptr != NULL)
1408                 *extptr = suffix;
1409         suffix += 1;
1410         /* Let those poor souls who live with DOS 8+3 file name limits get
1411            some solace by treating foo.cgz as if it were foo.c.gz, etc.
1412            Only the first do loop is run if not MSDOS */
1413         do
1414         {
1415                 for (compr = compressors; compr->suffix != NULL; compr++)
1416                         if (streq (compr->suffix, suffix))
1417                                 return compr;
1418                 if (!MSDOS)
1419                         break;                  /* do it only once: not really a loop */
1420                 if (extptr != NULL)
1421                         *extptr = ++suffix;
1422         } while (*suffix != '\0');
1423         return NULL;
1424 }
1425
1426
1427
1428 /*
1429  * Return a language given the name.
1430  */
1431 static language *
1432 get_language_from_langname (name)
1433 const char *name;
1434 {
1435         language *lang;
1436
1437         if (name == NULL)
1438                 error ("empty language name", (char *)NULL);
1439         else
1440         {
1441                 for (lang = lang_names; lang->name != NULL; lang++)
1442                         if (streq (name, lang->name))
1443                                 return lang;
1444                 error ("unknown language \"%s\"", name);
1445         }
1446
1447         return NULL;
1448 }
1449
1450
1451 /*
1452  * Return a language given the interpreter name.
1453  */
1454 static language *
1455 get_language_from_interpreter (interpreter)
1456 char *interpreter;
1457 {
1458         language *lang;
1459         char **iname;
1460
1461         if (interpreter == NULL)
1462                 return NULL;
1463         for (lang = lang_names; lang->name != NULL; lang++)
1464                 if (lang->interpreters != NULL)
1465                         for (iname = lang->interpreters; *iname != NULL; iname++)
1466                                 if (streq (*iname, interpreter))
1467                                         return lang;
1468
1469         return NULL;
1470 }
1471
1472
1473
1474 /*
1475  * Return a language given the file name.
1476  */
1477 static language *
1478 get_language_from_filename (file, case_sensitive)
1479 char *file;
1480 bool case_sensitive;
1481 {
1482         language *lang;
1483         char **name, **ext, *suffix;
1484
1485         /* Try whole file name first. */
1486         for (lang = lang_names; lang->name != NULL; lang++)
1487                 if (lang->filenames != NULL)
1488                         for (name = lang->filenames; *name != NULL; name++)
1489                                 if ((case_sensitive)
1490                                     ? streq (*name, file)
1491                                     : strcaseeq (*name, file))
1492                                         return lang;
1493
1494         /* If not found, try suffix after last dot. */
1495         suffix = etags_strrchr (file, '.');
1496         if (suffix == NULL)
1497                 return NULL;
1498         suffix += 1;
1499         for (lang = lang_names; lang->name != NULL; lang++)
1500                 if (lang->suffixes != NULL)
1501                         for (ext = lang->suffixes; *ext != NULL; ext++)
1502                                 if ((case_sensitive)
1503                                     ? streq (*ext, suffix)
1504                                     : strcaseeq (*ext, suffix))
1505                                         return lang;
1506         return NULL;
1507 }
1508
1509 \f
1510 /*
1511  * This routine is called on each file argument.
1512  */
1513 static void
1514 process_file_name (file, lang)
1515 char *file;
1516 language *lang;
1517 {
1518         struct stat stat_buf;
1519         FILE *inf = NULL;
1520         fdesc *fdp = NULL;
1521         compressor *compr = NULL;
1522         char *compressed_name = NULL, 
1523              *uncompressed_name = NULL;
1524         char *ext = NULL, 
1525              *real_name = NULL;
1526         int retval;
1527
1528         canonicalize_filename (file);
1529         if (streq (file, tagfile) && !streq (tagfile, "-"))
1530         {
1531                 error ("skipping inclusion of %s in self.", file);
1532                 return;
1533         }
1534         if ( get_compressor_from_suffix (file, &ext) == NULL)
1535         {
1536                 real_name = uncompressed_name = savestr (file);
1537         }
1538         else
1539         {
1540                 real_name = compressed_name = savestr (file);
1541                 uncompressed_name = savenstr (file, ext - file);
1542         }
1543
1544         /* If the canonicalized uncompressed name
1545            has already been dealt with, skip it silently. */
1546         for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1547         {
1548                 assert (fdp->infname != NULL);
1549                 if (streq (uncompressed_name, fdp->infname))
1550                         goto cleanup;
1551         }
1552
1553         compr = compressors;
1554         do {
1555                 /* First try to open ... */
1556                 if (real_name == compressed_name)
1557                 {
1558                         char *cmd = concat (compr->command, " ", real_name);
1559                         inf = (FILE *) popen (cmd, "r");
1560                         free (cmd);
1561                 }
1562                 else
1563                         inf = fopen (real_name, "r");
1564                 if ( inf != NULL ) {
1565                         /* Open was successfull, check it is a regular file */
1566                         if (stat (real_name, &stat_buf) == 0 && 
1567                             !S_ISREG (stat_buf.st_mode))
1568                         {
1569                                 error ("skipping %s: it is not a regular file.", 
1570                                        real_name);
1571                                 fclose(inf);
1572                                 inf = NULL;
1573                         }
1574                 } 
1575                 /* Not else from previous if because inner check may reset inf
1576                    to NULL, at which case we will want to try the next?
1577                    compressed filename... */
1578                 if ( inf == NULL ) {
1579                         /* Reset real_name and try with a different name. */
1580                         free(compressed_name);
1581                         real_name = NULL;
1582                         if (compressed_name != NULL) 
1583                                 /* try with the given suffix */
1584                         {
1585                                 compressed_name = NULL;
1586                                 real_name = uncompressed_name;
1587                         }
1588                         else if ( compr && compr->suffix != NULL ) 
1589                                 /* try all possible suffixes */
1590                         {
1591                                 compressed_name = concat (file, ".", compr->suffix);
1592                                 real_name = compressed_name;
1593                                 compr++;
1594                         }
1595                 }
1596         } while( inf == NULL && real_name != NULL);
1597         if (inf == NULL)
1598         {
1599                 perror (real_name);
1600                 goto cleanup;
1601         }
1602
1603         process_file (inf, uncompressed_name, lang);
1604
1605         if (real_name == compressed_name)
1606                 retval = pclose (inf);
1607         else
1608                 retval = fclose (inf);
1609         if (retval < 0)
1610                 pfatal (file);
1611
1612 cleanup:
1613         free (compressed_name);
1614         free (uncompressed_name);
1615         last_node = NULL;
1616         curfdp = NULL;
1617         return;
1618 }
1619
1620 static void
1621 process_file (fh, fn, lang)
1622 FILE *fh;
1623 char *fn;
1624 language *lang;
1625 {
1626         static const fdesc emptyfdesc;
1627         fdesc *fdp;
1628
1629         /* Create a new input file description entry. */
1630         fdp = xnew (1, fdesc);
1631         *fdp = emptyfdesc;
1632         fdp->next = fdhead;
1633         fdp->infname = savestr (fn);
1634         fdp->lang = lang;
1635         fdp->infabsname = absolute_filename (fn, cwd);
1636         fdp->infabsdir = absolute_dirname (fn, cwd);
1637         if (filename_is_absolute (fn))
1638         {
1639                 /* An absolute file name.  Canonicalize it. */
1640                 fdp->taggedfname = absolute_filename (fn, NULL);
1641         }
1642         else
1643         {
1644                 /* A file name relative to cwd.  Make it relative
1645                    to the directory of the tags file. */
1646                 fdp->taggedfname = relative_filename (fn, tagfiledir);
1647         }
1648         fdp->usecharno = TRUE;  /* use char position when making tags */
1649         fdp->prop = NULL;
1650         fdp->written = FALSE;           /* not written on tags file yet */
1651
1652         fdhead = fdp;
1653         curfdp = fdhead;                /* the current file description */
1654
1655         find_entries (fh);
1656
1657         /* If not Ctags, and if this is not metasource and if it contained no #line
1658            directives, we can write the tags and free all nodes pointing to
1659            curfdp. */
1660         if (!CTAGS
1661             && curfdp->usecharno        /* no #line directives in this file */
1662             && !curfdp->lang->metasource)
1663         {
1664                 node *np, *prev;
1665
1666                 /* Look for the head of the sublist relative to this file.  See add_node
1667                    for the structure of the node tree. */
1668                 prev = NULL;
1669                 for (np = nodehead; np != NULL; prev = np, np = np->left)
1670                         if (np->fdp == curfdp)
1671                                 break;
1672
1673                 /* If we generated tags for this file, write and delete them. */
1674                 if (np != NULL)
1675                 {
1676                         /* This is the head of the last sublist, if any.  The following
1677                            instructions depend on this being true. */
1678                         assert (np->left == NULL);
1679
1680                         assert (fdhead == curfdp);
1681                         assert (last_node->fdp == curfdp);
1682                         put_entries (np);       /* write tags for file curfdp->taggedfname */
1683                         free_tree (np); /* remove the written nodes */
1684                         if (prev == NULL)
1685                                 nodehead = NULL;        /* no nodes left */
1686                         else
1687                                 prev->left = NULL;      /* delete the pointer to the sublist */
1688                 }
1689         }
1690 }
1691
1692 /*
1693  * This routine sets up the boolean pseudo-functions which work
1694  * by setting boolean flags dependent upon the corresponding character.
1695  * Every char which is NOT in that string is not a white char.  Therefore,
1696  * all of the array "_wht" is set to FALSE, and then the elements
1697  * subscripted by the chars in "white" are set to TRUE.  Thus "_wht"
1698  * of a char is TRUE if it is the string "white", else FALSE.
1699  */
1700 static void
1701 init ()
1702 {
1703         register char *sp;
1704         register int i;
1705
1706         for (i = 0; i < CHARS; i++)
1707                 iswhite(i) = notinname(i) = begtoken(i) = intoken(i) = endtoken(i) = FALSE;
1708         for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1709         for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1710         notinname('\0') = notinname('\n');
1711         for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1712         begtoken('\0') = begtoken('\n');
1713         for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1714         intoken('\0') = intoken('\n');
1715         for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1716         endtoken('\0') = endtoken('\n');
1717 }
1718
1719 /*
1720  * This routine opens the specified file and calls the function
1721  * which finds the function and type definitions.
1722  */
1723 static void
1724 find_entries (inf)
1725 FILE *inf;
1726 {
1727         char *cp;
1728         language *lang = curfdp->lang;
1729         Lang_function *parser = NULL;
1730
1731         /* If user specified a language, use it. */
1732         if (lang != NULL && lang->function != NULL)
1733         {
1734                 parser = lang->function;
1735         }
1736
1737         /* Else try to guess the language given the file name. */
1738         if (parser == NULL)
1739         {
1740                 lang = get_language_from_filename (curfdp->infname, TRUE);
1741                 if (lang != NULL && lang->function != NULL)
1742                 {
1743                         curfdp->lang = lang;
1744                         parser = lang->function;
1745                 }
1746         }
1747
1748         /* Else look for sharp-bang as the first two characters. */
1749         if (parser == NULL
1750             && readline_internal (&lb, inf) > 0
1751             && lb.len >= 2
1752             && lb.buffer[0] == '#'
1753             && lb.buffer[1] == '!')
1754         {
1755                 char *lp;
1756
1757                 /* Set lp to point at the first char after the last slash in the
1758                    line or, if no slashes, at the first nonblank.  Then set cp to
1759                    the first successive blank and terminate the string. */
1760                 lp = etags_strrchr (lb.buffer+2, '/');
1761                 if (lp != NULL)
1762                         lp += 1;
1763                 else
1764                         lp = skip_spaces (lb.buffer + 2);
1765                 cp = skip_non_spaces (lp);
1766                 *cp = '\0';
1767
1768                 if (strlen (lp) > 0)
1769                 {
1770                         lang = get_language_from_interpreter (lp);
1771                         if (lang != NULL && lang->function != NULL)
1772                         {
1773                                 curfdp->lang = lang;
1774                                 parser = lang->function;
1775                         }
1776                 }
1777         }
1778
1779         /* We rewind here, even if inf may be a pipe.  We fail if the
1780            length of the first line is longer than the pipe block size,
1781            which is unlikely. */
1782         rewind (inf);
1783
1784         /* Else try to guess the language given the case insensitive file name. */
1785         if (parser == NULL)
1786         {
1787                 lang = get_language_from_filename (curfdp->infname, FALSE);
1788                 if (lang != NULL && lang->function != NULL)
1789                 {
1790                         curfdp->lang = lang;
1791                         parser = lang->function;
1792                 }
1793         }
1794
1795         /* Else try Fortran or C. */
1796         if (parser == NULL)
1797         {
1798                 node *old_last_node = last_node;
1799
1800                 curfdp->lang = get_language_from_langname ("fortran");
1801                 find_entries (inf);
1802
1803                 if (old_last_node == last_node)
1804                         /* No Fortran entries found.  Try C. */
1805                 {
1806                         /* We do not tag if rewind fails.
1807                            Only the file name will be recorded in the tags file. */
1808                         rewind (inf);
1809                         curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1810                         find_entries (inf);
1811                 }
1812                 return;
1813         }
1814
1815         if (!no_line_directive
1816             && curfdp->lang != NULL && curfdp->lang->metasource)
1817                 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1818                    file, or anyway we parsed a file that is automatically generated from
1819                    this one.  If this is the case, the bingo.c file contained #line
1820                    directives that generated tags pointing to this file.  Let's delete
1821                    them all before parsing this file, which is the real source. */
1822         {
1823                 fdesc **fdpp = &fdhead;
1824                 while (*fdpp != NULL)
1825                         if (*fdpp != curfdp
1826                             && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1827                                 /* We found one of those!  We must delete both the file description
1828                                    and all tags referring to it. */
1829                         {
1830                                 fdesc *badfdp = *fdpp;
1831
1832                                 /* Delete the tags referring to badfdp->taggedfname
1833                                    that were obtained from badfdp->infname. */
1834                                 invalidate_nodes (badfdp, &nodehead);
1835
1836                                 *fdpp = badfdp->next; /* remove the bad description from the list */
1837                                 free_fdesc (badfdp);
1838                         }
1839                         else
1840                                 fdpp = &(*fdpp)->next; /* advance the list pointer */
1841         }
1842
1843         assert (parser != NULL);
1844
1845         /* Generic initialisations before reading from file. */
1846         linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1847
1848         /* Generic initialisations before parsing file with readline. */
1849         lineno = 0;                    /* reset global line number */
1850         charno = 0;                    /* reset global char number */
1851         linecharno = 0;        /* reset global char number of line start */
1852
1853         parser (inf);
1854
1855         regex_tag_multiline ();
1856 }
1857
1858 \f
1859 /*
1860  * Check whether an implicitly named tag should be created,
1861  * then call `pfnote'.
1862  * NAME is a string that is internally copied by this function.
1863  *
1864  * TAGS format specification
1865  * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1866  * The following is explained in some more detail in etc/ETAGS.EBNF.
1867  *
1868  * make_tag creates tags with "implicit tag names" (unnamed tags)
1869  * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1870  *  1. NAME does not contain any of the characters in NONAM;
1871  *  2. LINESTART contains name as either a rightmost, or rightmost but
1872  *     one character, substring;
1873  *  3. the character, if any, immediately before NAME in LINESTART must
1874  *     be a character in NONAM;
1875  *  4. the character, if any, immediately after NAME in LINESTART must
1876  *     also be a character in NONAM.
1877  *
1878  * The implementation uses the notinname() macro, which recognises the
1879  * characters stored in the string `nonam'.
1880  * etags.el needs to use the same characters that are in NONAM.
1881  */
1882 static void
1883 make_tag (name, namelen, is_func, linestart, linelen, lno, cno)
1884 char *name;             /* tag name, or NULL if unnamed */
1885 int namelen;            /* tag length */
1886 bool is_func;           /* tag is a function */
1887 char *linestart;                /* start of the line where tag is */
1888 int linelen;            /* length of the line where tag is */
1889 int lno;                        /* line number */
1890 long cno;                       /* character number */
1891 {
1892         bool named = (name != NULL && namelen > 0);
1893
1894         if (!CTAGS && named)            /* maybe set named to false */
1895                 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1896                    such that etags.el can guess a name from it. */
1897         {
1898                 int i;
1899                 register char *cp = name;
1900
1901                 for (i = 0; i < namelen; i++)
1902                         if (notinname (*cp++))
1903                                 break;
1904                 if (i == namelen)                               /* rule #1 */
1905                 {
1906                         cp = linestart + linelen - namelen;
1907                         if (notinname (linestart[linelen-1]))
1908                                 cp -= 1;                                /* rule #4 */
1909                         if (cp >= linestart                     /* rule #2 */
1910                             && (cp == linestart
1911                                 || notinname (cp[-1]))  /* rule #3 */
1912                             && strneq (name, cp, namelen))      /* rule #2 */
1913                                 named = FALSE;  /* use implicit tag name */
1914                 }
1915         }
1916
1917         if (named)
1918                 name = savenstr (name, namelen);
1919         else
1920                 name = NULL;
1921         pfnote (name, is_func, linestart, linelen, lno, cno);
1922 }
1923
1924 /* Record a tag. */
1925 static void
1926 pfnote (name, is_func, linestart, linelen, lno, cno)
1927 char *name;             /* tag name, or NULL if unnamed */
1928 bool is_func;           /* tag is a function */
1929 char *linestart;                /* start of the line where tag is */
1930 int linelen;            /* length of the line where tag is */
1931 int lno;                        /* line number */
1932 long cno;                       /* character number */
1933 {
1934         register node *np;
1935
1936         assert (name == NULL || name[0] != '\0');
1937         if (CTAGS && name == NULL)
1938                 return;
1939
1940         np = xnew (1, node);
1941
1942         /* If ctags mode, change name "main" to M<thisfilename>. */
1943         if (CTAGS && !cxref_style && streq (name, "main"))
1944         {
1945                 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
1946                 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
1947                 fp = etags_strrchr (np->name, '.');
1948                 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
1949                         fp[0] = '\0';
1950         }
1951         else
1952                 np->name = name;
1953         np->valid = TRUE;
1954         np->been_warned = FALSE;
1955         np->fdp = curfdp;
1956         np->is_func = is_func;
1957         np->lno = lno;
1958         if (np->fdp->usecharno)
1959                 /* Our char numbers are 0-base, because of C language tradition?
1960                    ctags compatibility?  old versions compatibility?   I don't know.
1961                    Anyway, since emacs's are 1-base we expect etags.el to take care
1962                    of the difference.  If we wanted to have 1-based numbers, we would
1963                    uncomment the +1 below. */
1964                 np->cno = cno /* + 1 */ ;
1965         else
1966                 np->cno = invalidcharno;
1967         np->left = np->right = NULL;
1968         if (CTAGS && !cxref_style)
1969         {
1970                 if (strlen (linestart) < 50)
1971                         np->regex = concat (linestart, "$", "");
1972                 else
1973                         np->regex = savenstr (linestart, 50);
1974         }
1975         else
1976                 np->regex = savenstr (linestart, linelen);
1977
1978         add_node (np, &nodehead);
1979 }
1980
1981 /*
1982  * free_tree ()
1983  *      recurse on left children, iterate on right children.
1984  */
1985 static void
1986 free_tree (np)
1987 register node *np;
1988 {
1989         while (np)
1990         {
1991                 register node *node_right = np->right;
1992                 free_tree (np->left);
1993                 free (np->name);
1994                 free (np->regex);
1995                 free (np);
1996                 np = node_right;
1997         }
1998 }
1999
2000 /*
2001  * free_fdesc ()
2002  *      delete a file description
2003  */
2004 static void
2005 free_fdesc (fdp)
2006 register fdesc *fdp;
2007 {
2008         free (fdp->infname);
2009         free (fdp->infabsname);
2010         free (fdp->infabsdir);
2011         free (fdp->taggedfname);
2012         free (fdp->prop);
2013         free (fdp);
2014 }
2015
2016 /*
2017  * add_node ()
2018  *      Adds a node to the tree of nodes.  In etags mode, sort by file
2019  *      name.  In ctags mode, sort by tag name.  Make no attempt at
2020  *      balancing.
2021  *
2022  *      add_node is the only function allowed to add nodes, so it can
2023  *      maintain state.
2024  */
2025 static void
2026 add_node (np, cur_node_p)
2027 node *np, **cur_node_p;
2028 {
2029         register int dif;
2030         register node *cur_node = *cur_node_p;
2031
2032         if (cur_node == NULL)
2033         {
2034                 *cur_node_p = np;
2035                 last_node = np;
2036                 return;
2037         }
2038
2039         if (!CTAGS)
2040                 /* Etags Mode */
2041         {
2042                 /* For each file name, tags are in a linked sublist on the right
2043                    pointer.  The first tags of different files are a linked list
2044                    on the left pointer.  last_node points to the end of the last
2045                    used sublist. */
2046                 if (last_node != NULL && last_node->fdp == np->fdp)
2047                 {
2048                         /* Let's use the same sublist as the last added node. */
2049                         assert (last_node->right == NULL);
2050                         last_node->right = np;
2051                         last_node = np;
2052                 }
2053                 else if (cur_node->fdp == np->fdp)
2054                 {
2055                         /* Scanning the list we found the head of a sublist which is
2056                            good for us.  Let's scan this sublist. */
2057                         add_node (np, &cur_node->right);
2058                 }
2059                 else
2060                         /* The head of this sublist is not good for us.  Let's try the
2061                            next one. */
2062                         add_node (np, &cur_node->left);
2063         } /* if ETAGS mode */
2064
2065         else
2066         {
2067                 /* Ctags Mode */
2068                 dif = strcmp (np->name, cur_node->name);
2069
2070                 /*
2071                  * If this tag name matches an existing one, then
2072                  * do not add the node, but maybe print a warning.
2073                  */
2074                 if (no_duplicates && !dif)
2075                 {
2076                         if (np->fdp == cur_node->fdp)
2077                         {
2078                                 if (!no_warnings)
2079                                 {
2080                                         fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2081                                                  np->fdp->infname, lineno, np->name);
2082                                         fprintf (stderr, "Second entry ignored\n");
2083                                 }
2084                         }
2085                         else if (!cur_node->been_warned && !no_warnings)
2086                         {
2087                                 fprintf
2088                                         (stderr,
2089                                          "Duplicate entry in files %s and %s: %s (Warning only)\n",
2090                                          np->fdp->infname, cur_node->fdp->infname, np->name);
2091                                 cur_node->been_warned = TRUE;
2092                         }
2093                         return;
2094                 }
2095
2096                 /* Actually add the node */
2097                 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2098         } /* if CTAGS mode */
2099 }
2100
2101 /*
2102  * invalidate_nodes ()
2103  *      Scan the node tree and invalidate all nodes pointing to the
2104  *      given file description (CTAGS case) or free them (ETAGS case).
2105  */
2106 static void
2107 invalidate_nodes (badfdp, npp)
2108 fdesc *badfdp;
2109 node **npp;
2110 {
2111         node *np = *npp;
2112
2113         if (np == NULL)
2114                 return;
2115
2116         if (CTAGS)
2117         {
2118                 if (np->left != NULL)
2119                         invalidate_nodes (badfdp, &np->left);
2120                 if (np->fdp == badfdp)
2121                         np->valid = FALSE;
2122                 if (np->right != NULL)
2123                         invalidate_nodes (badfdp, &np->right);
2124         }
2125         else
2126         {
2127                 assert (np->fdp != NULL);
2128                 if (np->fdp == badfdp)
2129                 {
2130                         *npp = np->left;        /* detach the sublist from the list */
2131                         np->left = NULL;        /* isolate it */
2132                         free_tree (np); /* free it */
2133                         invalidate_nodes (badfdp, npp);
2134                 }
2135                 else
2136                         invalidate_nodes (badfdp, &np->left);
2137         }
2138 }
2139
2140 \f
2141 static int total_size_of_entries __P((node *));
2142 static int number_len __P((long));
2143
2144 /* Length of a non-negative number's decimal representation. */
2145 static int
2146 number_len (num)
2147 long num;
2148 {
2149         int len = 1;
2150         while ((num /= 10) > 0)
2151                 len += 1;
2152         return len;
2153 }
2154
2155 /*
2156  * Return total number of characters that put_entries will output for
2157  * the nodes in the linked list at the right of the specified node.
2158  * This count is irrelevant with etags.el since emacs 19.34 at least,
2159  * but is still supplied for backward compatibility.
2160  */
2161 static int
2162 total_size_of_entries (np)
2163 register node *np;
2164 {
2165         register int total = 0;
2166
2167         for (; np != NULL; np = np->right)
2168                 if (np->valid)
2169                 {
2170                         total += strlen (np->regex) + 1;                /* pat\177 */
2171                         if (np->name != NULL)
2172                                 total += strlen (np->name) + 1;         /* name\001 */
2173                         total += number_len ((long) np->lno) + 1;       /* lno, */
2174                         if (np->cno != invalidcharno)                   /* cno */
2175                                 total += number_len (np->cno);
2176                         total += 1;                                     /* newline */
2177                 }
2178
2179         return total;
2180 }
2181
2182 static void
2183 put_entries (np)
2184 register node *np;
2185 {
2186         register char *sp;
2187         static fdesc *fdp = NULL;
2188
2189         if (np == NULL)
2190                 return;
2191
2192         /* Output subentries that precede this one */
2193         if (CTAGS)
2194                 put_entries (np->left);
2195
2196         /* Output this entry */
2197         if (np->valid)
2198         {
2199                 if (!CTAGS)
2200                 {
2201                         /* Etags mode */
2202                         if (fdp != np->fdp)
2203                         {
2204                                 fdp = np->fdp;
2205                                 fprintf (tagf, "\f\n%s,%d\n",
2206                                          fdp->taggedfname, total_size_of_entries (np));
2207                                 fdp->written = TRUE;
2208                         }
2209                         fputs (np->regex, tagf);
2210                         fputc ('\177', tagf);
2211                         if (np->name != NULL)
2212                         {
2213                                 fputs (np->name, tagf);
2214                                 fputc ('\001', tagf);
2215                         }
2216                         fprintf (tagf, "%d,", np->lno);
2217                         if (np->cno != invalidcharno)
2218                                 fprintf (tagf, "%ld", np->cno);
2219                         fputs ("\n", tagf);
2220                 }
2221                 else
2222                 {
2223                         /* Ctags mode */
2224                         if (np->name == NULL)
2225                                 error ("internal error: NULL name in ctags mode.", (char *)NULL);
2226
2227                         if (cxref_style)
2228                         {
2229                                 if (vgrind_style)
2230                                         fprintf (stdout, "%s %s %d\n",
2231                                                  np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2232                                 else
2233                                         fprintf (stdout, "%-16s %3d %-16s %s\n",
2234                                                  np->name, np->lno, np->fdp->taggedfname, np->regex);
2235                         }
2236                         else
2237                         {
2238                                 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2239
2240                                 if (np->is_func)
2241                                 {               /* function or #define macro with args */
2242                                         putc (searchar, tagf);
2243                                         putc ('^', tagf);
2244
2245                                         for (sp = np->regex; *sp; sp++)
2246                                         {
2247                                                 if (*sp == '\\' || *sp == searchar)
2248                                                         putc ('\\', tagf);
2249                                                 putc (*sp, tagf);
2250                                         }
2251                                         putc (searchar, tagf);
2252                                 }
2253                                 else
2254                                 {               /* anything else; text pattern inadequate */
2255                                         fprintf (tagf, "%d", np->lno);
2256                                 }
2257                                 putc ('\n', tagf);
2258                         }
2259                 }
2260         } /* if this node contains a valid tag */
2261
2262         /* Output subentries that follow this one */
2263         put_entries (np->right);
2264         if (!CTAGS)
2265                 put_entries (np->left);
2266 }
2267
2268 \f
2269 /* C extensions. */
2270 #define C_EXT   0x00fff         /* C extensions */
2271 #define C_PLAIN 0x00000         /* C */
2272 #define C_PLPL  0x00001         /* C++ */
2273 #define C_STAR  0x00003         /* C* */
2274 #define C_JAVA  0x00005         /* JAVA */
2275 #define C_AUTO  0x01000         /* C, but switch to C++ if `class' is met */
2276 #define YACC    0x10000         /* yacc file */
2277
2278 /*
2279  * The C symbol tables.
2280  */
2281 enum sym_type
2282 {
2283         st_none,
2284         st_C_objprot, st_C_objimpl, st_C_objend,
2285         st_C_gnumacro,
2286         st_C_ignore, st_C_attribute,
2287         st_C_javastruct,
2288         st_C_operator,
2289         st_C_class, st_C_template,
2290         st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2291 };
2292
2293 static unsigned int hash __P((const char *, unsigned int));
2294 static struct C_stab_entry * in_word_set __P((const char *, unsigned int));
2295 static enum sym_type C_symtype __P((char *, int, int));
2296
2297 /* Feed stuff between (but not including) %[ and %] lines to:
2298    gperf -m 5
2299    %[
2300    %compare-strncmp
2301    %enum
2302    %struct-type
2303    struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2304    %%
2305    if,                  0,                      st_C_ignore
2306    for,                 0,                      st_C_ignore
2307    while,               0,                      st_C_ignore
2308    switch,              0,                      st_C_ignore
2309    return,              0,                      st_C_ignore
2310    __attribute__,       0,                      st_C_attribute
2311    GTY,                 0,                      st_C_attribute
2312    @interface,          0,                      st_C_objprot
2313    @protocol,           0,                      st_C_objprot
2314    @implementation,     0,                      st_C_objimpl
2315    @end,                0,                      st_C_objend
2316    import,              (C_JAVA & ~C_PLPL),     st_C_ignore
2317    package,             (C_JAVA & ~C_PLPL),     st_C_ignore
2318    friend,              C_PLPL,                 st_C_ignore
2319    extends,             (C_JAVA & ~C_PLPL),     st_C_javastruct
2320    implements,          (C_JAVA & ~C_PLPL),     st_C_javastruct
2321    interface,           (C_JAVA & ~C_PLPL),     st_C_struct
2322    class,               0,                      st_C_class
2323    namespace,           C_PLPL,                 st_C_struct
2324    domain,              C_STAR,                 st_C_struct
2325    union,               0,                      st_C_struct
2326    struct,              0,                      st_C_struct
2327    extern,              0,                      st_C_extern
2328    enum,                0,                      st_C_enum
2329    typedef,             0,                      st_C_typedef
2330    define,              0,                      st_C_define
2331    undef,               0,                      st_C_define
2332    operator,            C_PLPL,                 st_C_operator
2333    template,            0,                      st_C_template
2334    # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2335    DEFUN,               0,                      st_C_gnumacro
2336    SYSCALL,             0,                      st_C_gnumacro
2337    ENTRY,               0,                      st_C_gnumacro
2338    PSEUDO,              0,                      st_C_gnumacro
2339    # These are defined inside C functions, so currently they are not met.
2340    # EXFUN used in glibc, DEFVAR_* in emacs.
2341    #EXFUN,              0,                      st_C_gnumacro
2342    #DEFVAR_,            0,                      st_C_gnumacro
2343    %]
2344    and replace lines between %< and %> with its output, then:
2345    - remove the #if characterset check
2346    - make in_word_set static and not inline. */
2347 /*%<*/
2348 /* C code produced by gperf version 3.0.1 */
2349 /* Command-line: gperf -m 5  */
2350 /* Computed positions: -k'2-3' */
2351
2352 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
2353 /* maximum key range = 33, duplicates = 0 */
2354
2355 #ifdef __GNUC__
2356 __inline
2357 #else
2358 #ifdef __cplusplus
2359 inline
2360 #endif
2361 #endif
2362 static unsigned int
2363 hash (str, len)
2364 register const char *str;
2365 register unsigned int len;
2366 {
2367         static unsigned char asso_values[] =
2368                 {
2369                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2370                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2371                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2372                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2373                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2374                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2375                         35, 35, 35, 35, 35, 35, 35, 35, 35,  3,
2376                         26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2377                         35, 35, 35, 24,  0, 35, 35, 35, 35,  0,
2378                         35, 35, 35, 35, 35,  1, 35, 16, 35,  6,
2379                         23,  0,  0, 35, 22,  0, 35, 35,  5,  0,
2380                         0, 15,  1, 35,  6, 35,  8, 19, 35, 16,
2381                         4,  5, 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, 35,
2384                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2385                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2386                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2387                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2388                         35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2389                         35, 35, 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
2395                 };
2396         register int hval = len;
2397
2398         switch (hval)
2399         {
2400         default:
2401                 hval += asso_values[(unsigned char)str[2]];
2402                 /*FALLTHROUGH*/
2403         case 2:
2404                 hval += asso_values[(unsigned char)str[1]];
2405                 break;
2406         }
2407         return hval;
2408 }
2409
2410 static struct C_stab_entry *
2411 in_word_set (str, len)
2412 register const char *str;
2413 register unsigned int len;
2414 {
2415         enum
2416         {
2417                 TOTAL_KEYWORDS = 33,
2418                 MIN_WORD_LENGTH = 2,
2419                 MAX_WORD_LENGTH = 15,
2420                 MIN_HASH_VALUE = 2,
2421                 MAX_HASH_VALUE = 34
2422         };
2423
2424         static struct C_stab_entry wordlist[] =
2425                 {
2426                         {""}, {""},
2427                         {"if",          0,                      st_C_ignore},
2428                         {"GTY",           0,                      st_C_attribute},
2429                         {"@end",                0,                      st_C_objend},
2430                         {"union",               0,                      st_C_struct},
2431                         {"define",              0,                      st_C_define},
2432                         {"import",              (C_JAVA & ~C_PLPL),     st_C_ignore},
2433                         {"template",    0,                      st_C_template},
2434                         {"operator",    C_PLPL,                 st_C_operator},
2435                         {"@interface",  0,                      st_C_objprot},
2436                         {"implements",  (C_JAVA & ~C_PLPL),     st_C_javastruct},
2437                         {"friend",              C_PLPL,                 st_C_ignore},
2438                         {"typedef",     0,                      st_C_typedef},
2439                         {"return",              0,                      st_C_ignore},
2440                         {"@implementation",0,                   st_C_objimpl},
2441                         {"@protocol",   0,                      st_C_objprot},
2442                         {"interface",   (C_JAVA & ~C_PLPL),     st_C_struct},
2443                         {"extern",              0,                      st_C_extern},
2444                         {"extends",     (C_JAVA & ~C_PLPL),     st_C_javastruct},
2445                         {"struct",              0,                      st_C_struct},
2446                         {"domain",              C_STAR,                 st_C_struct},
2447                         {"switch",              0,                      st_C_ignore},
2448                         {"enum",                0,                      st_C_enum},
2449                         {"for",         0,                      st_C_ignore},
2450                         {"namespace",   C_PLPL,                 st_C_struct},
2451                         {"class",               0,                      st_C_class},
2452                         {"while",               0,                      st_C_ignore},
2453                         {"undef",               0,                      st_C_define},
2454                         {"package",     (C_JAVA & ~C_PLPL),     st_C_ignore},
2455                         {"__attribute__",       0,                      st_C_attribute},
2456                         {"SYSCALL",     0,                      st_C_gnumacro},
2457                         {"ENTRY",               0,                      st_C_gnumacro},
2458                         {"PSEUDO",              0,                      st_C_gnumacro},
2459                         {"DEFUN",               0,                      st_C_gnumacro}
2460                 };
2461
2462         if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2463         {
2464                 register int key = hash (str, len);
2465
2466                 if (key <= MAX_HASH_VALUE && key >= 0)
2467                 {
2468                         register const char *s = wordlist[key].name;
2469
2470                         if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2471                                 return &wordlist[key];
2472                 }
2473         }
2474         return 0;
2475 }
2476 /*%>*/
2477
2478 static enum sym_type
2479 C_symtype (str, len, c_ext)
2480 char *str;
2481 int len;
2482 int c_ext;
2483 {
2484         register struct C_stab_entry *se = in_word_set (str, len);
2485
2486         if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2487                 return st_none;
2488         return se->type;
2489 }
2490
2491 \f
2492 /*
2493  * Ignoring __attribute__ ((list))
2494  */
2495 static bool inattribute;        /* looking at an __attribute__ construct */
2496
2497 /*
2498  * C functions and variables are recognized using a simple
2499  * finite automaton.  fvdef is its state variable.
2500  */
2501 static enum
2502 {
2503         fvnone,                 /* nothing seen */
2504         fdefunkey,                      /* Emacs DEFUN keyword seen */
2505         fdefunname,                     /* Emacs DEFUN name seen */
2506         foperator,                      /* func: operator keyword seen (cplpl) */
2507         fvnameseen,                     /* function or variable name seen */
2508         fstartlist,                     /* func: just after open parenthesis */
2509         finlist,                        /* func: in parameter list */
2510         flistseen,                      /* func: after parameter list */
2511         fignore,                        /* func: before open brace */
2512         vignore                 /* var-like: ignore until ';' */
2513 } fvdef;
2514
2515 static bool fvextern;           /* func or var: extern keyword seen; */
2516
2517 /*
2518  * typedefs are recognized using a simple finite automaton.
2519  * typdef is its state variable.
2520  */
2521 static enum
2522 {
2523         tnone,                  /* nothing seen */
2524         tkeyseen,                       /* typedef keyword seen */
2525         ttypeseen,                      /* defined type seen */
2526         tinbody,                        /* inside typedef body */
2527         tend,                           /* just before typedef tag */
2528         tignore                 /* junk after typedef tag */
2529 } typdef;
2530
2531 /*
2532  * struct-like structures (enum, struct and union) are recognized
2533  * using another simple finite automaton.  `structdef' is its state
2534  * variable.
2535  */
2536 static enum
2537 {
2538         snone,                  /* nothing seen yet,
2539                                    or in struct body if bracelev > 0 */
2540         skeyseen,                       /* struct-like keyword seen */
2541         stagseen,                       /* struct-like tag seen */
2542         scolonseen                      /* colon seen after struct-like tag */
2543 } structdef;
2544
2545 /*
2546  * When objdef is different from onone, objtag is the name of the class.
2547  */
2548 static char *objtag = "<uninited>";
2549
2550 /*
2551  * Yet another little state machine to deal with preprocessor lines.
2552  */
2553 static enum
2554 {
2555         dnone,                  /* nothing seen */
2556         dsharpseen,                     /* '#' seen as first char on line */
2557         ddefineseen,                    /* '#' and 'define' seen */
2558         dignorerest                     /* ignore rest of line */
2559 } definedef;
2560
2561 /*
2562  * State machine for Objective C protocols and implementations.
2563  * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2564  */
2565 static enum
2566 {
2567         onone,                  /* nothing seen */
2568         oprotocol,                      /* @interface or @protocol seen */
2569         oimplementation,                /* @implementations seen */
2570         otagseen,                       /* class name seen */
2571         oparenseen,                     /* parenthesis before category seen */
2572         ocatseen,                       /* category name seen */
2573         oinbody,                        /* in @implementation body */
2574         omethodsign,                    /* in @implementation body, after +/- */
2575         omethodtag,                     /* after method name */
2576         omethodcolon,                   /* after method colon */
2577         omethodparm,                    /* after method parameter */
2578         oignore                 /* wait for @end */
2579 } objdef;
2580
2581
2582 /*
2583  * Use this structure to keep info about the token read, and how it
2584  * should be tagged.  Used by the make_C_tag function to build a tag.
2585  */
2586 static struct tok
2587 {
2588         char *line;                     /* string containing the token */
2589         int offset;                     /* where the token starts in LINE */
2590         int length;                     /* token length */
2591         /*
2592           The previous members can be used to pass strings around for generic
2593           purposes.  The following ones specifically refer to creating tags.  In this
2594           case the token contained here is the pattern that will be used to create a
2595           tag.
2596         */
2597         bool valid;                     /* do not create a tag; the token should be
2598                                            invalidated whenever a state machine is
2599                                            reset prematurely */
2600         bool named;                     /* create a named tag */
2601         int lineno;                     /* source line number of tag */
2602         long linepos;                   /* source char number of tag */
2603 } token;                        /* latest token read */
2604
2605 /*
2606  * Variables and functions for dealing with nested structures.
2607  * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2608  */
2609 static void pushclass_above __P((int, char *, int));
2610 static void popclass_above __P((int));
2611 static void write_classname __P((linebuffer *, char *qualifier));
2612
2613 static struct {
2614         char **cname;                   /* nested class names */
2615         int *bracelev;          /* nested class brace level */
2616         int nl;                 /* class nesting level (elements used) */
2617         int size;                       /* length of the array */
2618 } cstack;                       /* stack for nested declaration tags */
2619 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2620 #define nestlev         (cstack.nl)
2621 /* After struct keyword or in struct body, not inside a nested function. */
2622 #define instruct        (structdef == snone && nestlev > 0              \
2623                          && bracelev == cstack.bracelev[nestlev-1] + 1)
2624
2625 static void
2626 pushclass_above (bracelev, str, len)
2627 int bracelev;
2628 char *str;
2629 int len;
2630 {
2631         int nl;
2632
2633         popclass_above (bracelev);
2634         nl = cstack.nl;
2635         if (nl >= cstack.size)
2636         {
2637                 int size = cstack.size *= 2;
2638                 xrnew (cstack.cname, size, char *);
2639                 xrnew (cstack.bracelev, size, int);
2640         }
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;
2645 }
2646
2647 static void
2648 popclass_above (bracelev)
2649 int bracelev;
2650 {
2651         int nl;
2652
2653         for (nl = cstack.nl - 1;
2654              nl >= 0 && cstack.bracelev[nl] >= bracelev;
2655              nl--)
2656         {
2657                 free (cstack.cname[nl]);
2658                 cstack.nl = nl;
2659         }
2660 }
2661
2662 static void
2663 write_classname (cn, qualifier)
2664 linebuffer *cn;
2665 char *qualifier;
2666 {
2667         int i, len;
2668         int qlen = strlen (qualifier);
2669
2670         if (cstack.nl == 0 || cstack.cname[0] == NULL)
2671         {
2672                 len = 0;
2673                 cn->len = 0;
2674                 cn->buffer[0] = '\0';
2675         }
2676         else
2677         {
2678                 len = strlen (cstack.cname[0]);
2679                 linebuffer_setlen (cn, len+1);
2680                 strncpy (cn->buffer, cstack.cname[0],len+1);
2681         }
2682         for (i = 1; i < cstack.nl; i++)
2683         {
2684                 char *s;
2685                 int slen;
2686
2687                 s = cstack.cname[i];
2688                 if (s == NULL)
2689                         continue;
2690                 slen = strlen (s);
2691                 len += slen + qlen;
2692                 linebuffer_setlen (cn, len);
2693                 strncat (cn->buffer, qualifier, qlen);
2694                 strncat (cn->buffer, s, slen);
2695         }
2696 }
2697
2698 \f
2699 static bool consider_token __P((char *, int, int, int *, int, int, bool *));
2700 static void make_C_tag __P((bool));
2701
2702 /*
2703  * consider_token ()
2704  *      checks to see if the current token is at the start of a
2705  *      function or variable, or corresponds to a typedef, or
2706  *      is a struct/union/enum tag, or #define, or an enum constant.
2707  *
2708  *      *IS_FUNC gets TRUE if the token is a function or #define macro
2709  *      with args.  C_EXTP points to which language we are looking at.
2710  *
2711  * Globals
2712  *      fvdef                   IN OUT
2713  *      structdef               IN OUT
2714  *      definedef               IN OUT
2715  *      typdef                  IN OUT
2716  *      objdef                  IN OUT
2717  */
2718
2719 static bool
2720 consider_token (str, len, c, c_extp, bracelev, parlev, is_func_or_var)
2721 register char *str;     /* IN: token pointer */
2722 register int len;               /* IN: token length */
2723 register int c;         /* IN: first char after the token */
2724 int *c_extp;            /* IN, OUT: C extensions mask */
2725 int bracelev;           /* IN: brace level */
2726 int parlev;             /* IN: parenthesis level */
2727 bool *is_func_or_var;   /* OUT: function or variable found */
2728 {
2729         /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2730            structtype is the type of the preceding struct-like keyword, and
2731            structbracelev is the brace level where it has been seen. */
2732         static enum sym_type structtype;
2733         static int structbracelev;
2734         static enum sym_type toktype;
2735
2736
2737         toktype = C_symtype (str, len, *c_extp);
2738
2739         /*
2740          * Skip __attribute__
2741          */
2742         if (toktype == st_C_attribute)
2743         {
2744                 inattribute = TRUE;
2745                 return FALSE;
2746         }
2747
2748         /*
2749          * Advance the definedef state machine.
2750          */
2751         switch (definedef)
2752         {
2753         case dnone:
2754                 /* We're not on a preprocessor line. */
2755                 if (toktype == st_C_gnumacro)
2756                 {
2757                         fvdef = fdefunkey;
2758                         return FALSE;
2759                 }
2760                 break;
2761         case dsharpseen:
2762                 if (toktype == st_C_define)
2763                 {
2764                         definedef = ddefineseen;
2765                 }
2766                 else
2767                 {
2768                         definedef = dignorerest;
2769                 }
2770                 return FALSE;
2771         case ddefineseen:
2772                 /*
2773                  * Make a tag for any macro, unless it is a constant
2774                  * and constantypedefs is FALSE.
2775                  */
2776                 definedef = dignorerest;
2777                 *is_func_or_var = (c == '(');
2778                 if (!*is_func_or_var && !constantypedefs)
2779                         return FALSE;
2780                 else
2781                         return TRUE;
2782         case dignorerest:
2783                 return FALSE;
2784         default:
2785                 error ("internal error: definedef value.", (char *)NULL);
2786         }
2787
2788         /*
2789          * Now typedefs
2790          */
2791         switch (typdef)
2792         {
2793         case tnone:
2794                 if (toktype == st_C_typedef)
2795                 {
2796                         if (typedefs)
2797                                 typdef = tkeyseen;
2798                         fvextern = FALSE;
2799                         fvdef = fvnone;
2800                         return FALSE;
2801                 }
2802                 break;
2803         case tkeyseen:
2804                 switch (toktype)
2805                 {
2806                 case st_none:
2807                 case st_C_class:
2808                 case st_C_struct:
2809                 case st_C_enum:
2810                         typdef = ttypeseen;
2811
2812                         /* all the rest */
2813                 case st_C_objprot:
2814                 case st_C_objimpl:
2815                 case st_C_objend:
2816                 case st_C_gnumacro:
2817                 case st_C_ignore:
2818                 case st_C_attribute:
2819                 case st_C_javastruct:
2820                 case st_C_operator:
2821                 case st_C_template:
2822                 case st_C_extern:
2823                 case st_C_define:
2824                 case st_C_typedef:
2825                 default:
2826                         break;
2827                 }
2828                 break;
2829         case ttypeseen:
2830                 if (structdef == snone && fvdef == fvnone)
2831                 {
2832                         fvdef = fvnameseen;
2833                         return TRUE;
2834                 }
2835                 break;
2836         case tend:
2837                 switch (toktype)
2838                 {
2839                 case st_C_class:
2840                 case st_C_struct:
2841                 case st_C_enum:
2842                         return FALSE;
2843
2844                         /* all the rest */
2845                 case st_none:
2846                 case st_C_objprot:
2847                 case st_C_objimpl:
2848                 case st_C_objend:
2849                 case st_C_gnumacro:
2850                 case st_C_ignore:
2851                 case st_C_attribute:
2852                 case st_C_javastruct:
2853                 case st_C_operator:
2854                 case st_C_template:
2855                 case st_C_extern:
2856                 case st_C_define:
2857                 case st_C_typedef:
2858                 default:
2859                         break;
2860                 }
2861                 return TRUE;
2862
2863                 /* all the rest */
2864         case tinbody:
2865         case tignore:
2866         default:
2867                 break;
2868         }
2869
2870         switch (toktype)
2871         {
2872         case st_C_javastruct:
2873                 if (structdef == stagseen)
2874                         structdef = scolonseen;
2875                 return FALSE;
2876         case st_C_template:
2877         case st_C_class:
2878                 if ((*c_extp & C_AUTO)  /* automatic detection of C++ language */
2879                     && bracelev == 0
2880                     && definedef == dnone && structdef == snone
2881                     && typdef == tnone && fvdef == fvnone)
2882                         *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2883                 if (toktype == st_C_template)
2884                         break;
2885                 /* FALLTHRU */
2886         case st_C_struct:
2887         case st_C_enum:
2888                 if (parlev == 0
2889                     && fvdef != vignore
2890                     && (typdef == tkeyseen
2891                         || (typedefs_or_cplusplus && structdef == snone)))
2892                 {
2893                         structdef = skeyseen;
2894                         structtype = toktype;
2895                         structbracelev = bracelev;
2896                         if (fvdef == fvnameseen)
2897                                 fvdef = fvnone;
2898                 }
2899                 return FALSE;
2900
2901                 /* all the rest */
2902         case st_none:
2903         case st_C_objprot:
2904         case st_C_objimpl:
2905         case st_C_objend:
2906         case st_C_gnumacro:
2907         case st_C_ignore:
2908         case st_C_attribute:
2909         case st_C_operator:
2910         case st_C_extern:
2911         case st_C_define:
2912         case st_C_typedef:
2913         default:
2914                 break;
2915         }
2916
2917         if (structdef == skeyseen)
2918         {
2919                 structdef = stagseen;
2920                 return TRUE;
2921         }
2922
2923         if (typdef != tnone)
2924                 definedef = dnone;
2925
2926         /* Detect Objective C constructs. */
2927         switch (objdef)
2928         {
2929         case onone:
2930                 switch (toktype)
2931                 {
2932                 case st_C_objprot:
2933                         objdef = oprotocol;
2934                         return FALSE;
2935                 case st_C_objimpl:
2936                         objdef = oimplementation;
2937                         return FALSE;
2938
2939                         /* all the rest */
2940                 case st_none:
2941                 case st_C_objend:
2942                 case st_C_gnumacro:
2943                 case st_C_ignore:
2944                 case st_C_attribute:
2945                 case st_C_javastruct:
2946                 case st_C_operator:
2947                 case st_C_class:
2948                 case st_C_template:
2949                 case st_C_struct:
2950                 case st_C_extern:
2951                 case st_C_enum:
2952                 case st_C_define:
2953                 case st_C_typedef:
2954                 default:
2955                         break;
2956                 }
2957                 break;
2958         case oimplementation:
2959                 /* Save the class tag for functions or variables defined inside. */
2960                 objtag = savenstr (str, len);
2961                 objdef = oinbody;
2962                 return FALSE;
2963         case oprotocol:
2964                 /* Save the class tag for categories. */
2965                 objtag = savenstr (str, len);
2966                 objdef = otagseen;
2967                 *is_func_or_var = TRUE;
2968                 return TRUE;
2969         case oparenseen:
2970                 objdef = ocatseen;
2971                 *is_func_or_var = TRUE;
2972                 return TRUE;
2973         case oinbody:
2974                 break;
2975         case omethodsign:
2976                 if (parlev == 0)
2977                 {
2978                         fvdef = fvnone;
2979                         objdef = omethodtag;
2980                         linebuffer_setlen (&token_name, len);
2981                         strncpy (token_name.buffer, str, len);
2982                         token_name.buffer[len] = '\0';
2983                         return TRUE;
2984                 }
2985                 return FALSE;
2986         case omethodcolon:
2987                 if (parlev == 0)
2988                         objdef = omethodparm;
2989                 return FALSE;
2990         case omethodparm:
2991                 if (parlev == 0)
2992                 {
2993                         fvdef = fvnone;
2994                         objdef = omethodtag;
2995                         linebuffer_setlen (&token_name, token_name.len + len);
2996                         strncat (token_name.buffer, str, len);
2997                         return TRUE;
2998                 }
2999                 return FALSE;
3000         case oignore:
3001                 if (toktype == st_C_objend)
3002                 {
3003                         /* Memory leakage here: the string pointed by objtag is
3004                            never released, because many tests would be needed to
3005                            avoid breaking on incorrect input code.  The amount of
3006                            memory leaked here is the sum of the lengths of the
3007                            class tags.
3008                            free (objtag); */
3009                         objdef = onone;
3010                 }
3011                 return FALSE;
3012
3013                 /* all the rest */
3014         case otagseen:
3015         case ocatseen:
3016         case omethodtag:
3017         default:
3018                 break;
3019         }
3020
3021         /* A function, variable or enum constant? */
3022         switch (toktype)
3023         {
3024         case st_C_extern:
3025                 fvextern = TRUE;
3026                 switch  (fvdef)
3027                 {
3028                 case finlist:
3029                 case flistseen:
3030                 case fignore:
3031                 case vignore:
3032                         break;
3033                 case fvnone:
3034                 case fdefunkey:
3035                 case fdefunname:
3036                 case foperator:
3037                 case fvnameseen:
3038                 case fstartlist:
3039                 default:
3040                         fvdef = fvnone;
3041                 }
3042                 return FALSE;
3043         case st_C_ignore:
3044                 fvextern = FALSE;
3045                 fvdef = vignore;
3046                 return FALSE;
3047         case st_C_operator:
3048                 fvdef = foperator;
3049                 *is_func_or_var = TRUE;
3050                 return TRUE;
3051         case st_none:
3052                 if (constantypedefs
3053                     && structdef == snone
3054                     && structtype == st_C_enum && bracelev > structbracelev)
3055                         return TRUE;            /* enum constant */
3056                 switch (fvdef)
3057                 {
3058                 case fdefunkey:
3059                         if (bracelev > 0)
3060                                 break;
3061                         fvdef = fdefunname;     /* GNU macro */
3062                         *is_func_or_var = TRUE;
3063                         return TRUE;
3064                 case fvnone:
3065                         switch (typdef)
3066                         {
3067                         case ttypeseen:
3068                                 return FALSE;
3069                         case tnone:
3070                                 if ((strneq (str, "asm", 3) && endtoken (str[3]))
3071                                     || (strneq (str, "__asm__", 7) && endtoken (str[7])))
3072                                 {
3073                                         fvdef = vignore;
3074                                         return FALSE;
3075                                 }
3076                                 break;
3077
3078                                 /* all the rest */
3079                         case tkeyseen:
3080                         case tinbody:
3081                         case tend:
3082                         case tignore:
3083                         default:
3084                                 break;
3085                         }
3086                         /* FALLTHRU */
3087                 case fvnameseen:
3088                         if (len >= 10 && strneq (str+len-10, "::operator", 10))
3089                         {
3090                                 if (*c_extp & C_AUTO) /* automatic detection of C++ */
3091                                         *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
3092                                 fvdef = foperator;
3093                                 *is_func_or_var = TRUE;
3094                                 return TRUE;
3095                         }
3096                         if (bracelev > 0 && !instruct)
3097                                 break;
3098                         fvdef = fvnameseen;     /* function or variable */
3099                         *is_func_or_var = TRUE;
3100                         return TRUE;
3101
3102                         /* all the rest */
3103                 case fdefunname:
3104                 case foperator:
3105                 case fstartlist:
3106                 case finlist:
3107                 case flistseen:
3108                 case fignore:
3109                 case vignore:
3110                 default:
3111                         break;
3112                 }
3113                 break;
3114
3115                 /* all the rest */
3116         case st_C_objprot:
3117         case st_C_objimpl:
3118         case st_C_objend:
3119         case st_C_gnumacro:
3120         case st_C_attribute:
3121         case st_C_javastruct:
3122         case st_C_class:
3123         case st_C_template:
3124         case st_C_struct:
3125         case st_C_enum:
3126         case st_C_define:
3127         case st_C_typedef:
3128         default:
3129                 break;
3130         }
3131
3132         return FALSE;
3133 }
3134
3135 \f
3136 /*
3137  * C_entries often keeps pointers to tokens or lines which are older than
3138  * the line currently read.  By keeping two line buffers, and switching
3139  * them at end of line, it is possible to use those pointers.
3140  */
3141 static struct
3142 {
3143         long linepos;
3144         linebuffer lb;
3145 } lbs[2];
3146
3147 #define current_lb_is_new (newndx == curndx)
3148 #define switch_line_buffers() (curndx = 1 - curndx)
3149
3150 #define curlb (lbs[curndx].lb)
3151 #define newlb (lbs[newndx].lb)
3152 #define curlinepos (lbs[curndx].linepos)
3153 #define newlinepos (lbs[newndx].linepos)
3154
3155 #define plainc ((c_ext & C_EXT) == C_PLAIN)
3156 #define cplpl (c_ext & C_PLPL)
3157 #define cjava ((c_ext & C_JAVA) == C_JAVA)
3158
3159 #define CNL_SAVE_DEFINEDEF()                    \
3160         do {                                    \
3161                 curlinepos = charno;            \
3162                 readline (&curlb, inf);         \
3163                 lp = curlb.buffer;              \
3164                 quotednl = FALSE;               \
3165                 newndx = curndx;                \
3166         } while (0)
3167
3168 #define CNL()                                           \
3169         do {                                            \
3170                 CNL_SAVE_DEFINEDEF();                   \
3171                 if (savetoken.valid)                    \
3172                 {                                       \
3173                         token = savetoken;              \
3174                         savetoken.valid = FALSE;        \
3175                 }                                       \
3176                 definedef = dnone;                      \
3177         } while (0)
3178
3179
3180 static void
3181 make_C_tag (isfun)
3182 bool isfun;
3183 {
3184         /* This function is never called when token.valid is FALSE, but
3185            we must protect against invalid input or internal errors. */
3186         if (token.valid)
3187                 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3188                           token.offset+token.length+1, token.lineno, token.linepos);
3189         else if (DEBUG)
3190         {                                 /* this branch is optimised away if !DEBUG */
3191                 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3192                           token_name.len + 17, isfun, token.line,
3193                           token.offset+token.length+1, token.lineno, token.linepos);
3194                 error ("INVALID TOKEN", NULL);
3195         }
3196
3197         token.valid = FALSE;
3198 }
3199
3200
3201 /*
3202  * C_entries ()
3203  *      This routine finds functions, variables, typedefs,
3204  *      #define's, enum constants and struct/union/enum definitions in
3205  *      C syntax and adds them to the list.
3206  */
3207 static void
3208 C_entries (c_ext, inf)
3209 int c_ext;                      /* extension of C */
3210 FILE *inf;                      /* input file */
3211 {
3212         register char c;                /* latest char read; '\0' for end of line */
3213         register char *lp;              /* pointer one beyond the character `c' */
3214         int curndx, newndx;             /* indices for current and new lb */
3215         register int tokoff;            /* offset in line of start of current token */
3216         register int toklen;            /* length of current token */
3217         char *qualifier;                /* string used to qualify names */
3218         int qlen;                       /* length of qualifier */
3219         int bracelev;                   /* current brace level */
3220         int bracketlev;         /* current bracket level */
3221         int parlev;                     /* current parenthesis level */
3222         int attrparlev;         /* __attribute__ parenthesis level */
3223         int templatelev;                /* current template level */
3224         int typdefbracelev;             /* bracelev where a typedef struct body begun */
3225         bool incomm, inquote, inchar, quotednl, midtoken;
3226         bool yacc_rules;                /* in the rules part of a yacc file */
3227         struct tok savetoken = {0};     /* token saved during preprocessor handling */
3228
3229
3230         linebuffer_init (&lbs[0].lb);
3231         linebuffer_init (&lbs[1].lb);
3232         if (cstack.size == 0)
3233         {
3234                 cstack.size = (DEBUG) ? 1 : 4;
3235                 cstack.nl = 0;
3236                 cstack.cname = xnew (cstack.size, char *);
3237                 cstack.bracelev = xnew (cstack.size, int);
3238         }
3239
3240         tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3241         curndx = newndx = 0;
3242         lp = curlb.buffer;
3243         *lp = 0;
3244
3245         fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3246         structdef = snone; definedef = dnone; objdef = onone;
3247         yacc_rules = FALSE;
3248         midtoken = inquote = inchar = incomm = quotednl = FALSE;
3249         token.valid = savetoken.valid = FALSE;
3250         bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3251         if (cjava)
3252         { qualifier = "."; qlen = 1; }
3253         else
3254         { qualifier = "::"; qlen = 2; }
3255
3256
3257         while (!feof (inf))
3258         {
3259                 c = *lp++;
3260                 if (c == '\\')
3261                 {
3262                         /* If we are at the end of the line, the next character is a
3263                            '\0'; do not skip it, because it is what tells us
3264                            to read the next line.  */
3265                         if (*lp == '\0')
3266                         {
3267                                 quotednl = TRUE;
3268                                 continue;
3269                         }
3270                         lp++;
3271                         c = ' ';
3272                 }
3273                 else if (incomm)
3274                 {
3275                         switch (c)
3276                         {
3277                         case '*':
3278                                 if (*lp == '/')
3279                                 {
3280                                         c = *lp++;
3281                                         incomm = FALSE;
3282                                 }
3283                                 break;
3284                         case '\0':
3285                                 /* Newlines inside comments do not end macro definitions in
3286                                    traditional cpp. */
3287                                 CNL_SAVE_DEFINEDEF ();
3288                                 break;
3289                         default:
3290                                 break;
3291                         }
3292                         continue;
3293                 }
3294                 else if (inquote)
3295                 {
3296                         switch (c)
3297                         {
3298                         case '"':
3299                                 inquote = FALSE;
3300                                 break;
3301                         case '\0':
3302                                 /* Newlines inside strings do not end macro definitions
3303                                    in traditional cpp, even though compilers don't
3304                                    usually accept them. */
3305                                 CNL_SAVE_DEFINEDEF ();
3306                                 break;
3307                         default:
3308                                 break;
3309                         }
3310                         continue;
3311                 }
3312                 else if (inchar)
3313                 {
3314                         switch (c)
3315                         {
3316                         case '\0':
3317                                 /* Hmmm, something went wrong. */
3318                                 CNL ();
3319                                 /* FALLTHRU */
3320                         case '\'':
3321                                 inchar = FALSE;
3322                                 break;
3323                         default:
3324                                 break;
3325                         }
3326                         continue;
3327                 }
3328                 else if (bracketlev > 0)
3329                 {
3330                         switch (c)
3331                         {
3332                         case ']':
3333                                 if (--bracketlev > 0)
3334                                         continue;
3335                                 break;
3336                         case '\0':
3337                                 CNL_SAVE_DEFINEDEF ();
3338                                 break;
3339                         default:
3340                                 break;
3341                         }
3342                         continue;
3343                 }
3344                 else switch (c)
3345                 {
3346                 case '"':
3347                         inquote = TRUE;
3348                         if (inattribute)
3349                                 break;
3350                         switch (fvdef)
3351                         {
3352                         case fdefunkey:
3353                         case fstartlist:
3354                         case finlist:
3355                         case fignore:
3356                         case vignore:
3357                                 break;
3358                         case fvnone:
3359                         case fdefunname:
3360                         case foperator:
3361                         case fvnameseen:
3362                         case flistseen:
3363                         default:
3364                                 fvextern = FALSE;
3365                                 fvdef = fvnone;
3366                         }
3367                         continue;
3368                 case '\'':
3369                         inchar = TRUE;
3370                         if (inattribute)
3371                                 break;
3372                         if (fvdef != finlist && fvdef != fignore && fvdef !=vignore)
3373                         {
3374                                 fvextern = FALSE;
3375                                 fvdef = fvnone;
3376                         }
3377                         continue;
3378                 case '/':
3379                         if (*lp == '*')
3380                         {
3381                                 incomm = TRUE;
3382                                 lp++;
3383                                 c = ' ';
3384                         }
3385                         else if (/* cplpl && */ *lp == '/')
3386                         {
3387                                 c = '\0';
3388                         }
3389                         break;
3390                 case '%':
3391                         if ((c_ext & YACC) && *lp == '%')
3392                         {
3393                                 /* Entering or exiting rules section in yacc file. */
3394                                 lp++;
3395                                 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3396                                 typdef = tnone; structdef = snone;
3397                                 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3398                                 bracelev = 0;
3399                                 yacc_rules = !yacc_rules;
3400                                 continue;
3401                         }
3402                         else
3403                                 break;
3404                 case '#':
3405                         if (definedef == dnone)
3406                         {
3407                                 char *cp;
3408                                 bool cpptoken = TRUE;
3409
3410                                 /* Look back on this line.  If all blanks, or nonblanks
3411                                    followed by an end of comment, this is a preprocessor
3412                                    token. */
3413                                 for (cp = newlb.buffer; cp < lp-1; cp++)
3414                                         if (!iswhite (*cp))
3415                                         {
3416                                                 if (*cp == '*' && *(cp+1) == '/')
3417                                                 {
3418                                                         cp++;
3419                                                         cpptoken = TRUE;
3420                                                 }
3421                                                 else
3422                                                         cpptoken = FALSE;
3423                                         }
3424                                 if (cpptoken)
3425                                         definedef = dsharpseen;
3426                         } /* if (definedef == dnone) */
3427                         continue;
3428                 case '[':
3429                         bracketlev++;
3430                         continue;
3431                 default:
3432                         break;
3433                 } /* switch (c) */
3434
3435
3436                 /* Consider token only if some involved conditions are satisfied. */
3437                 if (typdef != tignore
3438                     && definedef != dignorerest
3439                     && fvdef != finlist
3440                     && templatelev == 0
3441                     && (definedef != dnone
3442                         || structdef != scolonseen)
3443                     && !inattribute)
3444                 {
3445                         if (midtoken)
3446                         {
3447                                 if (endtoken (c))
3448                                 {
3449                                         if (c == ':' && *lp == ':' && begtoken (lp[1]))
3450                                                 /* This handles :: in the middle,
3451                                                    but not at the beginning of an identifier.
3452                                                    Also, space-separated :: is not recognised. */
3453                                         {
3454                                                 if (c_ext & C_AUTO) /* automatic detection of C++ */
3455                                                         c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3456                                                 lp += 2;
3457                                                 toklen += 2;
3458                                                 c = lp[-1];
3459                                                 goto still_in_token;
3460                                         }
3461                                         else
3462                                         {
3463                                                 bool funorvar = FALSE;
3464
3465                                                 if (yacc_rules
3466                                                     || consider_token (newlb.buffer + tokoff, toklen, c,
3467                                                                        &c_ext, bracelev, parlev,
3468                                                                        &funorvar))
3469                                                 {
3470                                                         if (fvdef == foperator)
3471                                                         {
3472                                                                 char *oldlp = lp;
3473                                                                 lp = skip_spaces (lp-1);
3474                                                                 if (*lp != '\0')
3475                                                                         lp += 1;
3476                                                                 while (*lp != '\0'
3477                                                                        && !iswhite (*lp) && *lp != '(')
3478                                                                         lp += 1;
3479                                                                 c = *lp++;
3480                                                                 toklen += lp - oldlp;
3481                                                         }
3482                                                         token.named = FALSE;
3483                                                         if (!plainc
3484                                                             && nestlev > 0 && definedef == dnone)
3485                                                                 /* in struct body */
3486                                                         {
3487                                                                 write_classname (&token_name, qualifier);
3488                                                                 linebuffer_setlen (&token_name,
3489                                                                                    token_name.len+qlen+toklen);
3490                                                                 strcat (token_name.buffer, qualifier);
3491                                                                 strncat (token_name.buffer,
3492                                                                          newlb.buffer + tokoff, toklen);
3493                                                                 token.named = TRUE;
3494                                                         }
3495                                                         else if (objdef == ocatseen)
3496                                                                 /* Objective C category */
3497                                                         {
3498                                                                 int len = strlen (objtag) + 2 + toklen;
3499                                                                 linebuffer_setlen (&token_name, len);
3500                                                                 strcpy (token_name.buffer, objtag);
3501                                                                 strcat (token_name.buffer, "(");
3502                                                                 strncat (token_name.buffer,
3503                                                                          newlb.buffer + tokoff, toklen);
3504                                                                 strcat (token_name.buffer, ")");
3505                                                                 token.named = TRUE;
3506                                                         }
3507                                                         else if (objdef == omethodtag
3508                                                                  || objdef == omethodparm)
3509                                                                 /* Objective C method */
3510                                                         {
3511                                                                 token.named = TRUE;
3512                                                         }
3513                                                         else if (fvdef == fdefunname)
3514                                                                 /* GNU DEFUN and similar macros */
3515                                                         {
3516                                                                 bool defun = (newlb.buffer[tokoff] == 'F');
3517                                                                 int off = tokoff;
3518                                                                 int len = toklen;
3519
3520                                                                 /* Rewrite the tag so that emacs lisp DEFUNs
3521                                                                    can be found by their elisp name */
3522                                                                 if (defun)
3523                                                                 {
3524                                                                         off += 1;
3525                                                                         len -= 1;
3526                                                                 }
3527                                                                 linebuffer_setlen (&token_name, len);
3528                                                                 strncpy (token_name.buffer,
3529                                                                          newlb.buffer + off, len);
3530                                                                 token_name.buffer[len] = '\0';
3531                                                                 if (defun)
3532                                                                         while (--len >= 0)
3533                                                                                 if (token_name.buffer[len] == '_')
3534                                                                                         token_name.buffer[len] = '-';
3535                                                                 token.named = defun;
3536                                                         }
3537                                                         else
3538                                                         {
3539                                                                 linebuffer_setlen (&token_name, toklen);
3540                                                                 strncpy (token_name.buffer,
3541                                                                          newlb.buffer + tokoff, toklen);
3542                                                                 token_name.buffer[toklen] = '\0';
3543                                                                 /* Name macros and members. */
3544                                                                 token.named = (structdef == stagseen
3545                                                                                || typdef == ttypeseen
3546                                                                                || typdef == tend
3547                                                                                || (funorvar
3548                                                                                    && definedef == dignorerest)
3549                                                                                || (funorvar
3550                                                                                    && definedef == dnone
3551                                                                                    && structdef == snone
3552                                                                                    && bracelev > 0));
3553                                                         }
3554                                                         token.lineno = lineno;
3555                                                         token.offset = tokoff;
3556                                                         token.length = toklen;
3557                                                         token.line = newlb.buffer;
3558                                                         token.linepos = newlinepos;
3559                                                         token.valid = TRUE;
3560
3561                                                         if (definedef == dnone
3562                                                             && (fvdef == fvnameseen
3563                                                                 || fvdef == foperator
3564                                                                 || structdef == stagseen
3565                                                                 || typdef == tend
3566                                                                 || typdef == ttypeseen
3567                                                                 || objdef != onone))
3568                                                         {
3569                                                                 if (current_lb_is_new)
3570                                                                         switch_line_buffers ();
3571                                                         }
3572                                                         else if (definedef != dnone
3573                                                                  || fvdef == fdefunname
3574                                                                  || instruct)
3575                                                                 make_C_tag (funorvar);
3576                                                 }
3577                                                 else /* not yacc and consider_token failed */
3578                                                 {
3579                                                         if (inattribute && fvdef == fignore)
3580                                                         {
3581                                                                 /* We have just met __attribute__ after a
3582                                                                    function parameter list: do not tag the
3583                                                                    function again. */
3584                                                                 fvdef = fvnone;
3585                                                         }
3586                                                 }
3587                                                 midtoken = FALSE;
3588                                         }
3589                                 } /* if (endtoken (c)) */
3590                                 else if (intoken (c))
3591                                 still_in_token:
3592                                 {
3593                                         toklen++;
3594                                         continue;
3595                                 }
3596                         } /* if (midtoken) */
3597                         else if (begtoken (c))
3598                         {
3599                                 switch (definedef)
3600                                 {
3601                                 case dnone:
3602                                         switch (fvdef)
3603                                         {
3604                                         case fstartlist:
3605                                                 /* This prevents tagging fb in
3606                                                    void (__attribute__((noreturn)) *fb) (void);
3607                                                    Fixing this is not easy and not very important. */
3608                                                 fvdef = finlist;
3609                                                 continue;
3610                                         case flistseen:
3611                                                 if (plainc || declarations)
3612                                                 {
3613                                                         make_C_tag (TRUE); /* a function */
3614                                                         fvdef = fignore;
3615                                                 }
3616                                                 break;
3617
3618                                                 /* all the rest */
3619                                         case fvnone:
3620                                         case fdefunkey:
3621                                         case fdefunname:
3622                                         case foperator:
3623                                         case fvnameseen:
3624                                         case finlist:
3625                                         case fignore:
3626                                         case vignore:
3627                                         default:
3628                                                 break;
3629                                         }
3630                                         if (structdef == stagseen && !cjava)
3631                                         {
3632                                                 popclass_above (bracelev);
3633                                                 structdef = snone;
3634                                         }
3635                                         break;
3636                                 case dsharpseen:
3637                                         savetoken = token;
3638                                         break;
3639
3640                                         /* all the rest */
3641                                 case ddefineseen:
3642                                 case dignorerest:
3643                                 default:
3644                                         break;
3645                                 }
3646                                 if (!yacc_rules || lp == newlb.buffer + 1)
3647                                 {
3648                                         tokoff = lp - 1 - newlb.buffer;
3649                                         toklen = 1;
3650                                         midtoken = TRUE;
3651                                 }
3652                                 continue;
3653                         } /* if (begtoken) */
3654                 } /* if must look at token */
3655
3656
3657                 /* Detect end of line, colon, comma, semicolon and various braces
3658                    after having handled a token.*/
3659                 switch (c)
3660                 {
3661                 case ':':
3662                         if (inattribute)
3663                                 break;
3664                         if (yacc_rules && token.offset == 0 && token.valid)
3665                         {
3666                                 make_C_tag (FALSE); /* a yacc function */
3667                                 break;
3668                         }
3669                         if (definedef != dnone)
3670                                 break;
3671                         switch (objdef)
3672                         {
3673                         case  otagseen:
3674                                 objdef = oignore;
3675                                 make_C_tag (TRUE); /* an Objective C class */
3676                                 break;
3677                         case omethodtag:
3678                         case omethodparm:
3679                                 objdef = omethodcolon;
3680                                 linebuffer_setlen (&token_name, token_name.len + 1);
3681                                 strcat (token_name.buffer, ":");
3682                                 break;
3683
3684                                 /* all the rest */
3685                         case onone:
3686                         case oprotocol:
3687                         case oimplementation:
3688                         case oparenseen:
3689                         case ocatseen:
3690                         case oinbody:
3691                         case omethodsign:
3692                         case omethodcolon:
3693                         case oignore:
3694                         default:
3695                                 break;
3696                         }
3697                         if (structdef == stagseen)
3698                         {
3699                                 structdef = scolonseen;
3700                                 break;
3701                         }
3702                         /* Should be useless, but may be work as a safety net. */
3703                         if (cplpl && fvdef == flistseen)
3704                         {
3705                                 make_C_tag (TRUE); /* a function */
3706                                 fvdef = fignore;
3707                                 break;
3708                         }
3709                         break;
3710                 case ';':
3711                         if (definedef != dnone || inattribute)
3712                                 break;
3713                         switch (typdef)
3714                         {
3715                         case tend:
3716                         case ttypeseen:
3717                                 make_C_tag (FALSE); /* a typedef */
3718                                 typdef = tnone;
3719                                 fvdef = fvnone;
3720                                 break;
3721                         case tnone:
3722                         case tinbody:
3723                         case tignore:
3724                                 switch (fvdef)
3725                                 {
3726                                 case fignore:
3727                                         if (typdef == tignore || cplpl)
3728                                                 fvdef = fvnone;
3729                                         break;
3730                                 case fvnameseen:
3731                                         if ((globals && bracelev == 0 && (!fvextern || declarations))
3732                                             || (members && instruct))
3733                                                 make_C_tag (FALSE); /* a variable */
3734                                         fvextern = FALSE;
3735                                         fvdef = fvnone;
3736                                         token.valid = FALSE;
3737                                         break;
3738                                 case flistseen:
3739                                         if ((declarations
3740                                              && (cplpl || !instruct)
3741                                              && (typdef == tnone || (typdef != tignore && instruct)))
3742                                             || (members
3743                                                 && plainc && instruct))
3744                                                 make_C_tag (TRUE);  /* a function */
3745                                         /* FALLTHRU */
3746                                 case fvnone:
3747                                 case fdefunkey:
3748                                 case fdefunname:
3749                                 case foperator:
3750                                 case fstartlist:
3751                                 case finlist:
3752                                 case vignore:
3753                                 default:
3754                                         fvextern = FALSE;
3755                                         fvdef = fvnone;
3756                                         if (declarations
3757                                             && cplpl && structdef == stagseen)
3758                                                 make_C_tag (FALSE);     /* forward declaration */
3759                                         else
3760                                                 token.valid = FALSE;
3761                                 } /* switch (fvdef) */
3762                                 /* FALLTHRU */
3763                         case tkeyseen:
3764                         default:
3765                                 if (!instruct)
3766                                         typdef = tnone;
3767                         }
3768                         if (structdef == stagseen)
3769                                 structdef = snone;
3770                         break;
3771                 case ',':
3772                         if (definedef != dnone || inattribute)
3773                                 break;
3774                         switch (objdef)
3775                         {
3776                         case omethodtag:
3777                         case omethodparm:
3778                                 make_C_tag (TRUE); /* an Objective C method */
3779                                 objdef = oinbody;
3780                                 break;
3781
3782                                 /* all the rest */
3783                         case onone:
3784                         case oprotocol:
3785                         case oimplementation:
3786                         case otagseen:
3787                         case oparenseen:
3788                         case ocatseen:
3789                         case oinbody:
3790                         case omethodsign:
3791                         case omethodcolon:
3792                         case oignore:
3793                         default:
3794                                 break;
3795                         }
3796                         switch (fvdef)
3797                         {
3798                         case fdefunkey:
3799                         case foperator:
3800                         case fstartlist:
3801                         case finlist:
3802                         case fignore:
3803                         case vignore:
3804                                 break;
3805                         case fdefunname:
3806                                 fvdef = fignore;
3807                                 break;
3808                         case fvnameseen:
3809                                 if (parlev == 0
3810                                     && ((globals
3811                                          && bracelev == 0
3812                                          && templatelev == 0
3813                                          && (!fvextern || declarations))
3814                                         || (members && instruct)))
3815                                         make_C_tag (FALSE); /* a variable */
3816                                 break;
3817                         case flistseen:
3818                                 if ((declarations && typdef == tnone && !instruct)
3819                                     || (members && typdef != tignore && instruct))
3820                                 {
3821                                         make_C_tag (TRUE); /* a function */
3822                                         fvdef = fvnameseen;
3823                                 }
3824                                 else if (!declarations)
3825                                         fvdef = fvnone;
3826                                 token.valid = FALSE;
3827                                 break;
3828                         case fvnone:
3829                         default:
3830                                 fvdef = fvnone;
3831                         }
3832                         if (structdef == stagseen)
3833                                 structdef = snone;
3834                         break;
3835                 case ']':
3836                         if (definedef != dnone || inattribute)
3837                                 break;
3838                         if (structdef == stagseen)
3839                                 structdef = snone;
3840                         switch (typdef)
3841                         {
3842                         case ttypeseen:
3843                         case tend:
3844                                 typdef = tignore;
3845                                 make_C_tag (FALSE);     /* a typedef */
3846                                 break;
3847                         case tnone:
3848                         case tinbody:
3849                                 switch (fvdef)
3850                                 {
3851                                 case foperator:
3852                                 case finlist:
3853                                 case fignore:
3854                                 case vignore:
3855                                         break;
3856                                 case fvnameseen:
3857                                         if ((members && bracelev == 1)
3858                                             || (globals && bracelev == 0
3859                                                 && (!fvextern || declarations)))
3860                                                 make_C_tag (FALSE); /* a variable */
3861                                         /* FALLTHRU */
3862                                 case fvnone:
3863                                 case fdefunkey:
3864                                 case fdefunname:
3865                                 case fstartlist:
3866                                 case flistseen:
3867                                 default:
3868                                         fvdef = fvnone;
3869                                 }
3870                                 break;
3871
3872                                 /* all the rest */
3873                         case tkeyseen:
3874                         case tignore:
3875                         default:
3876                                 break;
3877                         }
3878                         break;
3879                 case '(':
3880                         if (inattribute)
3881                         {
3882                                 attrparlev++;
3883                                 break;
3884                         }
3885                         if (definedef != dnone)
3886                                 break;
3887                         if (objdef == otagseen && parlev == 0)
3888                                 objdef = oparenseen;
3889                         switch (fvdef)
3890                         {
3891                         case fvnameseen:
3892                                 if (typdef == ttypeseen
3893                                     && *lp != '*'
3894                                     && !instruct)
3895                                 {
3896                                         /* This handles constructs like:
3897                                            typedef void OperatorFun (int fun); */
3898                                         make_C_tag (FALSE);
3899                                         typdef = tignore;
3900                                         fvdef = fignore;
3901                                         break;
3902                                 }
3903                                 /* FALLTHRU */
3904                         case foperator:
3905                                 fvdef = fstartlist;
3906                                 break;
3907                         case flistseen:
3908                                 fvdef = finlist;
3909                                 break;
3910
3911                                 /* all the rest */
3912                         case fvnone:
3913                         case fdefunkey:
3914                         case fdefunname:
3915                         case fstartlist:
3916                         case finlist:
3917                         case fignore:
3918                         case vignore:
3919                         default:
3920                                 break;
3921                         }
3922                         parlev++;
3923                         break;
3924                 case ')':
3925                         if (inattribute)
3926                         {
3927                                 if (--attrparlev == 0)
3928                                         inattribute = FALSE;
3929                                 break;
3930                         }
3931                         if (definedef != dnone)
3932                                 break;
3933                         if (objdef == ocatseen && parlev == 1)
3934                         {
3935                                 make_C_tag (TRUE); /* an Objective C category */
3936                                 objdef = oignore;
3937                         }
3938                         if (--parlev == 0)
3939                         {
3940                                 switch (fvdef)
3941                                 {
3942                                 case fstartlist:
3943                                 case finlist:
3944                                         fvdef = flistseen;
3945                                         break;
3946
3947                                         /* all the rest */
3948                                 case fvnone:
3949                                 case fdefunkey:
3950                                 case fdefunname:
3951                                 case foperator:
3952                                 case fvnameseen:
3953                                 case flistseen:
3954                                 case fignore:
3955                                 case vignore:
3956                                 default:
3957                                         break;
3958                                 }
3959                                 if (!instruct
3960                                     && (typdef == tend
3961                                         || typdef == ttypeseen))
3962                                 {
3963                                         typdef = tignore;
3964                                         make_C_tag (FALSE); /* a typedef */
3965                                 }
3966                         }
3967                         else if (parlev < 0)    /* can happen due to ill-conceived #if's. */
3968                                 parlev = 0;
3969                         break;
3970                 case '{':
3971                         if (definedef != dnone)
3972                                 break;
3973                         if (typdef == ttypeseen)
3974                         {
3975                                 /* Whenever typdef is set to tinbody (currently only
3976                                    here), typdefbracelev should be set to bracelev. */
3977                                 typdef = tinbody;
3978                                 typdefbracelev = bracelev;
3979                         }
3980                         switch (fvdef)
3981                         {
3982                         case flistseen:
3983                                 make_C_tag (TRUE);    /* a function */
3984                                 /* FALLTHRU */
3985                         case fignore:
3986                                 fvdef = fvnone;
3987                                 break;
3988                         case fvnone:
3989                                 switch (objdef)
3990                                 {
3991                                 case otagseen:
3992                                         make_C_tag (TRUE); /* an Objective C class */
3993                                         objdef = oignore;
3994                                         break;
3995                                 case omethodtag:
3996                                 case omethodparm:
3997                                         make_C_tag (TRUE); /* an Objective C method */
3998                                         objdef = oinbody;
3999                                         break;
4000                                 case onone:
4001                                 case oprotocol:
4002                                 case oimplementation:
4003                                 case oparenseen:
4004                                 case ocatseen:
4005                                 case oinbody:
4006                                 case omethodsign:
4007                                 case omethodcolon:
4008                                 case oignore:
4009                                 default:
4010                                         /* Neutralize `extern "C" {' grot. */
4011                                         if (bracelev == 0 && structdef == snone && nestlev == 0
4012                                             && typdef == tnone)
4013                                                 bracelev = -1;
4014                                 }
4015                                 break;
4016
4017                                 /* all the rest */
4018                         case fdefunkey:
4019                         case fdefunname:
4020                         case foperator:
4021                         case fvnameseen:
4022                         case fstartlist:
4023                         case finlist:
4024                         case vignore:
4025                         default:
4026                                 break;
4027                         }
4028                         switch (structdef)
4029                         {
4030                         case skeyseen:     /* unnamed struct */
4031                                 pushclass_above (bracelev, NULL, 0);
4032                                 structdef = snone;
4033                                 break;
4034                         case stagseen:     /* named struct or enum */
4035                         case scolonseen:           /* a class */
4036                                 pushclass_above (bracelev,token.line+token.offset, token.length);
4037                                 structdef = snone;
4038                                 make_C_tag (FALSE);  /* a struct or enum */
4039                                 break;
4040
4041                                 /* all the rest */
4042                         case snone:
4043                         default:
4044                                 break;
4045                         }
4046                         bracelev += 1;
4047                         break;
4048                 case '*':
4049                         if (definedef != dnone)
4050                                 break;
4051                         if (fvdef == fstartlist)
4052                         {
4053                                 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
4054                                 token.valid = FALSE;
4055                         }
4056                         break;
4057                 case '}':
4058                         if (definedef != dnone)
4059                                 break;
4060                         bracelev -= 1;
4061                         if (!ignoreindent && lp == newlb.buffer + 1)
4062                         {
4063                                 if (bracelev != 0)
4064                                         token.valid = FALSE; /* unexpected value, token unreliable */
4065                                 bracelev = 0;   /* reset brace level if first column */
4066                                 parlev = 0;     /* also reset paren level, just in case... */
4067                         }
4068                         else if (bracelev < 0)
4069                         {
4070                                 token.valid = FALSE; /* something gone amiss, token unreliable */
4071                                 bracelev = 0;
4072                         }
4073                         if (bracelev == 0 && fvdef == vignore)
4074                                 fvdef = fvnone;         /* end of function */
4075                         popclass_above (bracelev);
4076                         structdef = snone;
4077                         /* Only if typdef == tinbody is typdefbracelev significant. */
4078                         if (typdef == tinbody && bracelev <= typdefbracelev)
4079                         {
4080                                 assert (bracelev == typdefbracelev);
4081                                 typdef = tend;
4082                         }
4083                         break;
4084                 case '=':
4085                         if (definedef != dnone)
4086                                 break;
4087                         switch (fvdef)
4088                         {
4089                         case foperator:
4090                         case finlist:
4091                         case fignore:
4092                         case vignore:
4093                                 break;
4094                         case fvnameseen:
4095                                 if ((members && bracelev == 1)
4096                                     || (globals && bracelev == 0 && (!fvextern || declarations)))
4097                                         make_C_tag (FALSE); /* a variable */
4098                                 /* FALLTHRU */
4099                         case fvnone:
4100                         case fdefunkey:
4101                         case fdefunname:
4102                         case fstartlist:
4103                         case flistseen:
4104                         default:
4105                                 fvdef = vignore;
4106                         }
4107                         break;
4108                 case '<':
4109                         if (cplpl
4110                             && (structdef == stagseen || fvdef == fvnameseen))
4111                         {
4112                                 templatelev++;
4113                                 break;
4114                         }
4115                         goto resetfvdef;
4116                 case '>':
4117                         if (templatelev > 0)
4118                         {
4119                                 templatelev--;
4120                                 break;
4121                         }
4122                         goto resetfvdef;
4123                 case '+':
4124                 case '-':
4125                         if (objdef == oinbody && bracelev == 0)
4126                         {
4127                                 objdef = omethodsign;
4128                                 break;
4129                         }
4130                         /* FALLTHRU */
4131                 resetfvdef:
4132                 case '#': case '~': case '&': case '%': case '/':
4133                 case '|': case '^': case '!': case '.': case '?':
4134                         if (definedef != dnone)
4135                                 break;
4136                         /* These surely cannot follow a function tag in C. */
4137                         switch (fvdef)
4138                         {
4139                         case foperator:
4140                         case finlist:
4141                         case fignore:
4142                         case vignore:
4143                                 break;
4144                         case fvnone:
4145                         case fdefunkey:
4146                         case fdefunname:
4147                         case fvnameseen:
4148                         case fstartlist:
4149                         case flistseen:
4150                         default:
4151                                 fvdef = fvnone;
4152                         }
4153                         break;
4154                 case '\0':
4155                         if (objdef == otagseen)
4156                         {
4157                                 make_C_tag (TRUE); /* an Objective C class */
4158                                 objdef = oignore;
4159                         }
4160                         /* If a macro spans multiple lines don't reset its state. */
4161                         if (quotednl)
4162                                 CNL_SAVE_DEFINEDEF ();
4163                         else
4164                                 CNL ();
4165                         break;
4166                 default:
4167                         break;
4168                 } /* switch (c) */
4169
4170         } /* while not eof */
4171
4172         free (lbs[0].lb.buffer);
4173         free (lbs[1].lb.buffer);
4174 }
4175
4176 /*
4177  * Process either a C++ file or a C file depending on the setting
4178  * of a global flag.
4179  */
4180 static void
4181 default_C_entries (inf)
4182 FILE *inf;
4183 {
4184         C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
4185 }
4186
4187 /* Always do plain C. */
4188 static void
4189 plain_C_entries (inf)
4190 FILE *inf;
4191 {
4192         C_entries (0, inf);
4193 }
4194
4195 /* Always do C++. */
4196 static void
4197 Cplusplus_entries (inf)
4198 FILE *inf;
4199 {
4200         C_entries (C_PLPL, inf);
4201 }
4202
4203 /* Always do Java. */
4204 static void
4205 Cjava_entries (inf)
4206 FILE *inf;
4207 {
4208         C_entries (C_JAVA, inf);
4209 }
4210
4211 /* Always do C*. */
4212 static void
4213 Cstar_entries (inf)
4214 FILE *inf;
4215 {
4216         C_entries (C_STAR, inf);
4217 }
4218
4219 /* Always do Yacc. */
4220 static void
4221 Yacc_entries (inf)
4222 FILE *inf;
4223 {
4224         C_entries (YACC, inf);
4225 }
4226
4227 \f
4228 /* Useful macros. */
4229 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer)    \
4230         for (;                  /* loop initialization */               \
4231              !feof (file_pointer)       /* loop test */                 \
4232                      &&                 /* instructions at start of loop */ \
4233                      (readline (&line_buffer, file_pointer),            \
4234                       char_pointer = line_buffer.buffer,                \
4235                       TRUE);                                            \
4236                 )
4237
4238 #define LOOKING_AT(cp, kw)  /* kw is the keyword, a literal string */   \
4239         ((assert("" kw), TRUE)   /* syntax error if not a literal string */ \
4240          && strneq ((cp), kw, sizeof(kw)-1)             /* cp points at kw */ \
4241          && notinname ((cp)[sizeof(kw)-1])              /* end of kw */ \
4242          && ((cp) = skip_spaces((cp)+sizeof(kw)-1)))    /* skip spaces */
4243
4244 /* Similar to LOOKING_AT but does not use notinname, does not skip */
4245 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
4246         ((assert("" kw), TRUE)     /* syntax error if not a literal string */ \
4247          && strncaseeq ((cp), kw, sizeof(kw)-1) /* cp points at kw */   \
4248          && ((cp) += sizeof(kw)-1))                     /* skip spaces */
4249
4250 /*
4251  * Read a file, but do no processing.  This is used to do regexp
4252  * matching on files that have no language defined.
4253  */
4254 static void
4255 just_read_file (inf)
4256 FILE *inf;
4257 {
4258         register char *dummy;
4259
4260         LOOP_ON_INPUT_LINES (inf, lb, dummy)
4261                 continue;
4262 }
4263
4264 \f
4265 /* Fortran parsing */
4266
4267 static void F_takeprec __P((void));
4268 static void F_getit __P((FILE *));
4269
4270 static void
4271 F_takeprec ()
4272 {
4273         dbp = skip_spaces (dbp);
4274         if (*dbp != '*')
4275                 return;
4276         dbp++;
4277         dbp = skip_spaces (dbp);
4278         if (strneq (dbp, "(*)", 3))
4279         {
4280                 dbp += 3;
4281                 return;
4282         }
4283         if (!ISDIGIT (*dbp))
4284         {
4285                 --dbp;                  /* force failure */
4286                 return;
4287         }
4288         do
4289                 dbp++;
4290         while (ISDIGIT (*dbp));
4291 }
4292
4293 static void
4294 F_getit (inf)
4295 FILE *inf;
4296 {
4297         register char *cp;
4298
4299         dbp = skip_spaces (dbp);
4300         if (*dbp == '\0')
4301         {
4302                 readline (&lb, inf);
4303                 dbp = lb.buffer;
4304                 if (dbp[5] != '&')
4305                         return;
4306                 dbp += 6;
4307                 dbp = skip_spaces (dbp);
4308         }
4309         if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
4310                 return;
4311         for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
4312                 continue;
4313         make_tag (dbp, cp-dbp, TRUE,
4314                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4315 }
4316
4317
4318 static void
4319 Fortran_functions (inf)
4320 FILE *inf;
4321 {
4322         LOOP_ON_INPUT_LINES (inf, lb, dbp)
4323         {
4324                 if (*dbp == '%')
4325                         dbp++;                  /* Ratfor escape to fortran */
4326                 dbp = skip_spaces (dbp);
4327                 if (*dbp == '\0')
4328                         continue;
4329                 switch (lowcase (*dbp))
4330                 {
4331                 case 'i':
4332                         if (nocase_tail ("integer"))
4333                                 F_takeprec ();
4334                         break;
4335                 case 'r':
4336                         if (nocase_tail ("real"))
4337                                 F_takeprec ();
4338                         break;
4339                 case 'l':
4340                         if (nocase_tail ("logical"))
4341                                 F_takeprec ();
4342                         break;
4343                 case 'c':
4344                         if (nocase_tail ("complex") || nocase_tail ("character"))
4345                                 F_takeprec ();
4346                         break;
4347                 case 'd':
4348                         if (nocase_tail ("double"))
4349                         {
4350                                 dbp = skip_spaces (dbp);
4351                                 if (*dbp == '\0')
4352                                         continue;
4353                                 if (nocase_tail ("precision"))
4354                                         break;
4355                                 continue;
4356                         }
4357                         break;
4358                 default:
4359                         break;
4360                 }
4361                 dbp = skip_spaces (dbp);
4362                 if (*dbp == '\0')
4363                         continue;
4364                 switch (lowcase (*dbp))
4365                 {
4366                 case 'f':
4367                         if (nocase_tail ("function"))
4368                                 F_getit (inf);
4369                         continue;
4370                 case 's':
4371                         if (nocase_tail ("subroutine"))
4372                                 F_getit (inf);
4373                         continue;
4374                 case 'e':
4375                         if (nocase_tail ("entry"))
4376                                 F_getit (inf);
4377                         continue;
4378                 case 'b':
4379                         if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4380                         {
4381                                 dbp = skip_spaces (dbp);
4382                                 if (*dbp == '\0')       /* assume un-named */
4383                                         make_tag ("blockdata", 9, TRUE,
4384                                                   lb.buffer, dbp - lb.buffer, lineno, linecharno);
4385                                 else
4386                                         F_getit (inf);  /* look for name */
4387                         }
4388                         continue;
4389                 default:
4390                         break;
4391                 }
4392         }
4393 }
4394
4395 \f
4396 /*
4397  * Ada parsing
4398  * Original code by
4399  * Philippe Waroquiers (1998)
4400  */
4401
4402 static void Ada_getit __P((FILE *, char *));
4403
4404 /* Once we are positioned after an "interesting" keyword, let's get
4405    the real tag value necessary. */
4406 static void
4407 Ada_getit (inf, name_qualifier)
4408 FILE *inf;
4409 char *name_qualifier;
4410 {
4411         register char *cp;
4412         char *name;
4413         char c;
4414
4415         while (!feof (inf))
4416         {
4417                 dbp = skip_spaces (dbp);
4418                 if (*dbp == '\0'
4419                     || (dbp[0] == '-' && dbp[1] == '-'))
4420                 {
4421                         readline (&lb, inf);
4422                         dbp = lb.buffer;
4423                 }
4424                 switch (lowcase(*dbp))
4425                 {
4426                 case 'b':
4427                         if (nocase_tail ("body"))
4428                         {
4429                                 /* Skipping body of   procedure body   or   package body or ....
4430                                    resetting qualifier to body instead of spec. */
4431                                 name_qualifier = "/b";
4432                                 continue;
4433                         }
4434                         break;
4435                 case 't':
4436                         /* Skipping type of   task type   or   protected type ... */
4437                         if (nocase_tail ("type"))
4438                                 continue;
4439                         break;
4440                 default:
4441                         break;
4442                 }
4443                 if (*dbp == '"')
4444                 {
4445                         dbp += 1;
4446                         for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4447                                 continue;
4448                 }
4449                 else
4450                 {
4451                         dbp = skip_spaces (dbp);
4452                         for (cp = dbp;
4453                              (*cp != '\0'
4454                               && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4455                              cp++)
4456                                 continue;
4457                         if (cp == dbp)
4458                                 return;
4459                 }
4460                 c = *cp;
4461                 *cp = '\0';
4462                 name = concat (dbp, name_qualifier, "");
4463                 *cp = c;
4464                 make_tag (name, strlen (name), TRUE,
4465                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4466                 free (name);
4467                 if (c == '"')
4468                         dbp = cp + 1;
4469                 return;
4470         }
4471 }
4472
4473 static void
4474 Ada_funcs (inf)
4475 FILE *inf;
4476 {
4477         bool inquote = FALSE;
4478         bool skip_till_semicolumn = FALSE;
4479
4480         LOOP_ON_INPUT_LINES (inf, lb, dbp)
4481         {
4482                 while (*dbp != '\0')
4483                 {
4484                         /* Skip a string i.e. "abcd". */
4485                         if (inquote || (*dbp == '"'))
4486                         {
4487                                 dbp = etags_strchr ((inquote) ? dbp : dbp+1, '"');
4488                                 if (dbp != NULL)
4489                                 {
4490                                         inquote = FALSE;
4491                                         dbp += 1;
4492                                         continue;       /* advance char */
4493                                 }
4494                                 else
4495                                 {
4496                                         inquote = TRUE;
4497                                         break;  /* advance line */
4498                                 }
4499                         }
4500
4501                         /* Skip comments. */
4502                         if (dbp[0] == '-' && dbp[1] == '-')
4503                                 break;          /* advance line */
4504
4505                         /* Skip character enclosed in single quote i.e. 'a'
4506                            and skip single quote starting an attribute i.e. 'Image. */
4507                         if (*dbp == '\'')
4508                         {
4509                                 dbp++ ;
4510                                 if (*dbp != '\0')
4511                                         dbp++;
4512                                 continue;
4513                         }
4514
4515                         if (skip_till_semicolumn)
4516                         {
4517                                 if (*dbp == ';')
4518                                         skip_till_semicolumn = FALSE;
4519                                 dbp++;
4520                                 continue;         /* advance char */
4521                         }
4522
4523                         /* Search for beginning of a token.  */
4524                         if (!begtoken (*dbp))
4525                         {
4526                                 dbp++;
4527                                 continue;               /* advance char */
4528                         }
4529
4530                         /* We are at the beginning of a token. */
4531                         switch (lowcase(*dbp))
4532                         {
4533                         case 'f':
4534                                 if (!packages_only && nocase_tail ("function"))
4535                                         Ada_getit (inf, "/f");
4536                                 else
4537                                         break;          /* from switch */
4538                                 continue;               /* advance char */
4539                         case 'p':
4540                                 if (!packages_only && nocase_tail ("procedure"))
4541                                         Ada_getit (inf, "/p");
4542                                 else if (nocase_tail ("package"))
4543                                         Ada_getit (inf, "/s");
4544                                 else if (nocase_tail ("protected")) /* protected type */
4545                                         Ada_getit (inf, "/t");
4546                                 else
4547                                         break;          /* from switch */
4548                                 continue;               /* advance char */
4549
4550                         case 'u':
4551                                 if (typedefs && !packages_only && nocase_tail ("use"))
4552                                 {
4553                                         /* when tagging types, avoid tagging  use type Pack.Typename;
4554                                            for this, we will skip everything till a ; */
4555                                         skip_till_semicolumn = TRUE;
4556                                         continue;     /* advance char */
4557                                 }
4558
4559                         case 't':
4560                                 if (!packages_only && nocase_tail ("task"))
4561                                         Ada_getit (inf, "/k");
4562                                 else if (typedefs && !packages_only && nocase_tail ("type"))
4563                                 {
4564                                         Ada_getit (inf, "/t");
4565                                         while (*dbp != '\0')
4566                                                 dbp += 1;
4567                                 }
4568                                 else
4569                                         break;          /* from switch */
4570                                 continue;               /* advance char */
4571                         default:
4572                                 break;
4573                         }
4574
4575                         /* Look for the end of the token. */
4576                         while (!endtoken (*dbp))
4577                                 dbp++;
4578
4579                 } /* advance char */
4580         } /* advance line */
4581 }
4582
4583 \f
4584 /*
4585  * Unix and microcontroller assembly tag handling
4586  * Labels:  /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4587  * Idea by Bob Weiner, Motorola Inc. (1994)
4588  */
4589 static void
4590 Asm_labels (inf)
4591 FILE *inf;
4592 {
4593         register char *cp;
4594
4595         LOOP_ON_INPUT_LINES (inf, lb, cp)
4596         {
4597                 /* If first char is alphabetic or one of [_.$], test for colon
4598                    following identifier. */
4599                 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4600                 {
4601                         /* Read past label. */
4602                         cp++;
4603                         while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4604                                 cp++;
4605                         if (*cp == ':' || iswhite (*cp))
4606                                 /* Found end of label, so copy it and add it to the table. */
4607                                 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4608                                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4609                 }
4610         }
4611 }
4612
4613 \f
4614 /*
4615  * Perl support
4616  * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4617  * Perl variable names: /^(my|local).../
4618  * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4619  * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4620  * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4621  */
4622 static void
4623 Perl_functions (inf)
4624 FILE *inf;
4625 {
4626         char *package = savestr ("main"); /* current package name */
4627         register char *cp;
4628
4629         LOOP_ON_INPUT_LINES (inf, lb, cp)
4630         {
4631                 cp = skip_spaces (cp);
4632
4633                 if (LOOKING_AT (cp, "package"))
4634                 {
4635                         free (package);
4636                         get_tag (cp, &package);
4637                 }
4638                 else if (LOOKING_AT (cp, "sub"))
4639                 {
4640                         char *pos;
4641                         char *sp = cp;
4642
4643                         while (!notinname (*cp))
4644                                 cp++;
4645                         if (cp == sp)
4646                                 continue;               /* nothing found */
4647                         if ((pos = etags_strchr (sp, ':')) != NULL
4648                             && pos < cp && pos[1] == ':')
4649                                 /* The name is already qualified. */
4650                                 make_tag (sp, cp - sp, TRUE,
4651                                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4652                         else
4653                                 /* Qualify it. */
4654                         {
4655                                 char savechar, *name;
4656
4657                                 savechar = *cp;
4658                                 *cp = '\0';
4659                                 name = concat (package, "::", sp);
4660                                 *cp = savechar;
4661                                 make_tag (name, strlen(name), TRUE,
4662                                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4663                                 free (name);
4664                         }
4665                 }
4666                 else if (globals)       /* only if we are tagging global vars */
4667                 {
4668                         /* Skip a qualifier, if any. */
4669                         bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4670                         /* After "my" or "local", but before any following paren or space. */
4671                         char *varstart = cp;
4672
4673                         if (qual                /* should this be removed?  If yes, how? */
4674                             && (*cp == '$' || *cp == '@' || *cp == '%'))
4675                         {
4676                                 varstart += 1;
4677                                 do
4678                                         cp++;
4679                                 while (ISALNUM (*cp) || *cp == '_');
4680                         }
4681                         else if (qual)
4682                         {
4683                                 /* Should be examining a variable list at this point;
4684                                    could insist on seeing an open parenthesis. */
4685                                 while (*cp != '\0' && *cp != ';' && *cp != '=' &&  *cp != ')')
4686                                         cp++;
4687                         }
4688                         else
4689                                 continue;
4690
4691                         make_tag (varstart, cp - varstart, FALSE,
4692                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4693                 }
4694         }
4695         free (package);
4696 }
4697
4698
4699 /*
4700  * Python support
4701  * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4702  * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4703  * More ideas by seb bacon <seb@jamkit.com> (2002)
4704  */
4705 static void
4706 Python_functions (inf)
4707 FILE *inf;
4708 {
4709         register char *cp;
4710
4711         LOOP_ON_INPUT_LINES (inf, lb, cp)
4712         {
4713                 cp = skip_spaces (cp);
4714                 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4715                 {
4716                         char *name = cp;
4717                         while (!notinname (*cp) && *cp != ':')
4718                                 cp++;
4719                         make_tag (name, cp - name, TRUE,
4720                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4721                 }
4722         }
4723 }
4724
4725 \f
4726 /*
4727  * PHP support
4728  * Look for:
4729  *  - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4730  *  - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4731  *  - /^[ \t]*define\(\"[^\"]+/
4732  * Only with --members:
4733  *  - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4734  * Idea by Diez B. Roggisch (2001)
4735  */
4736 static void
4737 PHP_functions (inf)
4738 FILE *inf;
4739 {
4740         register char *cp, *name;
4741         bool search_identifier = FALSE;
4742
4743         LOOP_ON_INPUT_LINES (inf, lb, cp)
4744         {
4745                 cp = skip_spaces (cp);
4746                 name = cp;
4747                 if (search_identifier
4748                     && *cp != '\0')
4749                 {
4750                         while (!notinname (*cp))
4751                                 cp++;
4752                         make_tag (name, cp - name, TRUE,
4753                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4754                         search_identifier = FALSE;
4755                 }
4756                 else if (LOOKING_AT (cp, "function"))
4757                 {
4758                         if(*cp == '&')
4759                                 cp = skip_spaces (cp+1);
4760                         if(*cp != '\0')
4761                         {
4762                                 name = cp;
4763                                 while (!notinname (*cp))
4764                                         cp++;
4765                                 make_tag (name, cp - name, TRUE,
4766                                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4767                         }
4768                         else
4769                                 search_identifier = TRUE;
4770                 }
4771                 else if (LOOKING_AT (cp, "class"))
4772                 {
4773                         if (*cp != '\0')
4774                         {
4775                                 name = cp;
4776                                 while (*cp != '\0' && !iswhite (*cp))
4777                                         cp++;
4778                                 make_tag (name, cp - name, FALSE,
4779                                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4780                         }
4781                         else
4782                                 search_identifier = TRUE;
4783                 }
4784                 else if (strneq (cp, "define", 6)
4785                          && (cp = skip_spaces (cp+6))
4786                          && *cp++ == '('
4787                          && (*cp == '"' || *cp == '\''))
4788                 {
4789                         char quote = *cp++;
4790                         name = cp;
4791                         while (*cp != quote && *cp != '\0')
4792                                 cp++;
4793                         make_tag (name, cp - name, FALSE,
4794                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4795                 }
4796                 else if (members
4797                          && LOOKING_AT (cp, "var")
4798                          && *cp == '$')
4799                 {
4800                         name = cp;
4801                         while (!notinname(*cp))
4802                                 cp++;
4803                         make_tag (name, cp - name, FALSE,
4804                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4805                 }
4806         }
4807 }
4808
4809 \f
4810 /*
4811  * Cobol tag functions
4812  * We could look for anything that could be a paragraph name.
4813  * i.e. anything that starts in column 8 is one word and ends in a full stop.
4814  * Idea by Corny de Souza (1993)
4815  */
4816 static void
4817 Cobol_paragraphs (inf)
4818 FILE *inf;
4819 {
4820         register char *bp, *ep;
4821
4822         LOOP_ON_INPUT_LINES (inf, lb, bp)
4823         {
4824                 if (lb.len < 9)
4825                         continue;
4826                 bp += 8;
4827
4828                 /* If eoln, compiler option or comment ignore whole line. */
4829                 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4830                         continue;
4831
4832                 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4833                         continue;
4834                 if (*ep++ == '.')
4835                         make_tag (bp, ep - bp, TRUE,
4836                                   lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4837         }
4838 }
4839
4840 \f
4841 /*
4842  * Makefile support
4843  * Ideas by Assar Westerlund <assar@sics.se> (2001)
4844  */
4845 static void
4846 Makefile_targets (inf)
4847 FILE *inf;
4848 {
4849         register char *bp;
4850
4851         LOOP_ON_INPUT_LINES (inf, lb, bp)
4852         {
4853                 if (*bp == '\t' || *bp == '#')
4854                         continue;
4855                 while (*bp != '\0' && *bp != '=' && *bp != ':')
4856                         bp++;
4857                 if (*bp == ':' || (globals && *bp == '='))
4858                 {
4859                         /* We should detect if there is more than one tag, but we do not.
4860                            We just skip initial and final spaces. */
4861                         char * namestart = skip_spaces (lb.buffer);
4862                         while (--bp > namestart)
4863                                 if (!notinname (*bp))
4864                                         break;
4865                         make_tag (namestart, bp - namestart + 1, TRUE,
4866                                   lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4867                 }
4868         }
4869 }
4870
4871 \f
4872 /*
4873  * Pascal parsing
4874  * Original code by Mosur K. Mohan (1989)
4875  *
4876  *  Locates tags for procedures & functions.  Doesn't do any type- or
4877  *  var-definitions.  It does look for the keyword "extern" or
4878  *  "forward" immediately following the procedure statement; if found,
4879  *  the tag is skipped.
4880  */
4881 static void
4882 Pascal_functions (inf)
4883 FILE *inf;
4884 {
4885         linebuffer tline;               /* mostly copied from C_entries */
4886         long save_lcno;
4887         int save_lineno, namelen, taglen;
4888         char c, *name;
4889
4890         bool                            /* each of these flags is TRUE if: */
4891                 incomment,                      /* point is inside a comment */
4892                 inquote,                        /* point is inside '..' string */
4893                 get_tagname,            /* point is after PROCEDURE/FUNCTION
4894                                            keyword, so next item = potential tag */
4895                 found_tag,                      /* point is after a potential tag */
4896                 inparms,                        /* point is within parameter-list */
4897                 verify_tag;                     /* point has passed the parm-list, so the
4898                                                    next token will determine whether this
4899                                                    is a FORWARD/EXTERN to be ignored, or
4900                                                    whether it is a real tag */
4901
4902         save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4903         name = NULL;                    /* keep compiler quiet */
4904         dbp = lb.buffer;
4905         *dbp = '\0';
4906         linebuffer_init (&tline);
4907
4908         incomment = inquote = FALSE;
4909         found_tag = FALSE;              /* have a proc name; check if extern */
4910         get_tagname = FALSE;            /* found "procedure" keyword         */
4911         inparms = FALSE;                /* found '(' after "proc"            */
4912         verify_tag = FALSE;             /* check if "extern" is ahead        */
4913
4914
4915         while (!feof (inf))             /* long main loop to get next char */
4916         {
4917                 c = *dbp++;
4918                 if (c == '\0')          /* if end of line */
4919                 {
4920                         readline (&lb, inf);
4921                         dbp = lb.buffer;
4922                         if (*dbp == '\0')
4923                                 continue;
4924                         if (!((found_tag && verify_tag)
4925                               || get_tagname))
4926                                 c = *dbp++;             /* only if don't need *dbp pointing
4927                                                            to the beginning of the name of
4928                                                            the procedure or function */
4929                 }
4930                 if (incomment)
4931                 {
4932                         if (c == '}')           /* within { } comments */
4933                                 incomment = FALSE;
4934                         else if (c == '*' && *dbp == ')') /* within (* *) comments */
4935                         {
4936                                 dbp++;
4937                                 incomment = FALSE;
4938                         }
4939                         continue;
4940                 }
4941                 else if (inquote)
4942                 {
4943                         if (c == '\'')
4944                                 inquote = FALSE;
4945                         continue;
4946                 }
4947                 else
4948                         switch (c)
4949                         {
4950                         case '\'':
4951                                 inquote = TRUE; /* found first quote */
4952                                 continue;
4953                         case '{':               /* found open { comment */
4954                                 incomment = TRUE;
4955                                 continue;
4956                         case '(':
4957                                 if (*dbp == '*')        /* found open (* comment */
4958                                 {
4959                                         incomment = TRUE;
4960                                         dbp++;
4961                                 }
4962                                 else if (found_tag)     /* found '(' after tag, i.e., parm-list */
4963                                         inparms = TRUE;
4964                                 continue;
4965                         case ')':               /* end of parms list */
4966                                 if (inparms)
4967                                         inparms = FALSE;
4968                                 continue;
4969                         case ';':
4970                                 if (found_tag && !inparms) /* end of proc or fn stmt */
4971                                 {
4972                                         verify_tag = TRUE;
4973                                         break;
4974                                 }
4975                                 continue;
4976                         default:
4977                                 break;
4978                         }
4979                 if (found_tag && verify_tag && (*dbp != ' '))
4980                 {
4981                         /* Check if this is an "extern" declaration. */
4982                         if (*dbp == '\0')
4983                                 continue;
4984                         if (lowcase (*dbp == 'e'))
4985                         {
4986                                 if (nocase_tail ("extern")) /* superfluous, really! */
4987                                 {
4988                                         found_tag = FALSE;
4989                                         verify_tag = FALSE;
4990                                 }
4991                         }
4992                         else if (lowcase (*dbp) == 'f')
4993                         {
4994                                 if (nocase_tail ("forward")) /* check for forward reference */
4995                                 {
4996                                         found_tag = FALSE;
4997                                         verify_tag = FALSE;
4998                                 }
4999                         }
5000                         if (found_tag && verify_tag) /* not external proc, so make tag */
5001                         {
5002                                 found_tag = FALSE;
5003                                 verify_tag = FALSE;
5004                                 make_tag (name, namelen, TRUE,
5005                                           tline.buffer, taglen, save_lineno, save_lcno);
5006                                 continue;
5007                         }
5008                 }
5009                 if (get_tagname)                /* grab name of proc or fn */
5010                 {
5011                         char *cp;
5012
5013                         if (*dbp == '\0')
5014                                 continue;
5015
5016                         /* Find block name. */
5017                         for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
5018                                 continue;
5019
5020                         /* Save all values for later tagging. */
5021                         linebuffer_setlen (&tline, lb.len);
5022                         strncpy(tline.buffer, lb.buffer, lb.len-1);
5023                         save_lineno = lineno;
5024                         save_lcno = linecharno;
5025                         name = tline.buffer + (dbp - lb.buffer);
5026                         namelen = cp - dbp;
5027                         taglen = cp - lb.buffer + 1;
5028
5029                         dbp = cp;               /* set dbp to e-o-token */
5030                         get_tagname = FALSE;
5031                         found_tag = TRUE;
5032                         continue;
5033
5034                         /* And proceed to check for "extern". */
5035                 }
5036                 else if (!incomment && !inquote && !found_tag)
5037                 {
5038                         /* Check for proc/fn keywords. */
5039                         switch (lowcase (c))
5040                         {
5041                         case 'p':
5042                                 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
5043                                         get_tagname = TRUE;
5044                                 continue;
5045                         case 'f':
5046                                 if (nocase_tail ("unction"))
5047                                         get_tagname = TRUE;
5048                                 continue;
5049                         default:
5050                                 break;
5051                         }
5052                 }
5053         } /* while not eof */
5054
5055         free (tline.buffer);
5056 }
5057
5058 \f
5059 /*
5060  * Lisp tag functions
5061  *  look for (def or (DEF, quote or QUOTE
5062  */
5063
5064 static void L_getit __P((void));
5065
5066 static void
5067 L_getit ()
5068 {
5069         if (*dbp == '\'')               /* Skip prefix quote */
5070                 dbp++;
5071         else if (*dbp == '(')
5072         {
5073                 dbp++;
5074                 /* Try to skip "(quote " */
5075                 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
5076                         /* Ok, then skip "(" before name in (defstruct (foo)) */
5077                         dbp = skip_spaces (dbp);
5078         }
5079         get_tag (dbp, NULL);
5080 }
5081
5082 static void
5083 Lisp_functions (inf)
5084 FILE *inf;
5085 {
5086         LOOP_ON_INPUT_LINES (inf, lb, dbp)
5087         {
5088                 if (dbp[0] != '(')
5089                         continue;
5090
5091                 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
5092                 {
5093                         dbp = skip_non_spaces (dbp);
5094                         dbp = skip_spaces (dbp);
5095                         L_getit ();
5096                 }
5097                 else
5098                 {
5099                         /* Check for (foo::defmumble name-defined ... */
5100                         do
5101                                 dbp++;
5102                         while (!notinname (*dbp) && *dbp != ':');
5103                         if (*dbp == ':')
5104                         {
5105                                 do
5106                                         dbp++;
5107                                 while (*dbp == ':');
5108
5109                                 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
5110                                 {
5111                                         dbp = skip_non_spaces (dbp);
5112                                         dbp = skip_spaces (dbp);
5113                                         L_getit ();
5114                                 }
5115                         }
5116                 }
5117         }
5118 }
5119
5120 \f
5121 /*
5122  * Lua script language parsing
5123  * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
5124  *
5125  *  "function" and "local function" are tags if they start at column 1.
5126  */
5127 static void
5128 Lua_functions (inf)
5129 FILE *inf;
5130 {
5131         register char *bp;
5132
5133         LOOP_ON_INPUT_LINES (inf, lb, bp)
5134         {
5135                 if (bp[0] != 'f' && bp[0] != 'l')
5136                         continue;
5137
5138                 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
5139
5140                 if (LOOKING_AT (bp, "function"))
5141                         get_tag (bp, NULL);
5142         }
5143 }
5144
5145 \f
5146 /*
5147  * Postscript tags
5148  * Just look for lines where the first character is '/'
5149  * Also look at "defineps" for PSWrap
5150  * Ideas by:
5151  *   Richard Mlynarik <mly@adoc.xerox.com> (1997)
5152  *   Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
5153  */
5154 static void
5155 PS_functions (inf)
5156 FILE *inf;
5157 {
5158         register char *bp, *ep;
5159
5160         LOOP_ON_INPUT_LINES (inf, lb, bp)
5161         {
5162                 if (bp[0] == '/')
5163                 {
5164                         for (ep = bp+1;
5165                              *ep != '\0' && *ep != ' ' && *ep != '{';
5166                              ep++)
5167                                 continue;
5168                         make_tag (bp, ep - bp, TRUE,
5169                                   lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
5170                 }
5171                 else if (LOOKING_AT (bp, "defineps"))
5172                         get_tag (bp, NULL);
5173         }
5174 }
5175
5176 \f
5177 /*
5178  * Forth tags
5179  * Ignore anything after \ followed by space or in ( )
5180  * Look for words defined by :
5181  * Look for constant, code, create, defer, value, and variable
5182  * OBP extensions:  Look for buffer:, field,
5183  * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
5184  */
5185 static void
5186 Forth_words (inf)
5187 FILE *inf;
5188 {
5189         register char *bp;
5190
5191         LOOP_ON_INPUT_LINES (inf, lb, bp)
5192                 while ((bp = skip_spaces (bp))[0] != '\0')
5193                         if (bp[0] == '\\' && iswhite(bp[1]))
5194                                 break;                  /* read next line */
5195                         else if (bp[0] == '(' && iswhite(bp[1]))
5196                                 do                      /* skip to ) or eol */
5197                                         bp++;
5198                                 while (*bp != ')' && *bp != '\0');
5199                         else if ((bp[0] == ':' && iswhite(bp[1]) && bp++)
5200                                  || LOOKING_AT_NOCASE (bp, "constant")
5201                                  || LOOKING_AT_NOCASE (bp, "code")
5202                                  || LOOKING_AT_NOCASE (bp, "create")
5203                                  || LOOKING_AT_NOCASE (bp, "defer")
5204                                  || LOOKING_AT_NOCASE (bp, "value")
5205                                  || LOOKING_AT_NOCASE (bp, "variable")
5206                                  || LOOKING_AT_NOCASE (bp, "buffer:")
5207                                  || LOOKING_AT_NOCASE (bp, "field"))
5208                                 get_tag (skip_spaces (bp), NULL); /* Yay!  A definition! */
5209                         else
5210                                 bp = skip_non_spaces (bp);
5211 }
5212
5213 \f
5214 /*
5215  * Scheme tag functions
5216  * look for (def... xyzzy
5217  *          (def... (xyzzy
5218  *          (def ... ((...(xyzzy ....
5219  *          (set! xyzzy
5220  * Original code by Ken Haase (1985?)
5221  */
5222 static void
5223 Scheme_functions (inf)
5224 FILE *inf;
5225 {
5226         register char *bp;
5227
5228         LOOP_ON_INPUT_LINES (inf, lb, bp)
5229         {
5230                 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
5231                 {
5232                         bp = skip_non_spaces (bp+4);
5233                         /* Skip over open parens and white space */
5234                         while (notinname (*bp))
5235                                 bp++;
5236                         get_tag (bp, NULL);
5237                 }
5238                 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
5239                         get_tag (bp, NULL);
5240         }
5241 }
5242
5243 \f
5244 /* Find tags in TeX and LaTeX input files.  */
5245
5246 /* TEX_toktab is a table of TeX control sequences that define tags.
5247  * Each entry records one such control sequence.
5248  *
5249  * Original code from who knows whom.
5250  * Ideas by:
5251  *   Stefan Monnier (2002)
5252  */
5253
5254 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
5255
5256 /* Default set of control sequences to put into TEX_toktab.
5257    The value of environment var TEXTAGS is prepended to this.  */
5258 static char *TEX_defenv = "\
5259 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
5260 :part:appendix:entry:index:def\
5261 :newcommand:renewcommand:newenvironment:renewenvironment";
5262
5263 static void TEX_mode __P((FILE *));
5264 static void TEX_decode_env __P((char *, char *));
5265
5266 static char TEX_esc = '\\';
5267 static char TEX_opgrp = '{';
5268 static char TEX_clgrp = '}';
5269
5270 /*
5271  * TeX/LaTeX scanning loop.
5272  */
5273 static void
5274 TeX_commands (inf)
5275 FILE *inf;
5276 {
5277         char *cp;
5278         linebuffer *key;
5279
5280         /* Select either \ or ! as escape character.  */
5281         TEX_mode (inf);
5282
5283         /* Initialize token table once from environment. */
5284         if (TEX_toktab == NULL)
5285                 TEX_decode_env ("TEXTAGS", TEX_defenv);
5286
5287         LOOP_ON_INPUT_LINES (inf, lb, cp)
5288         {
5289                 /* Look at each TEX keyword in line. */
5290                 for (;;)
5291                 {
5292                         /* Look for a TEX escape. */
5293                         while (*cp++ != TEX_esc)
5294                                 if (cp[-1] == '\0' || cp[-1] == '%')
5295                                         goto tex_next_line;
5296
5297                         for (key = TEX_toktab; key->buffer != NULL; key++)
5298                                 if (strneq (cp, key->buffer, key->len))
5299                                 {
5300                                         register char *p;
5301                                         int namelen, linelen;
5302                                         bool opgrp = FALSE;
5303
5304                                         cp = skip_spaces (cp + key->len);
5305                                         if (*cp == TEX_opgrp)
5306                                         {
5307                                                 opgrp = TRUE;
5308                                                 cp++;
5309                                         }
5310                                         for (p = cp;
5311                                              (!iswhite (*p) && *p != '#' &&
5312                                               *p != TEX_opgrp && *p != TEX_clgrp);
5313                                              p++)
5314                                                 continue;
5315                                         namelen = p - cp;
5316                                         linelen = lb.len;
5317                                         if (!opgrp || *p == TEX_clgrp)
5318                                         {
5319                                                 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
5320                                                         p++;
5321                                                 linelen = p - lb.buffer + 1;
5322                                         }
5323                                         make_tag (cp, namelen, TRUE,
5324                                                   lb.buffer, linelen, lineno, linecharno);
5325                                         goto tex_next_line; /* We only tag a line once */
5326                                 }
5327                 }
5328         tex_next_line:
5329                 ;
5330         }
5331 }
5332
5333 #define TEX_LESC '\\'
5334 #define TEX_SESC '!'
5335
5336 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5337    chars accordingly. */
5338 static void
5339 TEX_mode (inf)
5340 FILE *inf;
5341 {
5342         int c;
5343
5344         while ((c = getc (inf)) != EOF)
5345         {
5346                 /* Skip to next line if we hit the TeX comment char. */
5347                 if (c == '%')
5348                         while (c != '\n' && c != EOF)
5349                                 c = getc (inf);
5350                 else if (c == TEX_LESC || c == TEX_SESC )
5351                         break;
5352         }
5353
5354         if (c == TEX_LESC)
5355         {
5356                 TEX_esc = TEX_LESC;
5357                 TEX_opgrp = '{';
5358                 TEX_clgrp = '}';
5359         }
5360         else
5361         {
5362                 TEX_esc = TEX_SESC;
5363                 TEX_opgrp = '<';
5364                 TEX_clgrp = '>';
5365         }
5366         /* If the input file is compressed, inf is a pipe, and rewind may fail.
5367            No attempt is made to correct the situation. */
5368         rewind (inf);
5369 }
5370
5371 /* Read environment and prepend it to the default string.
5372    Build token table. */
5373 static void
5374 TEX_decode_env (evarname, defenv)
5375 char *evarname;
5376 char *defenv;
5377 {
5378         register char *env, *p;
5379         int i, len;
5380
5381         /* Append default string to environment. */
5382         env = getenv (evarname);
5383         if (!env)
5384                 env = defenv;
5385         else
5386         {
5387                 char *oldenv = env;
5388                 env = concat (oldenv, defenv, "");
5389         }
5390
5391         /* Allocate a token table */
5392         for (len = 1, p = env; p;)
5393                 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5394                         len++;
5395         TEX_toktab = xnew (len, linebuffer);
5396
5397         /* Unpack environment string into token table. Be careful about */
5398         /* zero-length strings (leading ':', "::" and trailing ':') */
5399         for (i = 0; *env != '\0';)
5400         {
5401                 p = etags_strchr (env, ':');
5402                 if (!p)                 /* End of environment string. */
5403                         p = env + strlen (env);
5404                 if (p - env > 0)
5405                 {                       /* Only non-zero strings. */
5406                         TEX_toktab[i].buffer = savenstr (env, p - env);
5407                         TEX_toktab[i].len = p - env;
5408                         i++;
5409                 }
5410                 if (*p)
5411                         env = p + 1;
5412                 else
5413                 {
5414                         TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5415                         TEX_toktab[i].len = 0;
5416                         break;
5417                 }
5418         }
5419 }
5420
5421 \f
5422 /* Texinfo support.  Dave Love, Mar. 2000.  */
5423 static void
5424 Texinfo_nodes (inf)
5425 FILE * inf;
5426 {
5427         char *cp, *start;
5428         LOOP_ON_INPUT_LINES (inf, lb, cp)
5429                 if (LOOKING_AT (cp, "@node"))
5430                 {
5431                         start = cp;
5432                         while (*cp != '\0' && *cp != ',')
5433                                 cp++;
5434                         make_tag (start, cp - start, TRUE,
5435                                   lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5436                 }
5437 }
5438
5439 \f
5440 /*
5441  * HTML support.
5442  * Contents of <title>, <h1>, <h2>, <h3> are tags.
5443  * Contents of <a name=xxx> are tags with name xxx.
5444  *
5445  * Francesco Potortì, 2002.
5446  */
5447 static void
5448 HTML_labels (inf)
5449 FILE * inf;
5450 {
5451         bool getnext = FALSE;           /* next text outside of HTML tags is a tag */
5452         bool skiptag = FALSE;           /* skip to the end of the current HTML tag */
5453         bool intag = FALSE;             /* inside an html tag, looking for ID= */
5454         bool inanchor = FALSE;  /* when INTAG, is an anchor, look for NAME= */
5455         char *end;
5456
5457
5458         linebuffer_setlen (&token_name, 0); /* no name in buffer */
5459
5460         LOOP_ON_INPUT_LINES (inf, lb, dbp)
5461                 for (;;)                        /* loop on the same line */
5462                 {
5463                         if (skiptag)            /* skip HTML tag */
5464                         {
5465                                 while (*dbp != '\0' && *dbp != '>')
5466                                         dbp++;
5467                                 if (*dbp == '>')
5468                                 {
5469                                         dbp += 1;
5470                                         skiptag = FALSE;
5471                                         continue;       /* look on the same line */
5472                                 }
5473                                 break;          /* go to next line */
5474                         }
5475
5476                         else if (intag) /* look for "name=" or "id=" */
5477                         {
5478                                 while (*dbp != '\0' && *dbp != '>'
5479                                        && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5480                                         dbp++;
5481                                 if (*dbp == '\0')
5482                                         break;          /* go to next line */
5483                                 if (*dbp == '>')
5484                                 {
5485                                         dbp += 1;
5486                                         intag = FALSE;
5487                                         continue;       /* look on the same line */
5488                                 }
5489                                 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5490                                     || LOOKING_AT_NOCASE (dbp, "id="))
5491                                 {
5492                                         bool quoted = (dbp[0] == '"');
5493
5494                                         if (quoted)
5495                                                 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5496                                                         continue;
5497                                         else
5498                                                 for (end = dbp; *end != '\0' && intoken (*end); end++)
5499                                                         continue;
5500                                         linebuffer_setlen (&token_name, end - dbp);
5501                                         strncpy (token_name.buffer, dbp, end - dbp);
5502                                         token_name.buffer[end - dbp] = '\0';
5503
5504                                         dbp = end;
5505                                         intag = FALSE;  /* we found what we looked for */
5506                                         skiptag = TRUE; /* skip to the end of the tag */
5507                                         getnext = TRUE; /* then grab the text */
5508                                         continue;       /* look on the same line */
5509                                 }
5510                                 dbp += 1;
5511                         }
5512
5513                         else if (getnext)       /* grab next tokens and tag them */
5514                         {
5515                                 dbp = skip_spaces (dbp);
5516                                 if (*dbp == '\0')
5517                                         break;          /* go to next line */
5518                                 if (*dbp == '<')
5519                                 {
5520                                         intag = TRUE;
5521                                         inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5522                                         continue;       /* look on the same line */
5523                                 }
5524
5525                                 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5526                                         continue;
5527                                 make_tag (token_name.buffer, token_name.len, TRUE,
5528                                           dbp, end - dbp, lineno, linecharno);
5529                                 linebuffer_setlen (&token_name, 0);     /* no name in buffer */
5530                                 getnext = FALSE;
5531                                 break;          /* go to next line */
5532                         }
5533
5534                         else                    /* look for an interesting HTML tag */
5535                         {
5536                                 while (*dbp != '\0' && *dbp != '<')
5537                                         dbp++;
5538                                 if (*dbp == '\0')
5539                                         break;          /* go to next line */
5540                                 intag = TRUE;
5541                                 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5542                                 {
5543                                         inanchor = TRUE;
5544                                         continue;       /* look on the same line */
5545                                 }
5546                                 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5547                                          || LOOKING_AT_NOCASE (dbp, "<h1>")
5548                                          || LOOKING_AT_NOCASE (dbp, "<h2>")
5549                                          || LOOKING_AT_NOCASE (dbp, "<h3>"))
5550                                 {
5551                                         intag = FALSE;
5552                                         getnext = TRUE;
5553                                         continue;       /* look on the same line */
5554                                 }
5555                                 dbp += 1;
5556                         }
5557                 }
5558 }
5559
5560 \f
5561 /*
5562  * Prolog support
5563  *
5564  * Assumes that the predicate or rule starts at column 0.
5565  * Only the first clause of a predicate or rule is added.
5566  * Original code by Sunichirou Sugou (1989)
5567  * Rewritten by Anders Lindgren (1996)
5568  */
5569 static int prolog_pr __P((char *, char *));
5570 static void prolog_skip_comment __P((linebuffer *, FILE *));
5571 static int prolog_atom __P((char *, int));
5572
5573 static void
5574 Prolog_functions (inf)
5575 FILE *inf;
5576 {
5577         char *cp, *last;
5578         int len;
5579         int allocated;
5580
5581         allocated = 0;
5582         len = 0;
5583         last = NULL;
5584
5585         LOOP_ON_INPUT_LINES (inf, lb, cp)
5586         {
5587                 if (cp[0] == '\0')      /* Empty line */
5588                         continue;
5589                 else if (iswhite (cp[0])) /* Not a predicate */
5590                         continue;
5591                 else if (cp[0] == '/' && cp[1] == '*')  /* comment. */
5592                         prolog_skip_comment (&lb, inf);
5593                 else if ((len = prolog_pr (cp, last)) > 0)
5594                 {
5595                         /* Predicate or rule.  Store the function name so that we
5596                            only generate a tag for the first clause.  */
5597                         if (last == NULL)
5598                                 last = xnew(len + 1, char);
5599                         else if (len + 1 > allocated)
5600                                 xrnew (last, len + 1, char);
5601                         allocated = len + 1;
5602                         strncpy (last, cp, len);
5603                         last[len] = '\0';
5604                 }
5605         }
5606         free (last);
5607 }
5608
5609
5610 static void
5611 prolog_skip_comment (plb, inf)
5612 linebuffer *plb;
5613 FILE *inf;
5614 {
5615         char *cp;
5616
5617         do
5618         {
5619                 for (cp = plb->buffer; *cp != '\0'; cp++)
5620                         if (cp[0] == '*' && cp[1] == '/')
5621                                 return;
5622                 readline (plb, inf);
5623         }
5624         while (!feof(inf));
5625 }
5626
5627 /*
5628  * A predicate or rule definition is added if it matches:
5629  *     <beginning of line><Prolog Atom><whitespace>(
5630  * or  <beginning of line><Prolog Atom><whitespace>:-
5631  *
5632  * It is added to the tags database if it doesn't match the
5633  * name of the previous clause header.
5634  *
5635  * Return the size of the name of the predicate or rule, or 0 if no
5636  * header was found.
5637  */
5638 static int
5639 prolog_pr (s, last)
5640 char *s;
5641 char *last;             /* Name of last clause. */
5642 {
5643         int pos;
5644         int len;
5645
5646         pos = prolog_atom (s, 0);
5647         if (pos < 1)
5648                 return 0;
5649
5650         len = pos;
5651         pos = skip_spaces (s + pos) - s;
5652
5653         if ((s[pos] == '.'
5654              || (s[pos] == '(' && (pos += 1))
5655              || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5656             && (last == NULL            /* save only the first clause */
5657                 || len != (int)strlen (last)
5658                 || !strneq (s, last, len)))
5659         {
5660                 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5661                 return len;
5662         }
5663         else
5664                 return 0;
5665 }
5666
5667 /*
5668  * Consume a Prolog atom.
5669  * Return the number of bytes consumed, or -1 if there was an error.
5670  *
5671  * A prolog atom, in this context, could be one of:
5672  * - An alphanumeric sequence, starting with a lower case letter.
5673  * - A quoted arbitrary string. Single quotes can escape themselves.
5674  *   Backslash quotes everything.
5675  */
5676 static int
5677 prolog_atom (s, pos)
5678 char *s;
5679 int pos;
5680 {
5681         int origpos;
5682
5683         origpos = pos;
5684
5685         if (ISLOWER(s[pos]) || (s[pos] == '_'))
5686         {
5687                 /* The atom is unquoted. */
5688                 pos++;
5689                 while (ISALNUM(s[pos]) || (s[pos] == '_'))
5690                 {
5691                         pos++;
5692                 }
5693                 return pos - origpos;
5694         }
5695         else if (s[pos] == '\'')
5696         {
5697                 pos++;
5698
5699                 for (;;)
5700                 {
5701                         if (s[pos] == '\'')
5702                         {
5703                                 pos++;
5704                                 if (s[pos] != '\'')
5705                                         break;
5706                                 pos++;          /* A double quote */
5707                         }
5708                         else if (s[pos] == '\0')
5709                                 /* Multiline quoted atoms are ignored. */
5710                                 return -1;
5711                         else if (s[pos] == '\\')
5712                         {
5713                                 if (s[pos+1] == '\0')
5714                                         return -1;
5715                                 pos += 2;
5716                         }
5717                         else
5718                                 pos++;
5719                 }
5720                 return pos - origpos;
5721         }
5722         else
5723                 return -1;
5724 }
5725
5726 \f
5727 /*
5728  * Support for Erlang
5729  *
5730  * Generates tags for functions, defines, and records.
5731  * Assumes that Erlang functions start at column 0.
5732  * Original code by Anders Lindgren (1996)
5733  */
5734 static int erlang_func __P((char *, char *));
5735 static void erlang_attribute __P((char *));
5736 static int erlang_atom __P((char *));
5737
5738 static void
5739 Erlang_functions (inf)
5740 FILE *inf;
5741 {
5742         char *cp, *last;
5743         int len;
5744         int allocated;
5745
5746         allocated = 0;
5747         len = 0;
5748         last = NULL;
5749
5750         LOOP_ON_INPUT_LINES (inf, lb, cp)
5751         {
5752                 if (cp[0] == '\0')      /* Empty line */
5753                         continue;
5754                 else if (iswhite (cp[0])) /* Not function nor attribute */
5755                         continue;
5756                 else if (cp[0] == '%')  /* comment */
5757                         continue;
5758                 else if (cp[0] == '"')  /* Sometimes, strings start in column one */
5759                         continue;
5760                 else if (cp[0] == '-')  /* attribute, e.g. "-define" */
5761                 {
5762                         erlang_attribute (cp);
5763                         if (last != NULL)
5764                         {
5765                                 free (last);
5766                                 last = NULL;
5767                         }
5768                 }
5769                 else if ((len = erlang_func (cp, last)) > 0)
5770                 {
5771                         /*
5772                          * Function.  Store the function name so that we only
5773                          * generates a tag for the first clause.
5774                          */
5775                         if (last == NULL)
5776                                 last = xnew (len + 1, char);
5777                         else if (len + 1 > allocated)
5778                                 xrnew (last, len + 1, char);
5779                         allocated = len + 1;
5780                         strncpy (last, cp, len);
5781                         last[len] = '\0';
5782                 }
5783         }
5784         free (last);
5785 }
5786
5787
5788 /*
5789  * A function definition is added if it matches:
5790  *     <beginning of line><Erlang Atom><whitespace>(
5791  *
5792  * It is added to the tags database if it doesn't match the
5793  * name of the previous clause header.
5794  *
5795  * Return the size of the name of the function, or 0 if no function
5796  * was found.
5797  */
5798 static int
5799 erlang_func (s, last)
5800 char *s;
5801 char *last;             /* Name of last clause. */
5802 {
5803         int pos;
5804         int len;
5805
5806         pos = erlang_atom (s);
5807         if (pos < 1)
5808                 return 0;
5809
5810         len = pos;
5811         pos = skip_spaces (s + pos) - s;
5812
5813         /* Save only the first clause. */
5814         if (s[pos++] == '('
5815             && (last == NULL
5816                 || len != (int)strlen (last)
5817                 || !strneq (s, last, len)))
5818         {
5819                 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5820                 return len;
5821         }
5822
5823         return 0;
5824 }
5825
5826
5827 /*
5828  * Handle attributes.  Currently, tags are generated for defines
5829  * and records.
5830  *
5831  * They are on the form:
5832  * -define(foo, bar).
5833  * -define(Foo(M, N), M+N).
5834  * -record(graph, {vtab = notable, cyclic = true}).
5835  */
5836 static void
5837 erlang_attribute (s)
5838 char *s;
5839 {
5840         char *cp = s;
5841
5842         if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5843             && *cp++ == '(')
5844         {
5845                 int len = erlang_atom (skip_spaces (cp));
5846                 if (len > 0)
5847                         make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5848         }
5849         return;
5850 }
5851
5852
5853 /*
5854  * Consume an Erlang atom (or variable).
5855  * Return the number of bytes consumed, or -1 if there was an error.
5856  */
5857 static int
5858 erlang_atom (s)
5859 char *s;
5860 {
5861         int pos = 0;
5862
5863         if (ISALPHA (s[pos]) || s[pos] == '_')
5864         {
5865                 /* The atom is unquoted. */
5866                 do
5867                         pos++;
5868                 while (ISALNUM (s[pos]) || s[pos] == '_');
5869         }
5870         else if (s[pos] == '\'')
5871         {
5872                 for (pos++; s[pos] != '\''; pos++)
5873                         if (s[pos] == '\0'      /* multiline quoted atoms are ignored */
5874                             || (s[pos] == '\\' && s[++pos] == '\0'))
5875                                 return 0;
5876                 pos++;
5877         }
5878
5879         return pos;
5880 }
5881
5882 \f
5883 static char *scan_separators __P((char *));
5884 static void add_regex __P((char *, language *));
5885 static char *substitute __P((char *, char *, struct re_registers *));
5886
5887 /*
5888  * Take a string like "/blah/" and turn it into "blah", verifying
5889  * that the first and last characters are the same, and handling
5890  * quoted separator characters.  Actually, stops on the occurrence of
5891  * an unquoted separator.  Also process \t, \n, etc. and turn into
5892  * appropriate characters. Works in place.  Null terminates name string.
5893  * Returns pointer to terminating separator, or NULL for
5894  * unterminated regexps.
5895  */
5896 static char *
5897 scan_separators (name)
5898 char *name;
5899 {
5900         char sep = name[0];
5901         char *copyto = name;
5902         bool quoted = FALSE;
5903
5904         for (++name; *name != '\0'; ++name)
5905         {
5906                 if (quoted)
5907                 {
5908                         switch (*name)
5909                         {
5910                         case 'a': *copyto++ = '\007'; break; /* BEL (bell)               */
5911                         case 'b': *copyto++ = '\b'; break;       /* BS (back space)      */
5912                         case 'd': *copyto++ = 0177; break;       /* DEL (delete)         */
5913                         case 'e': *copyto++ = 033; break;        /* ESC (delete)         */
5914                         case 'f': *copyto++ = '\f'; break;       /* FF (form feed)       */
5915                         case 'n': *copyto++ = '\n'; break;       /* NL (new line)        */
5916                         case 'r': *copyto++ = '\r'; break;       /* CR (carriage return) */
5917                         case 't': *copyto++ = '\t'; break;       /* TAB (horizontal tab) */
5918                         case 'v': *copyto++ = '\v'; break;       /* VT (vertical tab)    */
5919                         default:
5920                                 if (*name == sep)
5921                                         *copyto++ = sep;
5922                                 else
5923                                 {
5924                                         /* Something else is quoted, so preserve the quote. */
5925                                         *copyto++ = '\\';
5926                                         *copyto++ = *name;
5927                                 }
5928                                 break;
5929                         }
5930                         quoted = FALSE;
5931                 }
5932                 else if (*name == '\\')
5933                         quoted = TRUE;
5934                 else if (*name == sep)
5935                         break;
5936                 else
5937                         *copyto++ = *name;
5938         }
5939         if (*name != sep)
5940                 name = NULL;            /* signal unterminated regexp */
5941
5942         /* Terminate copied string. */
5943         *copyto = '\0';
5944         return name;
5945 }
5946
5947 /* Look at the argument of --regex or --no-regex and do the right
5948    thing.  Same for each line of a regexp file. */
5949 static void
5950 analyse_regex (regex_arg)
5951 char *regex_arg;
5952 {
5953         if (regex_arg == NULL)
5954         {
5955                 free_regexps ();                /* --no-regex: remove existing regexps */
5956                 return;
5957         }
5958
5959         /* A real --regexp option or a line in a regexp file. */
5960         switch (regex_arg[0])
5961         {
5962                 /* Comments in regexp file or null arg to --regex. */
5963         case '\0':
5964         case ' ':
5965         case '\t':
5966                 break;
5967
5968                 /* Read a regex file.  This is recursive and may result in a
5969                    loop, which will stop when the file descriptors are exhausted. */
5970         case '@':
5971         {
5972                 FILE *regexfp;
5973                 linebuffer regexbuf;
5974                 char *regexfile = regex_arg + 1;
5975
5976                 /* regexfile is a file containing regexps, one per line. */
5977                 regexfp = fopen (regexfile, "r");
5978                 if (regexfp == NULL)
5979                 {
5980                         pfatal (regexfile);
5981                         return;
5982                 }
5983                 linebuffer_init (&regexbuf);
5984                 while (readline_internal (&regexbuf, regexfp) > 0)
5985                         analyse_regex (regexbuf.buffer);
5986                 free (regexbuf.buffer);
5987                 fclose (regexfp);
5988         }
5989         break;
5990
5991         /* Regexp to be used for a specific language only. */
5992         case '{':
5993         {
5994                 language *lang;
5995                 char *lang_name = regex_arg + 1;
5996                 char *cp;
5997
5998                 for (cp = lang_name; *cp != '}'; cp++)
5999                         if (*cp == '\0')
6000                         {
6001                                 error ("unterminated language name in regex: %s", regex_arg);
6002                                 return;
6003                         }
6004                 *cp++ = '\0';
6005                 lang = get_language_from_langname (lang_name);
6006                 if (lang == NULL)
6007                         return;
6008                 add_regex (cp, lang);
6009         }
6010         break;
6011
6012         /* Regexp to be used for any language. */
6013         default:
6014                 add_regex (regex_arg, NULL);
6015                 break;
6016         }
6017 }
6018
6019 /* Separate the regexp pattern, compile it,
6020    and care for optional name and modifiers. */
6021 static void
6022 add_regex (regexp_pattern, lang)
6023 char *regexp_pattern;
6024 language *lang;
6025 {
6026         static struct re_pattern_buffer zeropattern;
6027         char sep, *pat, *name, *modifiers;
6028         const char *err;
6029         struct re_pattern_buffer *patbuf;
6030         regexp *rp;
6031         bool
6032                 force_explicit_name = TRUE, /* do not use implicit tag names */
6033                 ignore_case = FALSE,    /* case is significant */
6034                 multi_line = FALSE,             /* matches are done one line at a time */
6035                 single_line = FALSE;    /* dot does not match newline */
6036
6037
6038         if (strlen(regexp_pattern) < 3)
6039         {
6040                 error ("null regexp", (char *)NULL);
6041                 return;
6042         }
6043         sep = regexp_pattern[0];
6044         name = scan_separators (regexp_pattern);
6045         if (name == NULL)
6046         {
6047                 error ("%s: unterminated regexp", regexp_pattern);
6048                 return;
6049         }
6050         if (name[1] == sep)
6051         {
6052                 error ("null name for regexp \"%s\"", regexp_pattern);
6053                 return;
6054         }
6055         modifiers = scan_separators (name);
6056         if (modifiers == NULL)  /* no terminating separator --> no name */
6057         {
6058                 modifiers = name;
6059                 name = "";
6060         }
6061         else
6062                 modifiers += 1;         /* skip separator */
6063
6064         /* Parse regex modifiers. */
6065         for (; modifiers[0] != '\0'; modifiers++)
6066                 switch (modifiers[0])
6067                 {
6068                 case 'N':
6069                         if (modifiers == name)
6070                                 error ("forcing explicit tag name but no name, ignoring", NULL);
6071                         force_explicit_name = TRUE;
6072                         break;
6073                 case 'i':
6074                         ignore_case = TRUE;
6075                         break;
6076                 case 's':
6077                         single_line = TRUE;
6078                         /* FALLTHRU */
6079                 case 'm':
6080                         multi_line = TRUE;
6081                         need_filebuf = TRUE;
6082                         break;
6083                 default:
6084                 {
6085                         char wrongmod [2];
6086                         wrongmod[0] = modifiers[0];
6087                         wrongmod[1] = '\0';
6088                         error ("invalid regexp modifier `%s', ignoring", wrongmod);
6089                 }
6090                 break;
6091                 }
6092
6093         patbuf = xnew (1, struct re_pattern_buffer);
6094         *patbuf = zeropattern;
6095         if (ignore_case)
6096         {
6097                 static char lc_trans[CHARS];
6098                 int i;
6099                 for (i = 0; i < CHARS; i++)
6100                         lc_trans[i] = lowcase (i);
6101                 patbuf->translate = lc_trans;   /* translation table to fold case  */
6102         }
6103
6104         if (multi_line)
6105                 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
6106         else
6107                 pat = regexp_pattern;
6108
6109         if (single_line)
6110                 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
6111         else
6112                 re_set_syntax (RE_SYNTAX_EMACS);
6113
6114         err = re_compile_pattern (pat, strlen (regexp_pattern), patbuf);
6115         if (multi_line)
6116                 free (pat);
6117         if (err != NULL)
6118         {
6119                 error ("%s while compiling pattern", err);
6120                 return;
6121         }
6122
6123         rp = p_head;
6124         p_head = xnew (1, regexp);
6125         p_head->pattern = savestr (regexp_pattern);
6126         p_head->p_next = rp;
6127         p_head->lang = lang;
6128         p_head->pat = patbuf;
6129         p_head->name = savestr (name);
6130         p_head->error_signaled = FALSE;
6131         p_head->force_explicit_name = force_explicit_name;
6132         p_head->ignore_case = ignore_case;
6133         p_head->multi_line = multi_line;
6134 }
6135
6136 /*
6137  * Do the substitutions indicated by the regular expression and
6138  * arguments.
6139  */
6140 static char *
6141 substitute (in, out, regs)
6142 char *in, *out;
6143 struct re_registers *regs;
6144 {
6145         char *result, *t;
6146         int size, dig, diglen;
6147
6148         result = NULL;
6149         size = strlen (out);
6150
6151         /* Pass 1: figure out how much to allocate by finding all \N strings. */
6152         if (out[size - 1] == '\\')
6153                 fatal ("pattern error in \"%s\"", out);
6154         for (t = etags_strchr (out, '\\');
6155              t != NULL;
6156              t = etags_strchr (t + 2, '\\'))
6157                 if (ISDIGIT (t[1]))
6158                 {
6159                         dig = t[1] - '0';
6160                         diglen = regs->end[dig] - regs->start[dig];
6161                         size += diglen - 2;
6162                 }
6163                 else
6164                         size -= 1;
6165
6166         /* Allocate space and do the substitutions. */
6167         assert (size >= 0);
6168         result = xnew (size + 1, char);
6169
6170         for (t = result; *out != '\0'; out++)
6171                 if (*out == '\\' && ISDIGIT (*++out))
6172                 {
6173                         dig = *out - '0';
6174                         diglen = regs->end[dig] - regs->start[dig];
6175                         strncpy (t, in + regs->start[dig], diglen);
6176                         t += diglen;
6177                 }
6178                 else
6179                         *t++ = *out;
6180         *t = '\0';
6181
6182         assert (t <= result + size);
6183         assert (t - result == (int)strlen (result));
6184
6185         return result;
6186 }
6187
6188 /* Deallocate all regexps. */
6189 static void
6190 free_regexps ()
6191 {
6192         regexp *rp;
6193         while (p_head != NULL)
6194         {
6195                 rp = p_head->p_next;
6196                 free (p_head->pattern);
6197                 free (p_head->name);
6198                 free (p_head);
6199                 p_head = rp;
6200         }
6201         return;
6202 }
6203
6204 /*
6205  * Reads the whole file as a single string from `filebuf' and looks for
6206  * multi-line regular expressions, creating tags on matches.
6207  * readline already dealt with normal regexps.
6208  *
6209  * Idea by Ben Wing <ben@666.com> (2002).
6210  */
6211 static void
6212 regex_tag_multiline ()
6213 {
6214         char *buffer = filebuf.buffer;
6215         regexp *rp;
6216         char *name = NULL;
6217
6218         for (rp = p_head; rp != NULL; rp = rp->p_next)
6219         {
6220                 int match = 0;
6221
6222                 if (!rp->multi_line)
6223                         continue;               /* skip normal regexps */
6224
6225                 /* Generic initialisations before parsing file from memory. */
6226                 lineno = 1;             /* reset global line number */
6227                 charno = 0;             /* reset global char number */
6228                 linecharno = 0;         /* reset global char number of line start */
6229
6230                 /* Only use generic regexps or those for the current language. */
6231                 if (rp->lang != NULL && rp->lang != curfdp->lang)
6232                         continue;
6233
6234                 while (match >= 0 && match < filebuf.len)
6235                 {
6236                         match = re_search (rp->pat, buffer, filebuf.len, charno,
6237                                            filebuf.len - match, &rp->regs);
6238                         switch (match)
6239                         {
6240                         case -2:
6241                                 /* Some error. */
6242                                 if (!rp->error_signaled)
6243                                 {
6244                                         error ("regexp stack overflow while matching \"%s\"",
6245                                                rp->pattern);
6246                                         rp->error_signaled = TRUE;
6247                                 }
6248                                 break;
6249                         case -1:
6250                                 /* No match. */
6251                                 break;
6252                         default:
6253                                 if (match == rp->regs.end[0])
6254                                 {
6255                                         if (!rp->error_signaled)
6256                                         {
6257                                                 error ("regexp matches the empty string: \"%s\"",
6258                                                        rp->pattern);
6259                                                 rp->error_signaled = TRUE;
6260                                         }
6261                                         match = -3;     /* exit from while loop */
6262                                         break;
6263                                 }
6264
6265                                 /* Match occurred.  Construct a tag. */
6266                                 while (charno < rp->regs.end[0])
6267                                         if (buffer[charno++] == '\n')
6268                                                 lineno++, linecharno = charno;
6269                                 if (! rp->name || rp->name[0] == '\0')
6270                                         name = NULL;
6271                                 else /* make a named tag */
6272                                         name = substitute (buffer, rp->name, &rp->regs);
6273                                 if (rp->force_explicit_name)
6274                                         /* Force explicit tag name, if a name
6275                                            is there. */
6276                                         pfnote (name, TRUE, buffer + linecharno,
6277                                                 charno - linecharno + 1, lineno,
6278                                                 linecharno);
6279                                 else if(name == NULL)
6280                                         abort();
6281                                 else
6282                                         make_tag (name, strlen (name), TRUE,
6283                                                   buffer + linecharno,
6284                                                   charno - linecharno + 1,
6285                                                   lineno, linecharno);
6286                                 free(name);
6287                                 name = NULL;
6288                                 break;
6289                         }
6290                 }
6291         }
6292 }
6293
6294 \f
6295 static bool
6296 nocase_tail (cp)
6297 char *cp;
6298 {
6299         register int len = 0;
6300
6301         while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
6302                 cp++, len++;
6303         if (*cp == '\0' && !intoken (dbp[len]))
6304         {
6305                 dbp += len;
6306                 return TRUE;
6307         }
6308         return FALSE;
6309 }
6310
6311 static void
6312 get_tag (bp, namepp)
6313 register char *bp;
6314 char **namepp;
6315 {
6316         register char *cp = bp;
6317
6318         if (*bp != '\0')
6319         {
6320                 /* Go till you get to white space or a syntactic break */
6321                 for (cp = bp + 1; !notinname (*cp); cp++)
6322                         continue;
6323                 make_tag (bp, cp - bp, TRUE,
6324                           lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
6325         }
6326
6327         if (namepp != NULL)
6328                 *namepp = savenstr (bp, cp - bp);
6329 }
6330
6331 /*
6332  * Read a line of text from `stream' into `lbp', excluding the
6333  * newline or CR-NL, if any.  Return the number of characters read from
6334  * `stream', which is the length of the line including the newline.
6335  *
6336  * On DOS or Windows we do not count the CR character, if any before the
6337  * NL, in the returned length; this mirrors the behavior of Emacs on those
6338  * platforms (for text files, it translates CR-NL to NL as it reads in the
6339  * file).
6340  *
6341  * If multi-line regular expressions are requested, each line read is
6342  * appended to `filebuf'.
6343  */
6344 static long
6345 readline_internal (lbp, stream)
6346 linebuffer *lbp;
6347 register FILE *stream;
6348 {
6349         char *buffer = lbp->buffer;
6350         register char *p = lbp->buffer;
6351         register char *pend;
6352         int chars_deleted;
6353
6354         pend = p + lbp->size;           /* Separate to avoid 386/IX compiler bug.  */
6355
6356         for (;;)
6357         {
6358                 register int c = getc (stream);
6359                 if (p == pend)
6360                 {
6361                         /* We're at the end of linebuffer: expand it. */
6362                         lbp->size *= 2;
6363                         xrnew (buffer, lbp->size, char);
6364                         p += buffer - lbp->buffer;
6365                         pend = buffer + lbp->size;
6366                         lbp->buffer = buffer;
6367                 }
6368                 if (c == EOF)
6369                 {
6370                         *p = '\0';
6371                         chars_deleted = 0;
6372                         break;
6373                 }
6374                 if (c == '\n')
6375                 {
6376                         if (p > buffer && p[-1] == '\r')
6377                         {
6378                                 p -= 1;
6379                                 chars_deleted = 2;
6380                         }
6381                         else
6382                         {
6383                                 chars_deleted = 1;
6384                         }
6385                         *p = '\0';
6386                         break;
6387                 }
6388                 *p++ = c;
6389         }
6390         lbp->len = p - buffer;
6391
6392         if (need_filebuf                /* we need filebuf for multi-line regexps */
6393             && chars_deleted > 0)       /* not at EOF */
6394         {
6395                 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6396                 {
6397                         /* Expand filebuf. */
6398                         filebuf.size *= 2;
6399                         xrnew (filebuf.buffer, filebuf.size, char);
6400                 }
6401                 strncpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6402                 filebuf.len += lbp->len;
6403                 filebuf.buffer[filebuf.len++] = '\n';
6404                 filebuf.buffer[filebuf.len] = '\0';
6405         }
6406
6407         return lbp->len + chars_deleted;
6408 }
6409
6410 /*
6411  * Like readline_internal, above, but in addition try to match the
6412  * input line against relevant regular expressions and manage #line
6413  * directives.
6414  */
6415 static void
6416 readline (lbp, stream)
6417 linebuffer *lbp;
6418 FILE *stream;
6419 {
6420         long result;
6421
6422         linecharno = charno;            /* update global char number of line start */
6423         result = readline_internal (lbp, stream); /* read line */
6424         lineno += 1;                    /* increment global line number */
6425         charno += result;               /* increment global char number */
6426
6427         /* Honour #line directives. */
6428         if (!no_line_directive)
6429         {
6430                 static bool discard_until_line_directive;
6431
6432                 /* Check whether this is a #line directive. */
6433                 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6434                 {
6435                         unsigned int lno;
6436                         int start = 0;
6437
6438                         if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6439                             && start > 0)       /* double quote character found */
6440                         {
6441                                 char *endp = lbp->buffer + start;
6442
6443                                 while ((endp = etags_strchr (endp, '"')) != NULL
6444                                        && endp[-1] == '\\')
6445                                         endp++;
6446                                 if (endp != NULL)
6447                                         /* Ok, this is a real #line directive.  Let's deal with it. */
6448                                 {
6449                                         char *taggedabsname;    /* absolute name of original file */
6450                                         char *taggedfname;      /* name of original file as given */
6451                                         char *name;             /* temp var */
6452
6453                                         discard_until_line_directive = FALSE; /* found it */
6454                                         name = lbp->buffer + start;
6455                                         *endp = '\0';
6456                                         canonicalize_filename (name);
6457                                         taggedabsname = absolute_filename (name, tagfiledir);
6458                                         if (filename_is_absolute (name)
6459                                             || filename_is_absolute (curfdp->infname))
6460                                                 taggedfname = savestr (taggedabsname);
6461                                         else
6462                                                 taggedfname = relative_filename (taggedabsname,tagfiledir);
6463
6464                                         if (streq (curfdp->taggedfname, taggedfname))
6465                                                 /* The #line directive is only a line number change.  We
6466                                                    deal with this afterwards. */
6467                                                 free (taggedfname);
6468                                         else
6469                                                 /* The tags following this #line directive should be
6470                                                    attributed to taggedfname.  In order to do this, set
6471                                                    curfdp accordingly. */
6472                                         {
6473                                                 fdesc *fdp; /* file description pointer */
6474
6475                                                 /* Go look for a file description already set up for the
6476                                                    file indicated in the #line directive.  If there is
6477                                                    one, use it from now until the next #line
6478                                                    directive. */
6479                                                 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6480                                                         if (streq (fdp->infname, curfdp->infname)
6481                                                             && streq (fdp->taggedfname, taggedfname))
6482                                                                 /* If we remove the second test above (after the &&)
6483                                                                    then all entries pertaining to the same file are
6484                                                                    coalesced in the tags file.  If we use it, then
6485                                                                    entries pertaining to the same file but generated
6486                                                                    from different files (via #line directives) will
6487                                                                    go into separate sections in the tags file.  These
6488                                                                    alternatives look equivalent.  The first one
6489                                                                    destroys some apparently useless information. */
6490                                                         {
6491                                                                 curfdp = fdp;
6492                                                                 free (taggedfname);
6493                                                                 break;
6494                                                         }
6495                                                 /* Else, if we already tagged the real file, skip all
6496                                                    input lines until the next #line directive. */
6497                                                 if (fdp == NULL) /* not found */
6498                                                         for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6499                                                                 if (streq (fdp->infabsname, taggedabsname))
6500                                                                 {
6501                                                                         discard_until_line_directive = TRUE;
6502                                                                         free (taggedfname);
6503                                                                         break;
6504                                                                 }
6505                                                 /* Else create a new file description and use that from
6506                                                    now on, until the next #line directive. */
6507                                                 if (fdp == NULL) /* not found */
6508                                                 {
6509                                                         fdp = fdhead;
6510                                                         fdhead = xnew (1, fdesc);
6511                                                         *fdhead = *curfdp; /* copy curr. file description */
6512                                                         fdhead->next = fdp;
6513                                                         fdhead->infname = savestr (curfdp->infname);
6514                                                         fdhead->infabsname = savestr (curfdp->infabsname);
6515                                                         fdhead->infabsdir = savestr (curfdp->infabsdir);
6516                                                         fdhead->taggedfname = taggedfname;
6517                                                         fdhead->usecharno = FALSE;
6518                                                         fdhead->prop = NULL;
6519                                                         fdhead->written = FALSE;
6520                                                         curfdp = fdhead;
6521                                                 }
6522                                         }
6523                                         free (taggedabsname);
6524                                         lineno = lno - 1;
6525                                         readline (lbp, stream);
6526                                         return;
6527                                 } /* if a real #line directive */
6528                         } /* if #line is followed by a a number */
6529                 } /* if line begins with "#line " */
6530
6531                 /* If we are here, no #line directive was found. */
6532                 if (discard_until_line_directive)
6533                 {
6534                         if (result > 0)
6535                         {
6536                                 /* Do a tail recursion on ourselves, thus discarding the contents
6537                                    of the line buffer. */
6538                                 readline (lbp, stream);
6539                                 return;
6540                         }
6541                         /* End of file. */
6542                         discard_until_line_directive = FALSE;
6543                         return;
6544                 }
6545         } /* if #line directives should be considered */
6546
6547         {
6548                 int match;
6549                 regexp *rp;
6550                 char *name = NULL;
6551
6552                 /* Match against relevant regexps. */
6553                 if (lbp->len > 0)
6554                         for (rp = p_head; rp != NULL; rp = rp->p_next)
6555                         {
6556                                 /* Only use generic regexps or those for the current language.
6557                                    Also do not use multiline regexps, which is the job of
6558                                    regex_tag_multiline. */
6559                                 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6560                                     || rp->multi_line)
6561                                         continue;
6562
6563                                 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6564                                 switch (match)
6565                                 {
6566                                 case -2:
6567                                         /* Some error. */
6568                                         if (!rp->error_signaled)
6569                                         {
6570                                                 error ("regexp stack overflow while matching \"%s\"",
6571                                                        rp->pattern);
6572                                                 rp->error_signaled = TRUE;
6573                                         }
6574                                         break;
6575                                 case -1:
6576                                         /* No match. */
6577                                         break;
6578                                 case 0:
6579                                         /* Empty string matched. */
6580                                         if (!rp->error_signaled)
6581                                         {
6582                                                 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6583                                                 rp->error_signaled = TRUE;
6584                                         }
6585                                         break;
6586                                 default:
6587                                         /* Match occurred.  Construct a tag. */
6588                                         if (rp->name[0] != '\0')
6589                                                 /* make a named tag */
6590                                                 name = substitute (lbp->buffer, rp->name, &rp->regs);
6591                                         if (rp->force_explicit_name)
6592                                                 /* Force explicit tag name, if a name is there. */
6593                                                 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6594                                         else if (name) {
6595                                                 make_tag (name, strlen (name), TRUE,
6596                                                           lbp->buffer, match, lineno, linecharno);
6597                                                 free(name);
6598                                                 name = NULL;
6599                                         } else
6600                                                 make_tag (rp->name, strlen (rp->name), TRUE,
6601                                                           lbp->buffer, match, lineno, linecharno);
6602                                         break;
6603                                 }
6604                         }
6605         }
6606 }
6607
6608 \f
6609 /*
6610  * Return a pointer to a space of size strlen(cp)+1 allocated
6611  * with xnew where the string CP has been copied.
6612  */
6613 static char *
6614 savestr (cp)
6615 char *cp;
6616 {
6617         return savenstr (cp, strlen (cp));
6618 }
6619
6620 /*
6621  * Return a pointer to a space of size LEN+1 allocated with xnew where
6622  * the string CP has been copied for at most the first LEN characters.
6623  */
6624 static char *
6625 savenstr (cp, len)
6626 char *cp;
6627 int len;
6628 {
6629         register char *dp;
6630
6631         dp = xnew (len + 1, char);
6632         strncpy (dp, cp, len);
6633         dp[len] = '\0';
6634         return dp;
6635 }
6636
6637 /*
6638  * Return the ptr in sp at which the character c last
6639  * appears; NULL if not found
6640  *
6641  * Identical to POSIX strrchr, included for portability.
6642  */
6643 static char *
6644 etags_strrchr (sp, c)
6645 register const char *sp;
6646 register int c;
6647 {
6648         register const char *r;
6649
6650         r = NULL;
6651         do
6652         {
6653                 if (*sp == c)
6654                         r = sp;
6655         } while (*sp++);
6656         return (char *)r;
6657 }
6658
6659 /*
6660  * Return the ptr in sp at which the character c first
6661  * appears; NULL if not found
6662  *
6663  * Identical to POSIX strchr, included for portability.
6664  */
6665 static char *
6666 etags_strchr (sp, c)
6667 register const char *sp;
6668 register int c;
6669 {
6670         do
6671         {
6672                 if (*sp == c)
6673                         return (char *)sp;
6674         } while (*sp++);
6675         return NULL;
6676 }
6677
6678 /*
6679  * Compare two strings, ignoring case for alphabetic characters.
6680  *
6681  * Same as BSD's strcasecmp, included for portability.
6682  */
6683 static int
6684 etags_strcasecmp (s1, s2)
6685 register const char *s1;
6686 register const char *s2;
6687 {
6688         while (*s1 != '\0'
6689                && (ISALPHA (*s1) && ISALPHA (*s2)
6690                    ? lowcase (*s1) == lowcase (*s2)
6691                    : *s1 == *s2))
6692                 s1++, s2++;
6693
6694         return (ISALPHA (*s1) && ISALPHA (*s2)
6695                 ? lowcase (*s1) - lowcase (*s2)
6696                 : *s1 - *s2);
6697 }
6698
6699 /*
6700  * Compare two strings, ignoring case for alphabetic characters.
6701  * Stop after a given number of characters
6702  *
6703  * Same as BSD's strncasecmp, included for portability.
6704  */
6705 static int
6706 etags_strncasecmp (s1, s2, n)
6707 register const char *s1;
6708 register const char *s2;
6709 register int n;
6710 {
6711         while (*s1 != '\0' && n-- > 0
6712                && (ISALPHA (*s1) && ISALPHA (*s2)
6713                    ? lowcase (*s1) == lowcase (*s2)
6714                    : *s1 == *s2))
6715                 s1++, s2++;
6716
6717         if (n < 0)
6718                 return 0;
6719         else
6720                 return (ISALPHA (*s1) && ISALPHA (*s2)
6721                         ? lowcase (*s1) - lowcase (*s2)
6722                         : *s1 - *s2);
6723 }
6724
6725 /* Skip spaces (end of string is not space), return new pointer. */
6726 static char *
6727 skip_spaces (cp)
6728 char *cp;
6729 {
6730         while (iswhite (*cp))
6731                 cp++;
6732         return cp;
6733 }
6734
6735 /* Skip non spaces, except end of string, return new pointer. */
6736 static char *
6737 skip_non_spaces (cp)
6738 char *cp;
6739 {
6740         while (*cp != '\0' && !iswhite (*cp))
6741                 cp++;
6742         return cp;
6743 }
6744
6745 /* Print error message and exit.  */
6746 void
6747 fatal (s1, s2)
6748 char *s1, *s2;
6749 {
6750         error (s1, s2);
6751         exit (EXIT_FAILURE);
6752 }
6753
6754 static void
6755 pfatal (s1)
6756 char *s1;
6757 {
6758         perror (s1);
6759         exit (EXIT_FAILURE);
6760 }
6761
6762 static void
6763 suggest_asking_for_help ()
6764 {
6765         fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6766                  progname, NO_LONG_OPTIONS ? "-h" : "--help");
6767         exit (EXIT_FAILURE);
6768 }
6769
6770 /* Print error message.  `s1' is printf control string, `s2' is arg for it. */
6771 static void
6772 error (s1, s2)
6773 const char *s1, *s2;
6774 {
6775         fprintf (stderr, "%s: ", progname);
6776         fprintf (stderr, s1, s2);
6777         fprintf (stderr, "\n");
6778 }
6779
6780 /* Return a newly-allocated string whose contents
6781    concatenate those of s1, s2, s3.  */
6782 static char *
6783 concat (s1, s2, s3)
6784 char *s1, *s2, *s3;
6785 {
6786         int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6787         char *result = xnew (len1 + len2 + len3 + 1, char);
6788
6789         strncpy(result, s1, len1+1);
6790         strncpy(result + len1, s2, len2+1);
6791         strncpy(result + len1 + len2, s3, len3+1);
6792         result[len1 + len2 + len3] = '\0';
6793
6794         return result;
6795 }
6796
6797 \f
6798 /* Does the same work as the system V getcwd, but does not need to
6799    guess the buffer size in advance. */
6800 static char *
6801 etags_getcwd ()
6802 {
6803 #ifdef HAVE_GETCWD
6804         int bufsize = 200;
6805         char *path = xnew (bufsize, char);
6806
6807         while (getcwd (path, bufsize) == NULL)
6808         {
6809                 if (errno != ERANGE)
6810                         pfatal ("getcwd");
6811                 bufsize *= 2;
6812                 free (path);
6813                 path = xnew (bufsize, char);
6814         }
6815
6816         canonicalize_filename (path);
6817         return path;
6818
6819 #else /* not HAVE_GETCWD */
6820         linebuffer path;
6821         FILE *pipe;
6822
6823         linebuffer_init (&path);
6824         pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6825         if (pipe == NULL || readline_internal (&path, pipe) == 0)
6826                 pfatal ("pwd");
6827         pclose (pipe);
6828
6829         return path.buffer;
6830 #endif /* not HAVE_GETCWD */
6831 }
6832
6833 /* Return a newly allocated string containing the file name of FILE
6834    relative to the absolute directory DIR (which should end with a slash). */
6835 static char *
6836 relative_filename (file, dir)
6837 char *file, *dir;
6838 {
6839         char *fp, *dp, *afn, *res;
6840         int i;
6841         ssize_t res_left;
6842
6843         /* Find the common root of file and dir (with a trailing slash). */
6844         afn = absolute_filename (file, cwd);
6845         fp = afn;
6846         dp = dir;
6847         while (*fp++ == *dp++)
6848                 continue;
6849         fp--, dp--;                     /* back to the first differing char */
6850         do                              /* look at the equal chars until '/' */
6851                 fp--, dp--;
6852         while (*fp != '/');
6853         fp ++; /* Advance past the '/' */
6854
6855         /* Build a sequence of "../" strings for the resulting relative file name. */
6856         i = 0;
6857         while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6858                 i += 1;
6859         res_left = 3 * i + strlen(fp);
6860         res = xnew( res_left + 1, char);
6861         res[0] = '\0';
6862         for ( ; i-- > 0 ; res_left -= 4 )
6863                 strncat(res, "../", res_left );
6864
6865         /* Add the file name relative to the common root of file and dir. */
6866         strncat(res, fp, res_left);
6867         free(afn);
6868
6869         return res;
6870 }
6871
6872 /* Return a newly allocated string containing the absolute file name
6873    of FILE given DIR (which should end with a slash). */
6874 static char *
6875 absolute_filename (file, dir)
6876 char *file, *dir;
6877 {
6878         char *slashp, *cp, *res;
6879
6880         if (filename_is_absolute (file))
6881                 res = savestr (file);
6882         else
6883                 res = concat (dir, file, "");
6884
6885         /* Delete the "/dirname/.." and "/." substrings. */
6886         slashp = etags_strchr (res, '/');
6887         while (slashp != NULL && slashp[0] != '\0')
6888         {
6889                 if (slashp[1] == '.')
6890                 {
6891                         if (slashp[2] == '.'
6892                             && (slashp[3] == '/' || slashp[3] == '\0'))
6893                         {
6894                                 cp = slashp;
6895                                 do
6896                                         cp--;
6897                                 while (cp >= res && !filename_is_absolute (cp));
6898                                 if (cp < res)
6899                                         cp = slashp;    /* the absolute name begins with "/.." */
6900                                 strcpy (cp, slashp + 3);
6901                                 slashp = cp;
6902                                 continue;
6903                         }
6904                         else if (slashp[2] == '/' || slashp[2] == '\0')
6905                         {
6906                                 strcpy (slashp, slashp + 2);
6907                                 continue;
6908                         }
6909                 }
6910
6911                 slashp = etags_strchr (slashp + 1, '/');
6912         }
6913
6914         if (res[0] == '\0')             /* just a safety net: should never happen */
6915         {
6916                 free (res);
6917                 return savestr ("/");
6918         }
6919         else
6920                 return res;
6921 }
6922
6923 /* Return a newly allocated string containing the absolute
6924    file name of dir where FILE resides given DIR (which should
6925    end with a slash). */
6926 static char *
6927 absolute_dirname (file, dir)
6928 char *file, *dir;
6929 {
6930         char *slashp, *res;
6931         char save;
6932
6933         slashp = etags_strrchr (file, '/');
6934         if (slashp == NULL)
6935                 return savestr (dir);
6936         save = slashp[1];
6937         slashp[1] = '\0';
6938         res = absolute_filename (file, dir);
6939         slashp[1] = save;
6940
6941         return res;
6942 }
6943
6944 /* Whether the argument string is an absolute file name.  The argument
6945    string must have been canonicalized with canonicalize_filename. */
6946 static bool
6947 filename_is_absolute (fn)
6948 char *fn;
6949 {
6950         return (fn[0] == '/');
6951 }
6952
6953 /* Upcase DOS drive letter and collapse separators into single slashes.
6954    Works in place. */
6955 static void
6956 canonicalize_filename (fn)
6957 register char *fn;
6958 {
6959         register char* cp;
6960         char sep = '/';
6961
6962         /* Collapse multiple separators into a single slash. */
6963         for (cp = fn; *cp != '\0'; cp++, fn++)
6964                 if (*cp == sep)
6965                 {
6966                         *fn = '/';
6967                         while (cp[1] == sep)
6968                                 cp++;
6969                 }
6970                 else
6971                         *fn = *cp;
6972         *fn = '\0';
6973 }
6974
6975 \f
6976 /* Initialize a linebuffer for use. */
6977 static void
6978 linebuffer_init (lbp)
6979 linebuffer *lbp;
6980 {
6981         lbp->size = (DEBUG) ? 3 : 200;
6982         lbp->buffer = xnew (lbp->size, char);
6983         lbp->buffer[0] = '\0';
6984         lbp->len = 0;
6985 }
6986
6987 /* Set the minimum size of a string contained in a linebuffer. */
6988 static void
6989 linebuffer_setlen (lbp, toksize)
6990 linebuffer *lbp;
6991 int toksize;
6992 {
6993         while (lbp->size <= toksize)
6994         {
6995                 lbp->size *= 2;
6996                 xrnew (lbp->buffer, lbp->size, char);
6997         }
6998         lbp->len = toksize;
6999 }
7000
7001 /* Like malloc but get fatal error if memory is exhausted. */
7002 static PTR
7003 xmalloc (size)
7004 unsigned int size;
7005 {
7006         PTR result = (PTR) malloc (size);
7007         if (result == NULL)
7008                 fatal ("virtual memory exhausted", (char *)NULL);
7009         return result;
7010 }
7011
7012 static PTR
7013 xrealloc (ptr, size)
7014 char *ptr;
7015 unsigned int size;
7016 {
7017         PTR result = (PTR) realloc (ptr, size);
7018         if (result == NULL)
7019                 fatal ("virtual memory exhausted", (char *)NULL);
7020         return result;
7021 }
7022
7023 /*
7024  * Local Variables:
7025  * indent-tabs-mode: t
7026  * tab-width: 8
7027  * fill-column: 79
7028  * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
7029  * End:
7030  */
7031
7032 /* etags.c ends here */