*** empty log message ***
[emacs.git] / lib-src / etags.c
blob79a31c0be022d40fec2509c10ec211ddc63677d9
1 /* Tags file maker to go with GNU Emacs -*- coding: latin-1 -*-
2 Copyright (C) 1984, 1987-1989, 1993-1995, 1998-2001, 2002
3 Free Software Foundation, Inc. and Ken Arnold
5 This file is not considered part of GNU Emacs.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22 * Authors:
23 * Ctags originally by Ken Arnold.
24 * Fortran added by Jim Kleckner.
25 * Ed Pelegri-Llopart added C typedefs.
26 * Gnu Emacs TAGS format and modifications by RMS?
27 * 1989 Sam Kendall added C++.
28 * 1992 Joseph B. Wells improved C and C++ parsing.
29 * 1993 Francesco Potortì reorganised C and C++.
30 * 1994 Line-by-line regexp tags by Tom Tromey.
31 * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba).
32 * 2002 #line directives by Francesco Potortì.
34 * Francesco Potortì <pot@gnu.org> has maintained and improved it since 1993.
38 char pot_etags_version[] = "@(#) pot revision number is 16.56";
40 #define TRUE 1
41 #define FALSE 0
43 #ifdef DEBUG
44 # undef DEBUG
45 # define DEBUG TRUE
46 #else
47 # define DEBUG FALSE
48 # define NDEBUG /* disable assert */
49 #endif
51 #ifdef HAVE_CONFIG_H
52 # include <config.h>
53 /* On some systems, Emacs defines static as nothing for the sake
54 of unexec. We don't want that here since we don't use unexec. */
55 # undef static
56 # define ETAGS_REGEXPS /* use the regexp features */
57 # define LONG_OPTIONS /* accept long options */
58 # ifndef PTR /* for Xemacs */
59 # define PTR void *
60 # endif
61 # ifndef __P /* for Xemacs */
62 # define __P(args) args
63 # endif
64 #else
65 # if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
66 # define __P(args) args /* use prototypes */
67 # define PTR void * /* for generic pointers */
68 # else
69 # define __P(args) () /* no prototypes */
70 # define const /* remove const for old compilers' sake */
71 # define PTR long * /* don't use void* */
72 # endif
73 #endif /* !HAVE_CONFIG_H */
75 #ifndef _GNU_SOURCE
76 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
77 #endif
79 /* WIN32_NATIVE is for Xemacs.
80 MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
81 #ifdef WIN32_NATIVE
82 # undef MSDOS
83 # undef WINDOWSNT
84 # define WINDOWSNT
85 #endif /* WIN32_NATIVE */
87 #ifdef MSDOS
88 # undef MSDOS
89 # define MSDOS TRUE
90 # include <fcntl.h>
91 # include <sys/param.h>
92 # include <io.h>
93 # ifndef HAVE_CONFIG_H
94 # define DOS_NT
95 # include <sys/config.h>
96 # endif
97 #else
98 # define MSDOS FALSE
99 #endif /* MSDOS */
101 #ifdef WINDOWSNT
102 # include <stdlib.h>
103 # include <fcntl.h>
104 # include <string.h>
105 # include <direct.h>
106 # include <io.h>
107 # define MAXPATHLEN _MAX_PATH
108 # undef HAVE_NTGUI
109 # undef DOS_NT
110 # define DOS_NT
111 # ifndef HAVE_GETCWD
112 # define HAVE_GETCWD
113 # endif /* undef HAVE_GETCWD */
114 #else /* !WINDOWSNT */
115 # ifdef STDC_HEADERS
116 # include <stdlib.h>
117 # include <string.h>
118 # else
119 extern char *getenv ();
120 # endif
121 #endif /* !WINDOWSNT */
123 #ifdef HAVE_UNISTD_H
124 # include <unistd.h>
125 #else
126 # if defined (HAVE_GETCWD) && !defined (WINDOWSNT)
127 extern char *getcwd (char *buf, size_t size);
128 # endif
129 #endif /* HAVE_UNISTD_H */
131 #include <stdio.h>
132 #include <ctype.h>
133 #include <errno.h>
134 #ifndef errno
135 extern int errno;
136 #endif
137 #include <sys/types.h>
138 #include <sys/stat.h>
140 #include <assert.h>
141 #ifdef NDEBUG
142 # undef assert /* some systems have a buggy assert.h */
143 # define assert(x) ((void) 0)
144 #endif
146 #if !defined (S_ISREG) && defined (S_IFREG)
147 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
148 #endif
150 #ifdef LONG_OPTIONS
151 # include <getopt.h>
152 #else
153 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
154 extern char *optarg;
155 extern int optind, opterr;
156 #endif /* LONG_OPTIONS */
158 #ifdef ETAGS_REGEXPS
159 # ifndef HAVE_CONFIG_H /* this is a standalone compilation */
160 # ifdef __CYGWIN__ /* compiling on Cygwin */
161 !!! NOTICE !!!
162 the regex.h distributed with Cygwin is not compatible with etags, alas!
163 If you want regular expression support, you should delete this notice and
164 arrange to use the GNU regex.h and regex.c.
165 # endif
166 # endif
167 # include <regex.h>
168 #endif /* ETAGS_REGEXPS */
170 /* Define CTAGS to make the program "ctags" compatible with the usual one.
171 Leave it undefined to make the program "etags", which makes emacs-style
172 tag tables and tags typedefs, #defines and struct/union/enum by default. */
173 #ifdef CTAGS
174 # undef CTAGS
175 # define CTAGS TRUE
176 #else
177 # define CTAGS FALSE
178 #endif
180 /* Exit codes for success and failure. */
181 #ifdef VMS
182 # define GOOD 1
183 # define BAD 0
184 #else
185 # define GOOD 0
186 # define BAD 1
187 #endif
189 #define streq(s,t) (assert((s)!=NULL || (t)!=NULL), !strcmp (s, t))
190 #define strcaseeq(s,t) (assert((s)!=NULL && (t)!=NULL), !etags_strcasecmp (s, t))
191 #define strneq(s,t,n) (assert((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
192 #define strncaseeq(s,t,n) (assert((s)!=NULL && (t)!=NULL), !etags_strncasecmp (s, t, n))
194 #define CHARS 256 /* 2^sizeof(char) */
195 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
196 #define iswhite(c) (_wht[CHAR(c)]) /* c is white (see white) */
197 #define notinname(c) (_nin[CHAR(c)]) /* c is not in a name (see nonam) */
198 #define begtoken(c) (_btk[CHAR(c)]) /* c can start token (see begtk) */
199 #define intoken(c) (_itk[CHAR(c)]) /* c can be in token (see midtk) */
200 #define endtoken(c) (_etk[CHAR(c)]) /* c ends tokens (see endtk) */
202 #define ISALNUM(c) isalnum (CHAR(c))
203 #define ISALPHA(c) isalpha (CHAR(c))
204 #define ISDIGIT(c) isdigit (CHAR(c))
205 #define ISLOWER(c) islower (CHAR(c))
207 #define lowcase(c) tolower (CHAR(c))
208 #define upcase(c) toupper (CHAR(c))
212 * xnew, xrnew -- allocate, reallocate storage
214 * SYNOPSIS: Type *xnew (int n, Type);
215 * void xrnew (OldPointer, int n, Type);
217 #if DEBUG
218 # include "chkmalloc.h"
219 # define xnew(n,Type) ((Type *) trace_malloc (__FILE__, __LINE__, \
220 (n) * sizeof (Type)))
221 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
222 (char *) (op), (n) * sizeof (Type)))
223 #else
224 # define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
225 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
226 (char *) (op), (n) * sizeof (Type)))
227 #endif
229 #define bool int
231 typedef void Lang_function __P((FILE *));
233 typedef struct
235 char *suffix; /* file name suffix for this compressor */
236 char *command; /* takes one arg and decompresses to stdout */
237 } compressor;
239 typedef struct
241 char *name; /* language name */
242 char *help; /* detailed help for the language */
243 Lang_function *function; /* parse function */
244 char **suffixes; /* name suffixes of this language's files */
245 char **filenames; /* names of this language's files */
246 char **interpreters; /* interpreters for this language */
247 bool metasource; /* source used to generate other sources */
248 } language;
250 typedef struct fdesc
252 struct fdesc *next; /* for the linked list */
253 char *infname; /* uncompressed input file name */
254 char *infabsname; /* absolute uncompressed input file name */
255 char *infabsdir; /* absolute dir of input file */
256 char *taggedfname; /* file name to write in tagfile */
257 language *lang; /* language of file */
258 char *prop; /* file properties to write in tagfile */
259 bool usecharno; /* etags tags shall contain char number */
260 bool written; /* entry written in the tags file */
261 } fdesc;
263 typedef struct node_st
264 { /* sorting structure */
265 struct node_st *left, *right; /* left and right sons */
266 fdesc *fdp; /* description of file to whom tag belongs */
267 char *name; /* tag name */
268 char *regex; /* search regexp */
269 bool valid; /* write this tag on the tag file */
270 bool is_func; /* function tag: use regexp in CTAGS mode */
271 bool been_warned; /* warning already given for duplicated tag */
272 int lno; /* line number tag is on */
273 long cno; /* character number line starts on */
274 } node;
277 * A `linebuffer' is a structure which holds a line of text.
278 * `readline_internal' reads a line from a stream into a linebuffer
279 * and works regardless of the length of the line.
280 * SIZE is the size of BUFFER, LEN is the length of the string in
281 * BUFFER after readline reads it.
283 typedef struct
285 long size;
286 int len;
287 char *buffer;
288 } linebuffer;
290 /* Used to support mixing of --lang and file names. */
291 typedef struct
293 enum {
294 at_language, /* a language specification */
295 at_regexp, /* a regular expression */
296 at_filename, /* a file name */
297 at_stdin, /* read from stdin here */
298 at_end /* stop parsing the list */
299 } arg_type; /* argument type */
300 language *lang; /* language associated with the argument */
301 char *what; /* the argument itself */
302 } argument;
304 #ifdef ETAGS_REGEXPS
305 /* Structure defining a regular expression. */
306 typedef struct regexp
308 struct regexp *p_next; /* pointer to next in list */
309 language *lang; /* if set, use only for this language */
310 char *pattern; /* the regexp pattern */
311 char *name; /* tag name */
312 struct re_pattern_buffer *pat; /* the compiled pattern */
313 struct re_registers regs; /* re registers */
314 bool error_signaled; /* already signaled for this regexp */
315 bool force_explicit_name; /* do not allow implict tag name */
316 bool ignore_case; /* ignore case when matching */
317 bool multi_line; /* do a multi-line match on the whole file */
318 } regexp;
319 #endif /* ETAGS_REGEXPS */
322 /* Many compilers barf on this:
323 Lang_function Ada_funcs;
324 so let's write it this way */
325 static void Ada_funcs __P((FILE *));
326 static void Asm_labels __P((FILE *));
327 static void C_entries __P((int c_ext, FILE *));
328 static void default_C_entries __P((FILE *));
329 static void plain_C_entries __P((FILE *));
330 static void Cjava_entries __P((FILE *));
331 static void Cobol_paragraphs __P((FILE *));
332 static void Cplusplus_entries __P((FILE *));
333 static void Cstar_entries __P((FILE *));
334 static void Erlang_functions __P((FILE *));
335 static void Fortran_functions __P((FILE *));
336 static void HTML_labels __P((FILE *));
337 static void Lisp_functions __P((FILE *));
338 static void Makefile_targets __P((FILE *));
339 static void Pascal_functions __P((FILE *));
340 static void Perl_functions __P((FILE *));
341 static void PHP_functions __P((FILE *));
342 static void PS_functions __P((FILE *));
343 static void Prolog_functions __P((FILE *));
344 static void Python_functions __P((FILE *));
345 static void Scheme_functions __P((FILE *));
346 static void TeX_commands __P((FILE *));
347 static void Texinfo_nodes __P((FILE *));
348 static void Yacc_entries __P((FILE *));
349 static void just_read_file __P((FILE *));
351 static void print_language_names __P((void));
352 static void print_version __P((void));
353 static void print_help __P((argument *));
354 int main __P((int, char **));
356 static compressor *get_compressor_from_suffix __P((char *, char **));
357 static language *get_language_from_langname __P((const char *));
358 static language *get_language_from_interpreter __P((char *));
359 static language *get_language_from_filename __P((char *, bool));
360 static void readline __P((linebuffer *, FILE *));
361 static long readline_internal __P((linebuffer *, FILE *));
362 static bool nocase_tail __P((char *));
363 static void get_tag __P((char *, char **));
365 #ifdef ETAGS_REGEXPS
366 static void analyse_regex __P((char *));
367 static void free_regexps __P((void));
368 static void regex_tag_multiline __P((void));
369 #endif /* ETAGS_REGEXPS */
370 static void error __P((const char *, const char *));
371 static void suggest_asking_for_help __P((void));
372 void fatal __P((char *, char *));
373 static void pfatal __P((char *));
374 static void add_node __P((node *, node **));
376 static void init __P((void));
377 static void process_file_name __P((char *, language *));
378 static void process_file __P((FILE *, char *, language *));
379 static void find_entries __P((FILE *));
380 static void free_tree __P((node *));
381 static void free_fdesc __P((fdesc *));
382 static void pfnote __P((char *, bool, char *, int, int, long));
383 static void make_tag __P((char *, int, bool, char *, int, int, long));
384 static void invalidate_nodes __P((fdesc *, node **));
385 static void put_entries __P((node *));
387 static char *concat __P((char *, char *, char *));
388 static char *skip_spaces __P((char *));
389 static char *skip_non_spaces __P((char *));
390 static char *savenstr __P((char *, int));
391 static char *savestr __P((char *));
392 static char *etags_strchr __P((const char *, int));
393 static char *etags_strrchr __P((const char *, int));
394 static int etags_strcasecmp __P((const char *, const char *));
395 static int etags_strncasecmp __P((const char *, const char *, int));
396 static char *etags_getcwd __P((void));
397 static char *relative_filename __P((char *, char *));
398 static char *absolute_filename __P((char *, char *));
399 static char *absolute_dirname __P((char *, char *));
400 static bool filename_is_absolute __P((char *f));
401 static void canonicalize_filename __P((char *));
402 static void linebuffer_init __P((linebuffer *));
403 static void linebuffer_setlen __P((linebuffer *, int));
404 static PTR xmalloc __P((unsigned int));
405 static PTR xrealloc __P((char *, unsigned int));
408 static char searchar = '/'; /* use /.../ searches */
410 static char *tagfile; /* output file */
411 static char *progname; /* name this program was invoked with */
412 static char *cwd; /* current working directory */
413 static char *tagfiledir; /* directory of tagfile */
414 static FILE *tagf; /* ioptr for tags file */
416 static fdesc *fdhead; /* head of file description list */
417 static fdesc *curfdp; /* current file description */
418 static int lineno; /* line number of current line */
419 static long charno; /* current character number */
420 static long linecharno; /* charno of start of current line */
421 static char *dbp; /* pointer to start of current tag */
423 static const int invalidcharno = -1;
425 static node *nodehead; /* the head of the binary tree of tags */
426 static node *last_node; /* the last node created */
428 static linebuffer lb; /* the current line */
429 static linebuffer filebuf; /* a buffer containing the whole file */
430 static linebuffer token_name; /* a buffer containing a tag name */
432 /* boolean "functions" (see init) */
433 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
434 static char
435 /* white chars */
436 *white = " \f\t\n\r\v",
437 /* not in a name */
438 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
439 /* token ending chars */
440 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
441 /* token starting chars */
442 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
443 /* valid in-token chars */
444 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
446 static bool append_to_tagfile; /* -a: append to tags */
447 /* The next four default to TRUE for etags, but to FALSE for ctags. */
448 static bool typedefs; /* -t: create tags for C and Ada typedefs */
449 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
450 /* 0 struct/enum/union decls, and C++ */
451 /* member functions. */
452 static bool constantypedefs; /* -d: create tags for C #define, enum */
453 /* constants and variables. */
454 /* -D: opposite of -d. Default under ctags. */
455 static bool globals; /* create tags for global variables */
456 static bool declarations; /* --declarations: tag them and extern in C&Co*/
457 static bool members; /* create tags for C member variables */
458 static bool no_line_directive; /* ignore #line directives (undocumented) */
459 static bool update; /* -u: update tags */
460 static bool vgrind_style; /* -v: create vgrind style index output */
461 static bool no_warnings; /* -w: suppress warnings */
462 static bool cxref_style; /* -x: create cxref style output */
463 static bool cplusplus; /* .[hc] means C++, not C */
464 static bool ignoreindent; /* -I: ignore indentation in C */
465 static bool packages_only; /* --packages-only: in Ada, only tag packages*/
467 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
468 static bool parsing_stdin; /* --parse-stdin used */
470 #ifdef ETAGS_REGEXPS
471 static regexp *p_head; /* list of all regexps */
472 static bool need_filebuf; /* some regexes are multi-line */
473 #else
474 # define need_filebuf FALSE
475 #endif /* ETAGS_REGEXPS */
477 #ifdef LONG_OPTIONS
478 static struct option longopts[] =
480 { "packages-only", no_argument, &packages_only, TRUE },
481 { "c++", no_argument, NULL, 'C' },
482 { "declarations", no_argument, &declarations, TRUE },
483 { "no-line-directive", no_argument, &no_line_directive, TRUE },
484 { "help", no_argument, NULL, 'h' },
485 { "help", no_argument, NULL, 'H' },
486 { "ignore-indentation", no_argument, NULL, 'I' },
487 { "language", required_argument, NULL, 'l' },
488 { "members", no_argument, &members, TRUE },
489 { "no-members", no_argument, &members, FALSE },
490 { "output", required_argument, NULL, 'o' },
491 #ifdef ETAGS_REGEXPS
492 { "regex", required_argument, NULL, 'r' },
493 { "no-regex", no_argument, NULL, 'R' },
494 { "ignore-case-regex", required_argument, NULL, 'c' },
495 #endif /* ETAGS_REGEXPS */
496 { "parse-stdin", required_argument, NULL, STDIN },
497 { "version", no_argument, NULL, 'V' },
499 #if CTAGS /* Etags options */
500 { "backward-search", no_argument, NULL, 'B' },
501 { "cxref", no_argument, NULL, 'x' },
502 { "defines", no_argument, NULL, 'd' },
503 { "globals", no_argument, &globals, TRUE },
504 { "typedefs", no_argument, NULL, 't' },
505 { "typedefs-and-c++", no_argument, NULL, 'T' },
506 { "update", no_argument, NULL, 'u' },
507 { "vgrind", no_argument, NULL, 'v' },
508 { "no-warn", no_argument, NULL, 'w' },
510 #else /* Ctags options */
511 { "append", no_argument, NULL, 'a' },
512 { "no-defines", no_argument, NULL, 'D' },
513 { "no-globals", no_argument, &globals, FALSE },
514 { "include", required_argument, NULL, 'i' },
515 #endif
516 { NULL }
518 #endif /* LONG_OPTIONS */
520 static compressor compressors[] =
522 { "z", "gzip -d -c"},
523 { "Z", "gzip -d -c"},
524 { "gz", "gzip -d -c"},
525 { "GZ", "gzip -d -c"},
526 { "bz2", "bzip2 -d -c" },
527 { NULL }
531 * Language stuff.
534 /* Ada code */
535 static char *Ada_suffixes [] =
536 { "ads", "adb", "ada", NULL };
537 static char Ada_help [] =
538 "In Ada code, functions, procedures, packages, tasks and types are\n\
539 tags. Use the `--packages-only' option to create tags for\n\
540 packages only.\n\
541 Ada tag names have suffixes indicating the type of entity:\n\
542 Entity type: Qualifier:\n\
543 ------------ ----------\n\
544 function /f\n\
545 procedure /p\n\
546 package spec /s\n\
547 package body /b\n\
548 type /t\n\
549 task /k\n\
550 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
551 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
552 will just search for any tag `bidule'.";
554 /* Assembly code */
555 static char *Asm_suffixes [] =
556 { "a", /* Unix assembler */
557 "asm", /* Microcontroller assembly */
558 "def", /* BSO/Tasking definition includes */
559 "inc", /* Microcontroller include files */
560 "ins", /* Microcontroller include files */
561 "s", "sa", /* Unix assembler */
562 "S", /* cpp-processed Unix assembler */
563 "src", /* BSO/Tasking C compiler output */
564 NULL
566 static char Asm_help [] =
567 "In assembler code, labels appearing at the beginning of a line,\n\
568 followed by a colon, are tags.";
571 /* Note that .c and .h can be considered C++, if the --c++ flag was
572 given, or if the `class' or `template' keyowrds are met inside the file.
573 That is why default_C_entries is called for these. */
574 static char *default_C_suffixes [] =
575 { "c", "h", NULL };
576 static char default_C_help [] =
577 "In C code, any C function or typedef is a tag, and so are\n\
578 definitions of `struct', `union' and `enum'. `#define' macro\n\
579 definitions and `enum' constants are tags unless you specify\n\
580 `--no-defines'. Global variables are tags unless you specify\n\
581 `--no-globals'. Use of `--no-globals' and `--no-defines'\n\
582 can make the tags table file much smaller.\n\
583 You can tag function declarations and external variables by\n\
584 using `--declarations', and struct members by using `--members'.";
586 static char *Cplusplus_suffixes [] =
587 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
588 "M", /* Objective C++ */
589 "pdb", /* Postscript with C syntax */
590 NULL };
591 static char Cplusplus_help [] =
592 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
593 --help --lang=c --lang=c++ for full help.)\n\
594 In addition to C tags, member functions are also recognized, and\n\
595 optionally member variables if you use the `--members' option.\n\
596 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
597 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
598 `operator+'.";
600 static char *Cjava_suffixes [] =
601 { "java", NULL };
602 static char Cjava_help [] =
603 "In Java code, all the tags constructs of C and C++ code are\n\
604 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
607 static char *Cobol_suffixes [] =
608 { "COB", "cob", NULL };
609 static char Cobol_help [] =
610 "In Cobol code, tags are paragraph names; that is, any word\n\
611 starting in column 8 and followed by a period.";
613 static char *Cstar_suffixes [] =
614 { "cs", "hs", NULL };
616 static char *Erlang_suffixes [] =
617 { "erl", "hrl", NULL };
618 static char Erlang_help [] =
619 "In Erlang code, the tags are the functions, records and macros\n\
620 defined in the file.";
622 static char *Fortran_suffixes [] =
623 { "F", "f", "f90", "for", NULL };
624 static char Fortran_help [] =
625 "In Fortran code, functions, subroutines and block data are tags.";
627 static char *HTML_suffixes [] =
628 { "htm", "html", "shtml", NULL };
629 static char HTML_help [] =
630 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
631 `h3' headers. Also, tags are `name=' in anchors and all\n\
632 occurrences of `id='.";
634 static char *Lisp_suffixes [] =
635 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
636 static char Lisp_help [] =
637 "In Lisp code, any function defined with `defun', any variable\n\
638 defined with `defvar' or `defconst', and in general the first\n\
639 argument of any expression that starts with `(def' in column zero\n\
640 is a tag.";
642 static char *Makefile_filenames [] =
643 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
644 static char Makefile_help [] =
645 "In makefiles, targets are tags; additionally, variables are tags\n\
646 unless you specify `--no-globals'.";
648 static char *Objc_suffixes [] =
649 { "lm", /* Objective lex file */
650 "m", /* Objective C file */
651 NULL };
652 static char Objc_help [] =
653 "In Objective C code, tags include Objective C definitions for classes,\n\
654 class categories, methods and protocols. Tags for variables and\n\
655 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.";
657 static char *Pascal_suffixes [] =
658 { "p", "pas", NULL };
659 static char Pascal_help [] =
660 "In Pascal code, the tags are the functions and procedures defined\n\
661 in the file.";
663 static char *Perl_suffixes [] =
664 { "pl", "pm", NULL };
665 static char *Perl_interpreters [] =
666 { "perl", "@PERL@", NULL };
667 static char Perl_help [] =
668 "In Perl code, the tags are the packages, subroutines and variables\n\
669 defined by the `package', `sub', `my' and `local' keywords. Use\n\
670 `--globals' if you want to tag global variables. Tags for\n\
671 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
672 defined in the default package is `main::SUB'.";
674 static char *PHP_suffixes [] =
675 { "php", "php3", "php4", NULL };
676 static char PHP_help [] =
677 "In PHP code, tags are functions, classes and defines. When using\n\
678 the `--members' option, vars are tags too.";
680 static char *plain_C_suffixes [] =
681 { "pc", /* Pro*C file */
682 NULL };
684 static char *PS_suffixes [] =
685 { "ps", "psw", NULL }; /* .psw is for PSWrap */
686 static char PS_help [] =
687 "In PostScript code, the tags are the functions.";
689 static char *Prolog_suffixes [] =
690 { "prolog", NULL };
691 static char Prolog_help [] =
692 "In Prolog code, tags are predicates and rules at the beginning of\n\
693 line.";
695 static char *Python_suffixes [] =
696 { "py", NULL };
697 static char Python_help [] =
698 "In Python code, `def' or `class' at the beginning of a line\n\
699 generate a tag.";
701 /* Can't do the `SCM' or `scm' prefix with a version number. */
702 static char *Scheme_suffixes [] =
703 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
704 static char Scheme_help [] =
705 "In Scheme code, tags include anything defined with `def' or with a\n\
706 construct whose name starts with `def'. They also include\n\
707 variables set with `set!' at top level in the file.";
709 static char *TeX_suffixes [] =
710 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
711 static char TeX_help [] =
712 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
713 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
714 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
715 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
716 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
718 Other commands can be specified by setting the environment variable\n\
719 `TEXTAGS' to a colon-separated list like, for example,\n\
720 TEXTAGS=\"mycommand:myothercommand\".";
723 static char *Texinfo_suffixes [] =
724 { "texi", "texinfo", "txi", NULL };
725 static char Texinfo_help [] =
726 "for texinfo files, lines starting with @node are tagged.";
728 static char *Yacc_suffixes [] =
729 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
730 static char Yacc_help [] =
731 "In Bison or Yacc input files, each rule defines as a tag the\n\
732 nonterminal it constructs. The portions of the file that contain\n\
733 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
734 for full help).";
736 static char auto_help [] =
737 "`auto' is not a real language, it indicates to use\n\
738 a default language for files base on file name suffix and file contents.";
740 static char none_help [] =
741 "`none' is not a real language, it indicates to only do\n\
742 regexp processing on files.";
744 static char no_lang_help [] =
745 "No detailed help available for this language.";
749 * Table of languages.
751 * It is ok for a given function to be listed under more than one
752 * name. I just didn't.
755 static language lang_names [] =
757 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
758 { "asm", Asm_help, Asm_labels, Asm_suffixes },
759 { "c", default_C_help, default_C_entries, default_C_suffixes },
760 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
761 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
762 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
763 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
764 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
765 { "html", HTML_help, HTML_labels, HTML_suffixes },
766 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
767 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
768 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
769 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
770 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
771 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
772 { "php", PHP_help, PHP_functions, PHP_suffixes },
773 { "postscript",PS_help, PS_functions, PS_suffixes },
774 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
775 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
776 { "python", Python_help, Python_functions, Python_suffixes },
777 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
778 { "tex", TeX_help, TeX_commands, TeX_suffixes },
779 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
780 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
781 { "auto", auto_help }, /* default guessing scheme */
782 { "none", none_help, just_read_file }, /* regexp matching only */
783 { NULL } /* end of list */
787 static void
788 print_language_names ()
790 language *lang;
791 char **name, **ext;
793 puts ("\nThese are the currently supported languages, along with the\n\
794 default file names and dot suffixes:");
795 for (lang = lang_names; lang->name != NULL; lang++)
797 printf (" %-*s", 10, lang->name);
798 if (lang->filenames != NULL)
799 for (name = lang->filenames; *name != NULL; name++)
800 printf (" %s", *name);
801 if (lang->suffixes != NULL)
802 for (ext = lang->suffixes; *ext != NULL; ext++)
803 printf (" .%s", *ext);
804 puts ("");
806 puts ("where `auto' means use default language for files based on file\n\
807 name suffix, and `none' means only do regexp processing on files.\n\
808 If no language is specified and no matching suffix is found,\n\
809 the first line of the file is read for a sharp-bang (#!) sequence\n\
810 followed by the name of an interpreter. If no such sequence is found,\n\
811 Fortran is tried first; if no tags are found, C is tried next.\n\
812 When parsing any C file, a \"class\" or \"template\" keyword\n\
813 switches to C++.");
814 puts ("Compressed files are supported using gzip and bzip2.\n\
816 For detailed help on a given language use, for example,\n\
817 etags --help --lang=ada.");
820 #ifndef EMACS_NAME
821 # define EMACS_NAME "standalone"
822 #endif
823 #ifndef VERSION
824 # define VERSION "version"
825 #endif
826 static void
827 print_version ()
829 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
830 puts ("Copyright (C) 2002 Free Software Foundation, Inc. and Ken Arnold");
831 puts ("This program is distributed under the same terms as Emacs");
833 exit (GOOD);
836 static void
837 print_help (argbuffer)
838 argument *argbuffer;
840 bool help_for_lang = FALSE;
842 for (; argbuffer->arg_type != at_end; argbuffer++)
843 if (argbuffer->arg_type == at_language)
845 if (help_for_lang)
846 puts ("");
847 puts (argbuffer->lang->help);
848 help_for_lang = TRUE;
851 if (help_for_lang)
852 exit (GOOD);
854 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
856 These are the options accepted by %s.\n", progname, progname);
857 #ifdef LONG_OPTIONS
858 puts ("You may use unambiguous abbreviations for the long option names.");
859 #else
860 puts ("Long option names do not work with this executable, as it is not\n\
861 linked with GNU getopt.");
862 #endif /* LONG_OPTIONS */
863 puts (" A - as file name means read names from stdin (one per line).\n\
864 Absolute names are stored in the output file as they are.\n\
865 Relative ones are stored relative to the output file's directory.\n");
867 if (!CTAGS)
868 puts ("-a, --append\n\
869 Append tag entries to existing tags file.");
871 puts ("--packages-only\n\
872 For Ada files, only generate tags for packages.");
874 if (CTAGS)
875 puts ("-B, --backward-search\n\
876 Write the search commands for the tag entries using '?', the\n\
877 backward-search command instead of '/', the forward-search command.");
879 /* This option is mostly obsolete, because etags can now automatically
880 detect C++. Retained for backward compatibility and for debugging and
881 experimentation. In principle, we could want to tag as C++ even
882 before any "class" or "template" keyword.
883 puts ("-C, --c++\n\
884 Treat files whose name suffix defaults to C language as C++ files.");
887 puts ("--declarations\n\
888 In C and derived languages, create tags for function declarations,");
889 if (CTAGS)
890 puts ("\tand create tags for extern variables if --globals is used.");
891 else
892 puts
893 ("\tand create tags for extern variables unless --no-globals is used.");
895 if (CTAGS)
896 puts ("-d, --defines\n\
897 Create tag entries for C #define constants and enum constants, too.");
898 else
899 puts ("-D, --no-defines\n\
900 Don't create tag entries for C #define constants and enum constants.\n\
901 This makes the tags file smaller.");
903 if (!CTAGS)
904 puts ("-i FILE, --include=FILE\n\
905 Include a note in tag file indicating that, when searching for\n\
906 a tag, one should also consult the tags file FILE after\n\
907 checking the current file.");
909 puts ("-l LANG, --language=LANG\n\
910 Force the following files to be considered as written in the\n\
911 named language up to the next --language=LANG option.");
913 if (CTAGS)
914 puts ("--globals\n\
915 Create tag entries for global variables in some languages.");
916 else
917 puts ("--no-globals\n\
918 Do not create tag entries for global variables in some\n\
919 languages. This makes the tags file smaller.");
920 puts ("--members\n\
921 Create tag entries for members of structures in some languages.");
923 #ifdef ETAGS_REGEXPS
924 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
925 Make a tag for each line matching a regular expression pattern\n\
926 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
927 files only. REGEXFILE is a file containing one REGEXP per line.\n\
928 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
929 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
930 puts (" If TAGNAME/ is present, the tags created are named.\n\
931 For example Tcl named tags can be created with:\n\
932 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
933 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
934 `m' means to allow multi-line matches, `s' implies `m' and\n\
935 causes dot to match any character, including newline.");
936 puts ("-R, --no-regex\n\
937 Don't create tags from regexps for the following files.");
938 #endif /* ETAGS_REGEXPS */
939 puts ("-I, --ignore-indentation\n\
940 In C and C++ do not assume that a closing brace in the first\n\
941 column is the final brace of a function or structure definition.");
942 puts ("-o FILE, --output=FILE\n\
943 Write the tags to FILE.");
944 puts ("--parse-stdin=NAME\n\
945 Read from standard input and record tags as belonging to file NAME.");
947 if (CTAGS)
949 puts ("-t, --typedefs\n\
950 Generate tag entries for C and Ada typedefs.");
951 puts ("-T, --typedefs-and-c++\n\
952 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
953 and C++ member functions.");
956 if (CTAGS)
957 puts ("-u, --update\n\
958 Update the tag entries for the given files, leaving tag\n\
959 entries for other files in place. Currently, this is\n\
960 implemented by deleting the existing entries for the given\n\
961 files and then rewriting the new entries at the end of the\n\
962 tags file. It is often faster to simply rebuild the entire\n\
963 tag file than to use this.");
965 if (CTAGS)
967 puts ("-v, --vgrind\n\
968 Generates an index of items intended for human consumption,\n\
969 similar to the output of vgrind. The index is sorted, and\n\
970 gives the page number of each item.");
971 puts ("-w, --no-warn\n\
972 Suppress warning messages about entries defined in multiple\n\
973 files.");
974 puts ("-x, --cxref\n\
975 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
976 The output uses line numbers instead of page numbers, but\n\
977 beyond that the differences are cosmetic; try both to see\n\
978 which you like.");
981 puts ("-V, --version\n\
982 Print the version of the program.\n\
983 -h, --help\n\
984 Print this help message.\n\
985 Followed by one or more `--language' options prints detailed\n\
986 help about tag generation for the specified languages.");
988 print_language_names ();
990 puts ("");
991 puts ("Report bugs to bug-gnu-emacs@gnu.org");
993 exit (GOOD);
997 #ifdef VMS /* VMS specific functions */
999 #define EOS '\0'
1001 /* This is a BUG! ANY arbitrary limit is a BUG!
1002 Won't someone please fix this? */
1003 #define MAX_FILE_SPEC_LEN 255
1004 typedef struct {
1005 short curlen;
1006 char body[MAX_FILE_SPEC_LEN + 1];
1007 } vspec;
1010 v1.05 nmm 26-Jun-86 fn_exp - expand specification of list of file names
1011 returning in each successive call the next file name matching the input
1012 spec. The function expects that each in_spec passed
1013 to it will be processed to completion; in particular, up to and
1014 including the call following that in which the last matching name
1015 is returned, the function ignores the value of in_spec, and will
1016 only start processing a new spec with the following call.
1017 If an error occurs, on return out_spec contains the value
1018 of in_spec when the error occurred.
1020 With each successive file name returned in out_spec, the
1021 function's return value is one. When there are no more matching
1022 names the function returns zero. If on the first call no file
1023 matches in_spec, or there is any other error, -1 is returned.
1026 #include <rmsdef.h>
1027 #include <descrip.h>
1028 #define OUTSIZE MAX_FILE_SPEC_LEN
1029 static short
1030 fn_exp (out, in)
1031 vspec *out;
1032 char *in;
1034 static long context = 0;
1035 static struct dsc$descriptor_s o;
1036 static struct dsc$descriptor_s i;
1037 static bool pass1 = TRUE;
1038 long status;
1039 short retval;
1041 if (pass1)
1043 pass1 = FALSE;
1044 o.dsc$a_pointer = (char *) out;
1045 o.dsc$w_length = (short)OUTSIZE;
1046 i.dsc$a_pointer = in;
1047 i.dsc$w_length = (short)strlen(in);
1048 i.dsc$b_dtype = DSC$K_DTYPE_T;
1049 i.dsc$b_class = DSC$K_CLASS_S;
1050 o.dsc$b_dtype = DSC$K_DTYPE_VT;
1051 o.dsc$b_class = DSC$K_CLASS_VS;
1053 if ((status = lib$find_file(&i, &o, &context, 0, 0)) == RMS$_NORMAL)
1055 out->body[out->curlen] = EOS;
1056 return 1;
1058 else if (status == RMS$_NMF)
1059 retval = 0;
1060 else
1062 strcpy(out->body, in);
1063 retval = -1;
1065 lib$find_file_end(&context);
1066 pass1 = TRUE;
1067 return retval;
1071 v1.01 nmm 19-Aug-85 gfnames - return in successive calls the
1072 name of each file specified by the provided arg expanding wildcards.
1074 static char *
1075 gfnames (arg, p_error)
1076 char *arg;
1077 bool *p_error;
1079 static vspec filename = {MAX_FILE_SPEC_LEN, "\0"};
1081 switch (fn_exp (&filename, arg))
1083 case 1:
1084 *p_error = FALSE;
1085 return filename.body;
1086 case 0:
1087 *p_error = FALSE;
1088 return NULL;
1089 default:
1090 *p_error = TRUE;
1091 return filename.body;
1095 #ifndef OLD /* Newer versions of VMS do provide `system'. */
1096 system (cmd)
1097 char *cmd;
1099 error ("%s", "system() function not implemented under VMS");
1101 #endif
1103 #define VERSION_DELIM ';'
1104 char *massage_name (s)
1105 char *s;
1107 char *start = s;
1109 for ( ; *s; s++)
1110 if (*s == VERSION_DELIM)
1112 *s = EOS;
1113 break;
1115 else
1116 *s = lowcase (*s);
1117 return start;
1119 #endif /* VMS */
1123 main (argc, argv)
1124 int argc;
1125 char *argv[];
1127 int i;
1128 unsigned int nincluded_files;
1129 char **included_files;
1130 argument *argbuffer;
1131 int current_arg, file_count;
1132 linebuffer filename_lb;
1133 bool help_asked = FALSE;
1134 #ifdef VMS
1135 bool got_err;
1136 #endif
1137 char *optstring;
1138 int opt;
1141 #ifdef DOS_NT
1142 _fmode = O_BINARY; /* all of files are treated as binary files */
1143 #endif /* DOS_NT */
1145 progname = argv[0];
1146 nincluded_files = 0;
1147 included_files = xnew (argc, char *);
1148 current_arg = 0;
1149 file_count = 0;
1151 /* Allocate enough no matter what happens. Overkill, but each one
1152 is small. */
1153 argbuffer = xnew (argc, argument);
1156 * If etags, always find typedefs and structure tags. Why not?
1157 * Also default to find macro constants, enum constants and
1158 * global variables.
1160 if (!CTAGS)
1162 typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1163 globals = TRUE;
1166 optstring = "-";
1167 #ifdef ETAGS_REGEXPS
1168 optstring = "-r:Rc:";
1169 #endif /* ETAGS_REGEXPS */
1170 #ifndef LONG_OPTIONS
1171 optstring = optstring + 1;
1172 #endif /* LONG_OPTIONS */
1173 optstring = concat (optstring,
1174 "Cf:Il:o:SVhH",
1175 (CTAGS) ? "BxdtTuvw" : "aDi:");
1177 while ((opt = getopt_long (argc, argv, optstring, longopts, 0)) != EOF)
1178 switch (opt)
1180 case 0:
1181 /* If getopt returns 0, then it has already processed a
1182 long-named option. We should do nothing. */
1183 break;
1185 case 1:
1186 /* This means that a file name has been seen. Record it. */
1187 argbuffer[current_arg].arg_type = at_filename;
1188 argbuffer[current_arg].what = optarg;
1189 ++current_arg;
1190 ++file_count;
1191 break;
1193 case STDIN:
1194 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1195 argbuffer[current_arg].arg_type = at_stdin;
1196 argbuffer[current_arg].what = optarg;
1197 ++current_arg;
1198 ++file_count;
1199 if (parsing_stdin)
1200 fatal ("cannot parse standard input more than once", (char *)NULL);
1201 parsing_stdin = TRUE;
1202 break;
1204 /* Common options. */
1205 case 'C': cplusplus = TRUE; break;
1206 case 'f': /* for compatibility with old makefiles */
1207 case 'o':
1208 if (tagfile)
1210 error ("-o option may only be given once.", (char *)NULL);
1211 suggest_asking_for_help ();
1212 /* NOTREACHED */
1214 tagfile = optarg;
1215 break;
1216 case 'I':
1217 case 'S': /* for backward compatibility */
1218 ignoreindent = TRUE;
1219 break;
1220 case 'l':
1222 language *lang = get_language_from_langname (optarg);
1223 if (lang != NULL)
1225 argbuffer[current_arg].lang = lang;
1226 argbuffer[current_arg].arg_type = at_language;
1227 ++current_arg;
1230 break;
1231 case 'c':
1232 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1233 optarg = concat (optarg, "i", ""); /* memory leak here */
1234 /* FALLTHRU */
1235 case 'r':
1236 argbuffer[current_arg].arg_type = at_regexp;
1237 argbuffer[current_arg].what = optarg;
1238 ++current_arg;
1239 break;
1240 case 'R':
1241 argbuffer[current_arg].arg_type = at_regexp;
1242 argbuffer[current_arg].what = NULL;
1243 ++current_arg;
1244 break;
1245 case 'V':
1246 print_version ();
1247 break;
1248 case 'h':
1249 case 'H':
1250 help_asked = TRUE;
1251 break;
1253 /* Etags options */
1254 case 'a': append_to_tagfile = TRUE; break;
1255 case 'D': constantypedefs = FALSE; break;
1256 case 'i': included_files[nincluded_files++] = optarg; break;
1258 /* Ctags options. */
1259 case 'B': searchar = '?'; break;
1260 case 'd': constantypedefs = TRUE; break;
1261 case 't': typedefs = TRUE; break;
1262 case 'T': typedefs = typedefs_or_cplusplus = TRUE; break;
1263 case 'u': update = TRUE; break;
1264 case 'v': vgrind_style = TRUE; /*FALLTHRU*/
1265 case 'x': cxref_style = TRUE; break;
1266 case 'w': no_warnings = TRUE; break;
1267 default:
1268 suggest_asking_for_help ();
1269 /* NOTREACHED */
1272 for (; optind < argc; optind++)
1274 argbuffer[current_arg].arg_type = at_filename;
1275 argbuffer[current_arg].what = argv[optind];
1276 ++current_arg;
1277 ++file_count;
1280 argbuffer[current_arg].arg_type = at_end;
1282 if (help_asked)
1283 print_help (argbuffer);
1284 /* NOTREACHED */
1286 if (nincluded_files == 0 && file_count == 0)
1288 error ("no input files specified.", (char *)NULL);
1289 suggest_asking_for_help ();
1290 /* NOTREACHED */
1293 if (tagfile == NULL)
1294 tagfile = CTAGS ? "tags" : "TAGS";
1295 cwd = etags_getcwd (); /* the current working directory */
1296 if (cwd[strlen (cwd) - 1] != '/')
1298 char *oldcwd = cwd;
1299 cwd = concat (oldcwd, "/", "");
1300 free (oldcwd);
1302 if (streq (tagfile, "-"))
1303 tagfiledir = cwd;
1304 else
1305 tagfiledir = absolute_dirname (tagfile, cwd);
1307 init (); /* set up boolean "functions" */
1309 linebuffer_init (&lb);
1310 linebuffer_init (&filename_lb);
1311 linebuffer_init (&filebuf);
1312 linebuffer_init (&token_name);
1314 if (!CTAGS)
1316 if (streq (tagfile, "-"))
1318 tagf = stdout;
1319 #ifdef DOS_NT
1320 /* Switch redirected `stdout' to binary mode (setting `_fmode'
1321 doesn't take effect until after `stdout' is already open). */
1322 if (!isatty (fileno (stdout)))
1323 setmode (fileno (stdout), O_BINARY);
1324 #endif /* DOS_NT */
1326 else
1327 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1328 if (tagf == NULL)
1329 pfatal (tagfile);
1333 * Loop through files finding functions.
1335 for (i = 0; i < current_arg; i++)
1337 static language *lang; /* non-NULL if language is forced */
1338 char *this_file;
1340 switch (argbuffer[i].arg_type)
1342 case at_language:
1343 lang = argbuffer[i].lang;
1344 break;
1345 #ifdef ETAGS_REGEXPS
1346 case at_regexp:
1347 analyse_regex (argbuffer[i].what);
1348 break;
1349 #endif
1350 case at_filename:
1351 #ifdef VMS
1352 while ((this_file = gfnames (argbuffer[i].what, &got_err)) != NULL)
1354 if (got_err)
1356 error ("can't find file %s\n", this_file);
1357 argc--, argv++;
1359 else
1361 this_file = massage_name (this_file);
1363 #else
1364 this_file = argbuffer[i].what;
1365 #endif
1366 /* Input file named "-" means read file names from stdin
1367 (one per line) and use them. */
1368 if (streq (this_file, "-"))
1370 if (parsing_stdin)
1371 fatal ("cannot parse standard input AND read file names from it",
1372 (char *)NULL);
1373 while (readline_internal (&filename_lb, stdin) > 0)
1374 process_file_name (filename_lb.buffer, lang);
1376 else
1377 process_file_name (this_file, lang);
1378 #ifdef VMS
1380 #endif
1381 break;
1382 case at_stdin:
1383 this_file = argbuffer[i].what;
1384 process_file (stdin, this_file, lang);
1385 break;
1389 #ifdef ETAGS_REGEXPS
1390 free_regexps ();
1391 #endif /* ETAGS_REGEXPS */
1392 free (lb.buffer);
1393 free (filebuf.buffer);
1394 free (token_name.buffer);
1396 if (!CTAGS || cxref_style)
1398 put_entries (nodehead); /* write the remainig tags (ETAGS) */
1399 free_tree (nodehead);
1400 nodehead = NULL;
1401 if (!CTAGS)
1403 fdesc *fdp;
1405 /* Output file entries that have no tags. */
1406 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1407 if (!fdp->written)
1408 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1410 while (nincluded_files-- > 0)
1411 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1414 if (fclose (tagf) == EOF)
1415 pfatal (tagfile);
1416 exit (GOOD);
1419 if (update)
1421 char cmd[BUFSIZ];
1422 for (i = 0; i < current_arg; ++i)
1424 switch (argbuffer[i].arg_type)
1426 case at_filename:
1427 case at_stdin:
1428 break;
1429 default:
1430 continue; /* the for loop */
1432 sprintf (cmd,
1433 "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
1434 tagfile, argbuffer[i].what, tagfile);
1435 if (system (cmd) != GOOD)
1436 fatal ("failed to execute shell command", (char *)NULL);
1438 append_to_tagfile = TRUE;
1441 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1442 if (tagf == NULL)
1443 pfatal (tagfile);
1444 put_entries (nodehead); /* write all the tags (CTAGS) */
1445 free_tree (nodehead);
1446 nodehead = NULL;
1447 if (fclose (tagf) == EOF)
1448 pfatal (tagfile);
1450 if (update)
1452 char cmd[2*BUFSIZ+10];
1453 sprintf (cmd, "sort -o %.*s %.*s", BUFSIZ, tagfile, BUFSIZ, tagfile);
1454 exit (system (cmd));
1456 return GOOD;
1461 * Return a compressor given the file name. If EXTPTR is non-zero,
1462 * return a pointer into FILE where the compressor-specific
1463 * extension begins. If no compressor is found, NULL is returned
1464 * and EXTPTR is not significant.
1465 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1467 static compressor *
1468 get_compressor_from_suffix (file, extptr)
1469 char *file;
1470 char **extptr;
1472 compressor *compr;
1473 char *slash, *suffix;
1475 /* This relies on FN to be after canonicalize_filename,
1476 so we don't need to consider backslashes on DOS_NT. */
1477 slash = etags_strrchr (file, '/');
1478 suffix = etags_strrchr (file, '.');
1479 if (suffix == NULL || suffix < slash)
1480 return NULL;
1481 if (extptr != NULL)
1482 *extptr = suffix;
1483 suffix += 1;
1484 /* Let those poor souls who live with DOS 8+3 file name limits get
1485 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1486 Only the first do loop is run if not MSDOS */
1489 for (compr = compressors; compr->suffix != NULL; compr++)
1490 if (streq (compr->suffix, suffix))
1491 return compr;
1492 if (!MSDOS)
1493 break; /* do it only once: not really a loop */
1494 if (extptr != NULL)
1495 *extptr = ++suffix;
1496 } while (*suffix != '\0');
1497 return NULL;
1503 * Return a language given the name.
1505 static language *
1506 get_language_from_langname (name)
1507 const char *name;
1509 language *lang;
1511 if (name == NULL)
1512 error ("empty language name", (char *)NULL);
1513 else
1515 for (lang = lang_names; lang->name != NULL; lang++)
1516 if (streq (name, lang->name))
1517 return lang;
1518 error ("unknown language \"%s\"", name);
1521 return NULL;
1526 * Return a language given the interpreter name.
1528 static language *
1529 get_language_from_interpreter (interpreter)
1530 char *interpreter;
1532 language *lang;
1533 char **iname;
1535 if (interpreter == NULL)
1536 return NULL;
1537 for (lang = lang_names; lang->name != NULL; lang++)
1538 if (lang->interpreters != NULL)
1539 for (iname = lang->interpreters; *iname != NULL; iname++)
1540 if (streq (*iname, interpreter))
1541 return lang;
1543 return NULL;
1549 * Return a language given the file name.
1551 static language *
1552 get_language_from_filename (file, case_sensitive)
1553 char *file;
1554 bool case_sensitive;
1556 language *lang;
1557 char **name, **ext, *suffix;
1559 /* Try whole file name first. */
1560 for (lang = lang_names; lang->name != NULL; lang++)
1561 if (lang->filenames != NULL)
1562 for (name = lang->filenames; *name != NULL; name++)
1563 if ((case_sensitive)
1564 ? streq (*name, file)
1565 : strcaseeq (*name, file))
1566 return lang;
1568 /* If not found, try suffix after last dot. */
1569 suffix = etags_strrchr (file, '.');
1570 if (suffix == NULL)
1571 return NULL;
1572 suffix += 1;
1573 for (lang = lang_names; lang->name != NULL; lang++)
1574 if (lang->suffixes != NULL)
1575 for (ext = lang->suffixes; *ext != NULL; ext++)
1576 if ((case_sensitive)
1577 ? streq (*ext, suffix)
1578 : strcaseeq (*ext, suffix))
1579 return lang;
1580 return NULL;
1585 * This routine is called on each file argument.
1587 static void
1588 process_file_name (file, lang)
1589 char *file;
1590 language *lang;
1592 struct stat stat_buf;
1593 FILE *inf;
1594 fdesc *fdp;
1595 compressor *compr;
1596 char *compressed_name, *uncompressed_name;
1597 char *ext, *real_name;
1598 int retval;
1600 canonicalize_filename (file);
1601 if (streq (file, tagfile) && !streq (tagfile, "-"))
1603 error ("skipping inclusion of %s in self.", file);
1604 return;
1606 if ((compr = get_compressor_from_suffix (file, &ext)) == NULL)
1608 compressed_name = NULL;
1609 real_name = uncompressed_name = savestr (file);
1611 else
1613 real_name = compressed_name = savestr (file);
1614 uncompressed_name = savenstr (file, ext - file);
1617 /* If the canonicalized uncompressed name
1618 has already been dealt with, skip it silently. */
1619 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1621 assert (fdp->infname != NULL);
1622 if (streq (uncompressed_name, fdp->infname))
1623 goto cleanup;
1626 if (stat (real_name, &stat_buf) != 0)
1628 /* Reset real_name and try with a different name. */
1629 real_name = NULL;
1630 if (compressed_name != NULL) /* try with the given suffix */
1632 if (stat (uncompressed_name, &stat_buf) == 0)
1633 real_name = uncompressed_name;
1635 else /* try all possible suffixes */
1637 for (compr = compressors; compr->suffix != NULL; compr++)
1639 compressed_name = concat (file, ".", compr->suffix);
1640 if (stat (compressed_name, &stat_buf) != 0)
1642 if (MSDOS)
1644 char *suf = compressed_name + strlen (file);
1645 size_t suflen = strlen (compr->suffix) + 1;
1646 for ( ; suf[1]; suf++, suflen--)
1648 memmove (suf, suf + 1, suflen);
1649 if (stat (compressed_name, &stat_buf) == 0)
1651 real_name = compressed_name;
1652 break;
1655 if (real_name != NULL)
1656 break;
1657 } /* MSDOS */
1658 free (compressed_name);
1659 compressed_name = NULL;
1661 else
1663 real_name = compressed_name;
1664 break;
1668 if (real_name == NULL)
1670 perror (file);
1671 goto cleanup;
1673 } /* try with a different name */
1675 if (!S_ISREG (stat_buf.st_mode))
1677 error ("skipping %s: it is not a regular file.", real_name);
1678 goto cleanup;
1680 if (real_name == compressed_name)
1682 char *cmd = concat (compr->command, " ", real_name);
1683 inf = (FILE *) popen (cmd, "r");
1684 free (cmd);
1686 else
1687 inf = fopen (real_name, "r");
1688 if (inf == NULL)
1690 perror (real_name);
1691 goto cleanup;
1694 process_file (inf, uncompressed_name, lang);
1696 if (real_name == compressed_name)
1697 retval = pclose (inf);
1698 else
1699 retval = fclose (inf);
1700 if (retval < 0)
1701 pfatal (file);
1703 cleanup:
1704 if (compressed_name) free (compressed_name);
1705 if (uncompressed_name) free (uncompressed_name);
1706 last_node = NULL;
1707 curfdp = NULL;
1708 return;
1711 static void
1712 process_file (fh, fn, lang)
1713 FILE *fh;
1714 char *fn;
1715 language *lang;
1717 static const fdesc emptyfdesc;
1718 fdesc *fdp;
1720 /* Create a new input file description entry. */
1721 fdp = xnew (1, fdesc);
1722 *fdp = emptyfdesc;
1723 fdp->next = fdhead;
1724 fdp->infname = savestr (fn);
1725 fdp->lang = lang;
1726 fdp->infabsname = absolute_filename (fn, cwd);
1727 fdp->infabsdir = absolute_dirname (fn, cwd);
1728 if (filename_is_absolute (fn))
1730 /* An absolute file name. Canonicalize it. */
1731 fdp->taggedfname = absolute_filename (fn, NULL);
1733 else
1735 /* A file name relative to cwd. Make it relative
1736 to the directory of the tags file. */
1737 fdp->taggedfname = relative_filename (fn, tagfiledir);
1739 fdp->usecharno = TRUE; /* use char position when making tags */
1740 fdp->prop = NULL;
1741 fdp->written = FALSE; /* not written on tags file yet */
1743 fdhead = fdp;
1744 curfdp = fdhead; /* the current file description */
1746 find_entries (fh);
1748 /* If not Ctags, and if this is not metasource and if it contained no #line
1749 directives, we can write the tags and free all nodes pointing to
1750 curfdp. */
1751 if (!CTAGS
1752 && curfdp->usecharno /* no #line directives in this file */
1753 && !curfdp->lang->metasource)
1755 node *np, *prev;
1757 /* Look for the head of the sublist relative to this file. See add_node
1758 for the structure of the node tree. */
1759 prev = NULL;
1760 for (np = nodehead; np != NULL; prev = np, np = np->left)
1761 if (np->fdp == curfdp)
1762 break;
1764 /* If we generated tags for this file, write and delete them. */
1765 if (np != NULL)
1767 /* This is the head of the last sublist, if any. The following
1768 instructions depend on this being true. */
1769 assert (np->left == NULL);
1771 assert (fdhead == curfdp);
1772 assert (last_node->fdp == curfdp);
1773 put_entries (np); /* write tags for file curfdp->taggedfname */
1774 free_tree (np); /* remove the written nodes */
1775 if (prev == NULL)
1776 nodehead = NULL; /* no nodes left */
1777 else
1778 prev->left = NULL; /* delete the pointer to the sublist */
1784 * This routine sets up the boolean pseudo-functions which work
1785 * by setting boolean flags dependent upon the corresponding character.
1786 * Every char which is NOT in that string is not a white char. Therefore,
1787 * all of the array "_wht" is set to FALSE, and then the elements
1788 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1789 * of a char is TRUE if it is the string "white", else FALSE.
1791 static void
1792 init ()
1794 register char *sp;
1795 register int i;
1797 for (i = 0; i < CHARS; i++)
1798 iswhite(i) = notinname(i) = begtoken(i) = intoken(i) = endtoken(i) = FALSE;
1799 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1800 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1801 notinname('\0') = notinname('\n');
1802 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1803 begtoken('\0') = begtoken('\n');
1804 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1805 intoken('\0') = intoken('\n');
1806 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1807 endtoken('\0') = endtoken('\n');
1811 * This routine opens the specified file and calls the function
1812 * which finds the function and type definitions.
1814 static void
1815 find_entries (inf)
1816 FILE *inf;
1818 char *cp;
1819 language *lang = curfdp->lang;
1820 Lang_function *parser = NULL;
1822 /* If user specified a language, use it. */
1823 if (lang != NULL && lang->function != NULL)
1825 parser = lang->function;
1828 /* Else try to guess the language given the file name. */
1829 if (parser == NULL)
1831 lang = get_language_from_filename (curfdp->infname, TRUE);
1832 if (lang != NULL && lang->function != NULL)
1834 curfdp->lang = lang;
1835 parser = lang->function;
1839 /* Else look for sharp-bang as the first two characters. */
1840 if (parser == NULL
1841 && readline_internal (&lb, inf) > 0
1842 && lb.len >= 2
1843 && lb.buffer[0] == '#'
1844 && lb.buffer[1] == '!')
1846 char *lp;
1848 /* Set lp to point at the first char after the last slash in the
1849 line or, if no slashes, at the first nonblank. Then set cp to
1850 the first successive blank and terminate the string. */
1851 lp = etags_strrchr (lb.buffer+2, '/');
1852 if (lp != NULL)
1853 lp += 1;
1854 else
1855 lp = skip_spaces (lb.buffer + 2);
1856 cp = skip_non_spaces (lp);
1857 *cp = '\0';
1859 if (strlen (lp) > 0)
1861 lang = get_language_from_interpreter (lp);
1862 if (lang != NULL && lang->function != NULL)
1864 curfdp->lang = lang;
1865 parser = lang->function;
1870 /* We rewind here, even if inf may be a pipe. We fail if the
1871 length of the first line is longer than the pipe block size,
1872 which is unlikely. */
1873 rewind (inf);
1875 /* Else try to guess the language given the case insensitive file name. */
1876 if (parser == NULL)
1878 lang = get_language_from_filename (curfdp->infname, FALSE);
1879 if (lang != NULL && lang->function != NULL)
1881 curfdp->lang = lang;
1882 parser = lang->function;
1886 /* Else try Fortran or C. */
1887 if (parser == NULL)
1889 node *old_last_node = last_node;
1891 curfdp->lang = get_language_from_langname ("fortran");
1892 find_entries (inf);
1894 if (old_last_node == last_node)
1895 /* No Fortran entries found. Try C. */
1897 /* We do not tag if rewind fails.
1898 Only the file name will be recorded in the tags file. */
1899 rewind (inf);
1900 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1901 find_entries (inf);
1903 return;
1906 if (!no_line_directive
1907 && curfdp->lang != NULL && curfdp->lang->metasource)
1908 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1909 file, or anyway we parsed a file that is automatically generated from
1910 this one. If this is the case, the bingo.c file contained #line
1911 directives that generated tags pointing to this file. Let's delete
1912 them all before parsing this file, which is the real source. */
1914 fdesc **fdpp = &fdhead;
1915 while (*fdpp != NULL)
1916 if (*fdpp != curfdp
1917 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1918 /* We found one of those! We must delete both the file description
1919 and all tags referring to it. */
1921 fdesc *badfdp = *fdpp;
1923 /* Delete the tags referring to badfdp->taggedfname
1924 that were obtained from badfdp->infname. */
1925 invalidate_nodes (badfdp, &nodehead);
1927 *fdpp = badfdp->next; /* remove the bad description from the list */
1928 free_fdesc (badfdp);
1930 else
1931 fdpp = &(*fdpp)->next; /* advance the list pointer */
1934 assert (parser != NULL);
1936 /* Generic initialisations before reading from file. */
1937 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1939 /* Generic initialisations before parsing file with readline. */
1940 lineno = 0; /* reset global line number */
1941 charno = 0; /* reset global char number */
1942 linecharno = 0; /* reset global char number of line start */
1944 parser (inf);
1946 #ifdef ETAGS_REGEXPS
1947 regex_tag_multiline ();
1948 #endif /* ETAGS_REGEXPS */
1953 * Check whether an implicitly named tag should be created,
1954 * then call `pfnote'.
1955 * NAME is a string that is internally copied by this function.
1957 * TAGS format specification
1958 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1959 * The following is explained in some more detail in etc/ETAGS.EBNF.
1961 * make_tag creates tags with "implicit tag names" (unnamed tags)
1962 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1963 * 1. NAME does not contain any of the characters in NONAM;
1964 * 2. LINESTART contains name as either a rightmost, or rightmost but
1965 * one character, substring;
1966 * 3. the character, if any, immediately before NAME in LINESTART must
1967 * be a character in NONAM;
1968 * 4. the character, if any, immediately after NAME in LINESTART must
1969 * also be a character in NONAM.
1971 * The implementation uses the notinname() macro, which recognises the
1972 * characters stored in the string `nonam'.
1973 * etags.el needs to use the same characters that are in NONAM.
1975 static void
1976 make_tag (name, namelen, is_func, linestart, linelen, lno, cno)
1977 char *name; /* tag name, or NULL if unnamed */
1978 int namelen; /* tag length */
1979 bool is_func; /* tag is a function */
1980 char *linestart; /* start of the line where tag is */
1981 int linelen; /* length of the line where tag is */
1982 int lno; /* line number */
1983 long cno; /* character number */
1985 bool named = (name != NULL && namelen > 0);
1987 if (!CTAGS && named) /* maybe set named to false */
1988 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1989 such that etags.el can guess a name from it. */
1991 int i;
1992 register char *cp = name;
1994 for (i = 0; i < namelen; i++)
1995 if (notinname (*cp++))
1996 break;
1997 if (i == namelen) /* rule #1 */
1999 cp = linestart + linelen - namelen;
2000 if (notinname (linestart[linelen-1]))
2001 cp -= 1; /* rule #4 */
2002 if (cp >= linestart /* rule #2 */
2003 && (cp == linestart
2004 || notinname (cp[-1])) /* rule #3 */
2005 && strneq (name, cp, namelen)) /* rule #2 */
2006 named = FALSE; /* use implicit tag name */
2010 if (named)
2011 name = savenstr (name, namelen);
2012 else
2013 name = NULL;
2014 pfnote (name, is_func, linestart, linelen, lno, cno);
2017 /* Record a tag. */
2018 static void
2019 pfnote (name, is_func, linestart, linelen, lno, cno)
2020 char *name; /* tag name, or NULL if unnamed */
2021 bool is_func; /* tag is a function */
2022 char *linestart; /* start of the line where tag is */
2023 int linelen; /* length of the line where tag is */
2024 int lno; /* line number */
2025 long cno; /* character number */
2027 register node *np;
2029 assert (name == NULL || name[0] != '\0');
2030 if (CTAGS && name == NULL)
2031 return;
2033 np = xnew (1, node);
2035 /* If ctags mode, change name "main" to M<thisfilename>. */
2036 if (CTAGS && !cxref_style && streq (name, "main"))
2038 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
2039 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
2040 fp = etags_strrchr (np->name, '.');
2041 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
2042 fp[0] = '\0';
2044 else
2045 np->name = name;
2046 np->valid = TRUE;
2047 np->been_warned = FALSE;
2048 np->fdp = curfdp;
2049 np->is_func = is_func;
2050 np->lno = lno;
2051 if (np->fdp->usecharno)
2052 /* Our char numbers are 0-base, because of C language tradition?
2053 ctags compatibility? old versions compatibility? I don't know.
2054 Anyway, since emacs's are 1-base we expect etags.el to take care
2055 of the difference. If we wanted to have 1-based numbers, we would
2056 uncomment the +1 below. */
2057 np->cno = cno /* + 1 */ ;
2058 else
2059 np->cno = invalidcharno;
2060 np->left = np->right = NULL;
2061 if (CTAGS && !cxref_style)
2063 if (strlen (linestart) < 50)
2064 np->regex = concat (linestart, "$", "");
2065 else
2066 np->regex = savenstr (linestart, 50);
2068 else
2069 np->regex = savenstr (linestart, linelen);
2071 add_node (np, &nodehead);
2075 * free_tree ()
2076 * recurse on left children, iterate on right children.
2078 static void
2079 free_tree (np)
2080 register node *np;
2082 while (np)
2084 register node *node_right = np->right;
2085 free_tree (np->left);
2086 if (np->name != NULL)
2087 free (np->name);
2088 free (np->regex);
2089 free (np);
2090 np = node_right;
2095 * free_fdesc ()
2096 * delete a file description
2098 static void
2099 free_fdesc (fdp)
2100 register fdesc *fdp;
2102 if (fdp->infname != NULL) free (fdp->infname);
2103 if (fdp->infabsname != NULL) free (fdp->infabsname);
2104 if (fdp->infabsdir != NULL) free (fdp->infabsdir);
2105 if (fdp->taggedfname != NULL) free (fdp->taggedfname);
2106 if (fdp->prop != NULL) free (fdp->prop);
2107 free (fdp);
2111 * add_node ()
2112 * Adds a node to the tree of nodes. In etags mode, sort by file
2113 * name. In ctags mode, sort by tag name. Make no attempt at
2114 * balancing.
2116 * add_node is the only function allowed to add nodes, so it can
2117 * maintain state.
2119 static void
2120 add_node (np, cur_node_p)
2121 node *np, **cur_node_p;
2123 register int dif;
2124 register node *cur_node = *cur_node_p;
2126 if (cur_node == NULL)
2128 *cur_node_p = np;
2129 last_node = np;
2130 return;
2133 if (!CTAGS)
2134 /* Etags Mode */
2136 /* For each file name, tags are in a linked sublist on the right
2137 pointer. The first tags of different files are a linked list
2138 on the left pointer. last_node points to the end of the last
2139 used sublist. */
2140 if (last_node != NULL && last_node->fdp == np->fdp)
2142 /* Let's use the same sublist as the last added node. */
2143 assert (last_node->right == NULL);
2144 last_node->right = np;
2145 last_node = np;
2147 else if (cur_node->fdp == np->fdp)
2149 /* Scanning the list we found the head of a sublist which is
2150 good for us. Let's scan this sublist. */
2151 add_node (np, &cur_node->right);
2153 else
2154 /* The head of this sublist is not good for us. Let's try the
2155 next one. */
2156 add_node (np, &cur_node->left);
2157 } /* if ETAGS mode */
2159 else
2161 /* Ctags Mode */
2162 dif = strcmp (np->name, cur_node->name);
2165 * If this tag name matches an existing one, then
2166 * do not add the node, but maybe print a warning.
2168 if (!dif)
2170 if (np->fdp == cur_node->fdp)
2172 if (!no_warnings)
2174 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2175 np->fdp->infname, lineno, np->name);
2176 fprintf (stderr, "Second entry ignored\n");
2179 else if (!cur_node->been_warned && !no_warnings)
2181 fprintf
2182 (stderr,
2183 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2184 np->fdp->infname, cur_node->fdp->infname, np->name);
2185 cur_node->been_warned = TRUE;
2187 return;
2190 /* Actually add the node */
2191 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2192 } /* if CTAGS mode */
2196 * invalidate_nodes ()
2197 * Scan the node tree and invalidate all nodes pointing to the
2198 * given file description (CTAGS case) or free them (ETAGS case).
2200 static void
2201 invalidate_nodes (badfdp, npp)
2202 fdesc *badfdp;
2203 node **npp;
2205 node *np = *npp;
2207 if (np == NULL)
2208 return;
2210 if (CTAGS)
2212 if (np->left != NULL)
2213 invalidate_nodes (badfdp, &np->left);
2214 if (np->fdp == badfdp)
2215 np->valid = FALSE;
2216 if (np->right != NULL)
2217 invalidate_nodes (badfdp, &np->right);
2219 else
2221 assert (np->fdp != NULL);
2222 if (np->fdp == badfdp)
2224 *npp = np->left; /* detach the sublist from the list */
2225 np->left = NULL; /* isolate it */
2226 free_tree (np); /* free it */
2227 invalidate_nodes (badfdp, npp);
2229 else
2230 invalidate_nodes (badfdp, &np->left);
2235 static int total_size_of_entries __P((node *));
2236 static int number_len __P((long));
2238 /* Length of a non-negative number's decimal representation. */
2239 static int
2240 number_len (num)
2241 long num;
2243 int len = 1;
2244 while ((num /= 10) > 0)
2245 len += 1;
2246 return len;
2250 * Return total number of characters that put_entries will output for
2251 * the nodes in the linked list at the right of the specified node.
2252 * This count is irrelevant with etags.el since emacs 19.34 at least,
2253 * but is still supplied for backward compatibility.
2255 static int
2256 total_size_of_entries (np)
2257 register node *np;
2259 register int total = 0;
2261 for (; np != NULL; np = np->right)
2262 if (np->valid)
2264 total += strlen (np->regex) + 1; /* pat\177 */
2265 if (np->name != NULL)
2266 total += strlen (np->name) + 1; /* name\001 */
2267 total += number_len ((long) np->lno) + 1; /* lno, */
2268 if (np->cno != invalidcharno) /* cno */
2269 total += number_len (np->cno);
2270 total += 1; /* newline */
2273 return total;
2276 static void
2277 put_entries (np)
2278 register node *np;
2280 register char *sp;
2281 static fdesc *fdp = NULL;
2283 if (np == NULL)
2284 return;
2286 /* Output subentries that precede this one */
2287 if (CTAGS)
2288 put_entries (np->left);
2290 /* Output this entry */
2291 if (np->valid)
2293 if (!CTAGS)
2295 /* Etags mode */
2296 if (fdp != np->fdp)
2298 fdp = np->fdp;
2299 fprintf (tagf, "\f\n%s,%d\n",
2300 fdp->taggedfname, total_size_of_entries (np));
2301 fdp->written = TRUE;
2303 fputs (np->regex, tagf);
2304 fputc ('\177', tagf);
2305 if (np->name != NULL)
2307 fputs (np->name, tagf);
2308 fputc ('\001', tagf);
2310 fprintf (tagf, "%d,", np->lno);
2311 if (np->cno != invalidcharno)
2312 fprintf (tagf, "%ld", np->cno);
2313 fputs ("\n", tagf);
2315 else
2317 /* Ctags mode */
2318 if (np->name == NULL)
2319 error ("internal error: NULL name in ctags mode.", (char *)NULL);
2321 if (cxref_style)
2323 if (vgrind_style)
2324 fprintf (stdout, "%s %s %d\n",
2325 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2326 else
2327 fprintf (stdout, "%-16s %3d %-16s %s\n",
2328 np->name, np->lno, np->fdp->taggedfname, np->regex);
2330 else
2332 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2334 if (np->is_func)
2335 { /* function or #define macro with args */
2336 putc (searchar, tagf);
2337 putc ('^', tagf);
2339 for (sp = np->regex; *sp; sp++)
2341 if (*sp == '\\' || *sp == searchar)
2342 putc ('\\', tagf);
2343 putc (*sp, tagf);
2345 putc (searchar, tagf);
2347 else
2348 { /* anything else; text pattern inadequate */
2349 fprintf (tagf, "%d", np->lno);
2351 putc ('\n', tagf);
2354 } /* if this node contains a valid tag */
2356 /* Output subentries that follow this one */
2357 put_entries (np->right);
2358 if (!CTAGS)
2359 put_entries (np->left);
2363 /* C extensions. */
2364 #define C_EXT 0x00fff /* C extensions */
2365 #define C_PLAIN 0x00000 /* C */
2366 #define C_PLPL 0x00001 /* C++ */
2367 #define C_STAR 0x00003 /* C* */
2368 #define C_JAVA 0x00005 /* JAVA */
2369 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2370 #define YACC 0x10000 /* yacc file */
2373 * The C symbol tables.
2375 enum sym_type
2377 st_none,
2378 st_C_objprot, st_C_objimpl, st_C_objend,
2379 st_C_gnumacro,
2380 st_C_ignore,
2381 st_C_javastruct,
2382 st_C_operator,
2383 st_C_class, st_C_template,
2384 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
2387 static unsigned int hash __P((const char *, unsigned int));
2388 static struct C_stab_entry * in_word_set __P((const char *, unsigned int));
2389 static enum sym_type C_symtype __P((char *, int, int));
2391 /* Feed stuff between (but not including) %[ and %] lines to:
2392 gperf -c -k 1,3 -o -p -r -t
2394 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2396 if, 0, st_C_ignore
2397 for, 0, st_C_ignore
2398 while, 0, st_C_ignore
2399 switch, 0, st_C_ignore
2400 return, 0, st_C_ignore
2401 @interface, 0, st_C_objprot
2402 @protocol, 0, st_C_objprot
2403 @implementation,0, st_C_objimpl
2404 @end, 0, st_C_objend
2405 import, C_JAVA, st_C_ignore
2406 package, C_JAVA, st_C_ignore
2407 friend, C_PLPL, st_C_ignore
2408 extends, C_JAVA, st_C_javastruct
2409 implements, C_JAVA, st_C_javastruct
2410 interface, C_JAVA, st_C_struct
2411 class, 0, st_C_class
2412 namespace, C_PLPL, st_C_struct
2413 domain, C_STAR, st_C_struct
2414 union, 0, st_C_struct
2415 struct, 0, st_C_struct
2416 extern, 0, st_C_extern
2417 enum, 0, st_C_enum
2418 typedef, 0, st_C_typedef
2419 define, 0, st_C_define
2420 operator, C_PLPL, st_C_operator
2421 template, 0, st_C_template
2422 bool, C_PLPL, st_C_typespec
2423 long, 0, st_C_typespec
2424 short, 0, st_C_typespec
2425 int, 0, st_C_typespec
2426 char, 0, st_C_typespec
2427 float, 0, st_C_typespec
2428 double, 0, st_C_typespec
2429 signed, 0, st_C_typespec
2430 unsigned, 0, st_C_typespec
2431 auto, 0, st_C_typespec
2432 void, 0, st_C_typespec
2433 static, 0, st_C_typespec
2434 const, 0, st_C_typespec
2435 volatile, 0, st_C_typespec
2436 explicit, C_PLPL, st_C_typespec
2437 mutable, C_PLPL, st_C_typespec
2438 typename, C_PLPL, st_C_typespec
2439 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2440 DEFUN, 0, st_C_gnumacro
2441 SYSCALL, 0, st_C_gnumacro
2442 ENTRY, 0, st_C_gnumacro
2443 PSEUDO, 0, st_C_gnumacro
2444 # These are defined inside C functions, so currently they are not met.
2445 # EXFUN used in glibc, DEFVAR_* in emacs.
2446 #EXFUN, 0, st_C_gnumacro
2447 #DEFVAR_, 0, st_C_gnumacro
2449 and replace lines between %< and %> with its output,
2450 then make in_word_set and C_stab_entry static. */
2451 /*%<*/
2452 /* C code produced by gperf version 2.7.1 (19981006 egcs) */
2453 /* Command-line: gperf -c -k 1,3 -o -p -r -t */
2454 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
2456 #define TOTAL_KEYWORDS 47
2457 #define MIN_WORD_LENGTH 2
2458 #define MAX_WORD_LENGTH 15
2459 #define MIN_HASH_VALUE 18
2460 #define MAX_HASH_VALUE 138
2461 /* maximum key range = 121, duplicates = 0 */
2463 #ifdef __GNUC__
2464 __inline
2465 #endif
2466 static unsigned int
2467 hash (str, len)
2468 register const char *str;
2469 register unsigned int len;
2471 static unsigned char asso_values[] =
2473 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2474 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2475 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2476 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2477 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2478 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2479 139, 139, 139, 139, 63, 139, 139, 139, 33, 44,
2480 62, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2481 42, 139, 139, 12, 32, 139, 139, 139, 139, 139,
2482 139, 139, 139, 139, 139, 139, 139, 34, 59, 37,
2483 24, 58, 33, 3, 139, 16, 139, 139, 42, 60,
2484 18, 11, 39, 139, 23, 57, 4, 63, 6, 20,
2485 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2486 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2487 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2488 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2489 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2490 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2491 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2492 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2493 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2494 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2495 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2496 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2497 139, 139, 139, 139, 139, 139, 139, 139, 139, 139,
2498 139, 139, 139, 139, 139, 139
2500 register int hval = len;
2502 switch (hval)
2504 default:
2505 case 3:
2506 hval += asso_values[(unsigned char)str[2]];
2507 case 2:
2508 case 1:
2509 hval += asso_values[(unsigned char)str[0]];
2510 break;
2512 return hval;
2515 #ifdef __GNUC__
2516 __inline
2517 #endif
2518 static struct C_stab_entry *
2519 in_word_set (str, len)
2520 register const char *str;
2521 register unsigned int len;
2523 static struct C_stab_entry wordlist[] =
2525 {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
2526 {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
2527 {"if", 0, st_C_ignore},
2528 {""}, {""}, {""}, {""},
2529 {"int", 0, st_C_typespec},
2530 {""}, {""},
2531 {"void", 0, st_C_typespec},
2532 {""}, {""},
2533 {"interface", C_JAVA, st_C_struct},
2534 {""},
2535 {"SYSCALL", 0, st_C_gnumacro},
2536 {""},
2537 {"return", 0, st_C_ignore},
2538 {""}, {""}, {""}, {""}, {""}, {""}, {""},
2539 {"while", 0, st_C_ignore},
2540 {"auto", 0, st_C_typespec},
2541 {""}, {""}, {""}, {""}, {""}, {""},
2542 {"float", 0, st_C_typespec},
2543 {"typedef", 0, st_C_typedef},
2544 {"typename", C_PLPL, st_C_typespec},
2545 {""}, {""}, {""},
2546 {"friend", C_PLPL, st_C_ignore},
2547 {"volatile", 0, st_C_typespec},
2548 {""}, {""},
2549 {"for", 0, st_C_ignore},
2550 {"const", 0, st_C_typespec},
2551 {"import", C_JAVA, st_C_ignore},
2552 {""},
2553 {"define", 0, st_C_define},
2554 {"long", 0, st_C_typespec},
2555 {"implements", C_JAVA, st_C_javastruct},
2556 {"signed", 0, st_C_typespec},
2557 {""},
2558 {"extern", 0, st_C_extern},
2559 {"extends", C_JAVA, st_C_javastruct},
2560 {""},
2561 {"mutable", C_PLPL, st_C_typespec},
2562 {"template", 0, st_C_template},
2563 {"short", 0, st_C_typespec},
2564 {"bool", C_PLPL, st_C_typespec},
2565 {"char", 0, st_C_typespec},
2566 {"class", 0, st_C_class},
2567 {"operator", C_PLPL, st_C_operator},
2568 {""},
2569 {"switch", 0, st_C_ignore},
2570 {""},
2571 {"ENTRY", 0, st_C_gnumacro},
2572 {""},
2573 {"package", C_JAVA, st_C_ignore},
2574 {"union", 0, st_C_struct},
2575 {"@end", 0, st_C_objend},
2576 {"struct", 0, st_C_struct},
2577 {"namespace", C_PLPL, st_C_struct},
2578 {""}, {""},
2579 {"domain", C_STAR, st_C_struct},
2580 {"@interface", 0, st_C_objprot},
2581 {"PSEUDO", 0, st_C_gnumacro},
2582 {"double", 0, st_C_typespec},
2583 {""},
2584 {"@protocol", 0, st_C_objprot},
2585 {""},
2586 {"static", 0, st_C_typespec},
2587 {""}, {""},
2588 {"DEFUN", 0, st_C_gnumacro},
2589 {""}, {""}, {""}, {""},
2590 {"explicit", C_PLPL, st_C_typespec},
2591 {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
2592 {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
2593 {""},
2594 {"enum", 0, st_C_enum},
2595 {""}, {""},
2596 {"unsigned", 0, st_C_typespec},
2597 {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
2598 {"@implementation",0, st_C_objimpl}
2601 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2603 register int key = hash (str, len);
2605 if (key <= MAX_HASH_VALUE && key >= 0)
2607 register const char *s = wordlist[key].name;
2609 if (*str == *s && !strncmp (str + 1, s + 1, len - 1))
2610 return &wordlist[key];
2613 return 0;
2615 /*%>*/
2617 static enum sym_type
2618 C_symtype (str, len, c_ext)
2619 char *str;
2620 int len;
2621 int c_ext;
2623 register struct C_stab_entry *se = in_word_set (str, len);
2625 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2626 return st_none;
2627 return se->type;
2632 * C functions and variables are recognized using a simple
2633 * finite automaton. fvdef is its state variable.
2635 static enum
2637 fvnone, /* nothing seen */
2638 fdefunkey, /* Emacs DEFUN keyword seen */
2639 fdefunname, /* Emacs DEFUN name seen */
2640 foperator, /* func: operator keyword seen (cplpl) */
2641 fvnameseen, /* function or variable name seen */
2642 fstartlist, /* func: just after open parenthesis */
2643 finlist, /* func: in parameter list */
2644 flistseen, /* func: after parameter list */
2645 fignore, /* func: before open brace */
2646 vignore /* var-like: ignore until ';' */
2647 } fvdef;
2649 static bool fvextern; /* func or var: extern keyword seen; */
2652 * typedefs are recognized using a simple finite automaton.
2653 * typdef is its state variable.
2655 static enum
2657 tnone, /* nothing seen */
2658 tkeyseen, /* typedef keyword seen */
2659 ttypeseen, /* defined type seen */
2660 tinbody, /* inside typedef body */
2661 tend, /* just before typedef tag */
2662 tignore /* junk after typedef tag */
2663 } typdef;
2666 * struct-like structures (enum, struct and union) are recognized
2667 * using another simple finite automaton. `structdef' is its state
2668 * variable.
2670 static enum
2672 snone, /* nothing seen yet,
2673 or in struct body if cblev > 0 */
2674 skeyseen, /* struct-like keyword seen */
2675 stagseen, /* struct-like tag seen */
2676 sintemplate, /* inside template (ignore) */
2677 scolonseen /* colon seen after struct-like tag */
2678 } structdef;
2681 * When objdef is different from onone, objtag is the name of the class.
2683 static char *objtag = "<uninited>";
2686 * Yet another little state machine to deal with preprocessor lines.
2688 static enum
2690 dnone, /* nothing seen */
2691 dsharpseen, /* '#' seen as first char on line */
2692 ddefineseen, /* '#' and 'define' seen */
2693 dignorerest /* ignore rest of line */
2694 } definedef;
2697 * State machine for Objective C protocols and implementations.
2698 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2700 static enum
2702 onone, /* nothing seen */
2703 oprotocol, /* @interface or @protocol seen */
2704 oimplementation, /* @implementations seen */
2705 otagseen, /* class name seen */
2706 oparenseen, /* parenthesis before category seen */
2707 ocatseen, /* category name seen */
2708 oinbody, /* in @implementation body */
2709 omethodsign, /* in @implementation body, after +/- */
2710 omethodtag, /* after method name */
2711 omethodcolon, /* after method colon */
2712 omethodparm, /* after method parameter */
2713 oignore /* wait for @end */
2714 } objdef;
2718 * Use this structure to keep info about the token read, and how it
2719 * should be tagged. Used by the make_C_tag function to build a tag.
2721 static struct tok
2723 char *line; /* string containing the token */
2724 int offset; /* where the token starts in LINE */
2725 int length; /* token length */
2727 The previous members can be used to pass strings around for generic
2728 purposes. The following ones specifically refer to creating tags. In this
2729 case the token contained here is the pattern that will be used to create a
2730 tag.
2732 bool valid; /* do not create a tag; the token should be
2733 invalidated whenever a state machine is
2734 reset prematurely */
2735 bool named; /* create a named tag */
2736 int lineno; /* source line number of tag */
2737 long linepos; /* source char number of tag */
2738 } token; /* latest token read */
2741 * Variables and functions for dealing with nested structures.
2742 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2744 static void pushclass_above __P((int, char *, int));
2745 static void popclass_above __P((int));
2746 static void write_classname __P((linebuffer *, char *qualifier));
2748 static struct {
2749 char **cname; /* nested class names */
2750 int *cblev; /* nested class curly brace level */
2751 int nl; /* class nesting level (elements used) */
2752 int size; /* length of the array */
2753 } cstack; /* stack for nested declaration tags */
2754 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2755 #define nestlev (cstack.nl)
2756 /* After struct keyword or in struct body, not inside a nested function. */
2757 #define instruct (structdef == snone && nestlev > 0 \
2758 && cblev == cstack.cblev[nestlev-1] + 1)
2760 static void
2761 pushclass_above (cblev, str, len)
2762 int cblev;
2763 char *str;
2764 int len;
2766 int nl;
2768 popclass_above (cblev);
2769 nl = cstack.nl;
2770 if (nl >= cstack.size)
2772 int size = cstack.size *= 2;
2773 xrnew (cstack.cname, size, char *);
2774 xrnew (cstack.cblev, size, int);
2776 assert (nl == 0 || cstack.cblev[nl-1] < cblev);
2777 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2778 cstack.cblev[nl] = cblev;
2779 cstack.nl = nl + 1;
2782 static void
2783 popclass_above (cblev)
2784 int cblev;
2786 int nl;
2788 for (nl = cstack.nl - 1;
2789 nl >= 0 && cstack.cblev[nl] >= cblev;
2790 nl--)
2792 if (cstack.cname[nl] != NULL)
2793 free (cstack.cname[nl]);
2794 cstack.nl = nl;
2798 static void
2799 write_classname (cn, qualifier)
2800 linebuffer *cn;
2801 char *qualifier;
2803 int i, len;
2804 int qlen = strlen (qualifier);
2806 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2808 len = 0;
2809 cn->len = 0;
2810 cn->buffer[0] = '\0';
2812 else
2814 len = strlen (cstack.cname[0]);
2815 linebuffer_setlen (cn, len);
2816 strcpy (cn->buffer, cstack.cname[0]);
2818 for (i = 1; i < cstack.nl; i++)
2820 char *s;
2821 int slen;
2823 s = cstack.cname[i];
2824 if (s == NULL)
2825 continue;
2826 slen = strlen (s);
2827 len += slen + qlen;
2828 linebuffer_setlen (cn, len);
2829 strncat (cn->buffer, qualifier, qlen);
2830 strncat (cn->buffer, s, slen);
2835 static bool consider_token __P((char *, int, int, int *, int, int, bool *));
2836 static void make_C_tag __P((bool));
2839 * consider_token ()
2840 * checks to see if the current token is at the start of a
2841 * function or variable, or corresponds to a typedef, or
2842 * is a struct/union/enum tag, or #define, or an enum constant.
2844 * *IS_FUNC gets TRUE iff the token is a function or #define macro
2845 * with args. C_EXTP points to which language we are looking at.
2847 * Globals
2848 * fvdef IN OUT
2849 * structdef IN OUT
2850 * definedef IN OUT
2851 * typdef IN OUT
2852 * objdef IN OUT
2855 static bool
2856 consider_token (str, len, c, c_extp, cblev, parlev, is_func_or_var)
2857 register char *str; /* IN: token pointer */
2858 register int len; /* IN: token length */
2859 register int c; /* IN: first char after the token */
2860 int *c_extp; /* IN, OUT: C extensions mask */
2861 int cblev; /* IN: curly brace level */
2862 int parlev; /* IN: parenthesis level */
2863 bool *is_func_or_var; /* OUT: function or variable found */
2865 /* When structdef is stagseen, scolonseen, or snone with cblev > 0,
2866 structtype is the type of the preceding struct-like keyword, and
2867 structcblev is the curly brace level where it has been seen. */
2868 static enum sym_type structtype;
2869 static int structcblev;
2870 static enum sym_type toktype;
2873 toktype = C_symtype (str, len, *c_extp);
2876 * Advance the definedef state machine.
2878 switch (definedef)
2880 case dnone:
2881 /* We're not on a preprocessor line. */
2882 if (toktype == st_C_gnumacro)
2884 fvdef = fdefunkey;
2885 return FALSE;
2887 break;
2888 case dsharpseen:
2889 if (toktype == st_C_define)
2891 definedef = ddefineseen;
2893 else
2895 definedef = dignorerest;
2897 return FALSE;
2898 case ddefineseen:
2900 * Make a tag for any macro, unless it is a constant
2901 * and constantypedefs is FALSE.
2903 definedef = dignorerest;
2904 *is_func_or_var = (c == '(');
2905 if (!*is_func_or_var && !constantypedefs)
2906 return FALSE;
2907 else
2908 return TRUE;
2909 case dignorerest:
2910 return FALSE;
2911 default:
2912 error ("internal error: definedef value.", (char *)NULL);
2916 * Now typedefs
2918 switch (typdef)
2920 case tnone:
2921 if (toktype == st_C_typedef)
2923 if (typedefs)
2924 typdef = tkeyseen;
2925 fvextern = FALSE;
2926 fvdef = fvnone;
2927 return FALSE;
2929 break;
2930 case tkeyseen:
2931 switch (toktype)
2933 case st_none:
2934 case st_C_typespec:
2935 case st_C_class:
2936 case st_C_struct:
2937 case st_C_enum:
2938 typdef = ttypeseen;
2939 break;
2941 break;
2942 case ttypeseen:
2943 if (structdef == snone && fvdef == fvnone)
2945 fvdef = fvnameseen;
2946 return TRUE;
2948 break;
2949 case tend:
2950 switch (toktype)
2952 case st_C_typespec:
2953 case st_C_class:
2954 case st_C_struct:
2955 case st_C_enum:
2956 return FALSE;
2958 return TRUE;
2962 * This structdef business is NOT invoked when we are ctags and the
2963 * file is plain C. This is because a struct tag may have the same
2964 * name as another tag, and this loses with ctags.
2966 switch (toktype)
2968 case st_C_javastruct:
2969 if (structdef == stagseen)
2970 structdef = scolonseen;
2971 return FALSE;
2972 case st_C_template:
2973 case st_C_class:
2974 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2975 && cblev == 0
2976 && definedef == dnone && structdef == snone
2977 && typdef == tnone && fvdef == fvnone)
2978 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2979 if (toktype == st_C_template)
2980 break;
2981 /* FALLTHRU */
2982 case st_C_struct:
2983 case st_C_enum:
2984 if (parlev == 0
2985 && fvdef != vignore
2986 && (typdef == tkeyseen
2987 || (typedefs_or_cplusplus && structdef == snone)))
2989 structdef = skeyseen;
2990 structtype = toktype;
2991 structcblev = cblev;
2993 return FALSE;
2996 if (structdef == skeyseen)
2998 structdef = stagseen;
2999 return TRUE;
3002 if (typdef != tnone)
3003 definedef = dnone;
3005 /* Detect Objective C constructs. */
3006 switch (objdef)
3008 case onone:
3009 switch (toktype)
3011 case st_C_objprot:
3012 objdef = oprotocol;
3013 return FALSE;
3014 case st_C_objimpl:
3015 objdef = oimplementation;
3016 return FALSE;
3018 break;
3019 case oimplementation:
3020 /* Save the class tag for functions or variables defined inside. */
3021 objtag = savenstr (str, len);
3022 objdef = oinbody;
3023 return FALSE;
3024 case oprotocol:
3025 /* Save the class tag for categories. */
3026 objtag = savenstr (str, len);
3027 objdef = otagseen;
3028 *is_func_or_var = TRUE;
3029 return TRUE;
3030 case oparenseen:
3031 objdef = ocatseen;
3032 *is_func_or_var = TRUE;
3033 return TRUE;
3034 case oinbody:
3035 break;
3036 case omethodsign:
3037 if (parlev == 0)
3039 objdef = omethodtag;
3040 linebuffer_setlen (&token_name, len);
3041 strncpy (token_name.buffer, str, len);
3042 token_name.buffer[len] = '\0';
3043 return TRUE;
3045 return FALSE;
3046 case omethodcolon:
3047 if (parlev == 0)
3048 objdef = omethodparm;
3049 return FALSE;
3050 case omethodparm:
3051 if (parlev == 0)
3053 objdef = omethodtag;
3054 linebuffer_setlen (&token_name, token_name.len + len);
3055 strncat (token_name.buffer, str, len);
3056 return TRUE;
3058 return FALSE;
3059 case oignore:
3060 if (toktype == st_C_objend)
3062 /* Memory leakage here: the string pointed by objtag is
3063 never released, because many tests would be needed to
3064 avoid breaking on incorrect input code. The amount of
3065 memory leaked here is the sum of the lengths of the
3066 class tags.
3067 free (objtag); */
3068 objdef = onone;
3070 return FALSE;
3073 /* A function, variable or enum constant? */
3074 switch (toktype)
3076 case st_C_extern:
3077 fvextern = TRUE;
3078 /* FALLTHRU */
3079 case st_C_typespec:
3080 switch (fvdef)
3082 case finlist:
3083 case flistseen:
3084 case fignore:
3085 case vignore:
3086 break;
3087 default:
3088 fvdef = fvnone;
3090 return FALSE;
3091 case st_C_ignore:
3092 fvextern = FALSE;
3093 fvdef = vignore;
3094 return FALSE;
3095 case st_C_operator:
3096 fvdef = foperator;
3097 *is_func_or_var = TRUE;
3098 return TRUE;
3099 case st_none:
3100 if (constantypedefs
3101 && structdef == snone
3102 && structtype == st_C_enum && cblev > structcblev)
3103 return TRUE; /* enum constant */
3104 switch (fvdef)
3106 case fdefunkey:
3107 if (cblev > 0)
3108 break;
3109 fvdef = fdefunname; /* GNU macro */
3110 *is_func_or_var = TRUE;
3111 return TRUE;
3112 case fvnone:
3113 if ((strneq (str, "asm", 3) && endtoken (str[3]))
3114 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
3116 fvdef = vignore;
3117 return FALSE;
3119 if (strneq (str+len-10, "::operator", 10))
3121 if (*c_extp & C_AUTO) /* automatic detection of C++ */
3122 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
3123 fvdef = foperator;
3124 *is_func_or_var = TRUE;
3125 return TRUE;
3127 if (cblev > 0 && !instruct)
3128 break;
3129 fvdef = fvnameseen; /* function or variable */
3130 *is_func_or_var = TRUE;
3131 return TRUE;
3133 break;
3136 return FALSE;
3141 * C_entries often keeps pointers to tokens or lines which are older than
3142 * the line currently read. By keeping two line buffers, and switching
3143 * them at end of line, it is possible to use those pointers.
3145 static struct
3147 long linepos;
3148 linebuffer lb;
3149 } lbs[2];
3151 #define current_lb_is_new (newndx == curndx)
3152 #define switch_line_buffers() (curndx = 1 - curndx)
3154 #define curlb (lbs[curndx].lb)
3155 #define newlb (lbs[newndx].lb)
3156 #define curlinepos (lbs[curndx].linepos)
3157 #define newlinepos (lbs[newndx].linepos)
3159 #define plainc ((c_ext & C_EXT) == C_PLAIN)
3160 #define cplpl (c_ext & C_PLPL)
3161 #define cjava ((c_ext & C_JAVA) == C_JAVA)
3163 #define CNL_SAVE_DEFINEDEF() \
3164 do { \
3165 curlinepos = charno; \
3166 readline (&curlb, inf); \
3167 lp = curlb.buffer; \
3168 quotednl = FALSE; \
3169 newndx = curndx; \
3170 } while (0)
3172 #define CNL() \
3173 do { \
3174 CNL_SAVE_DEFINEDEF(); \
3175 if (savetoken.valid) \
3177 token = savetoken; \
3178 savetoken.valid = FALSE; \
3180 definedef = dnone; \
3181 } while (0)
3184 static void
3185 make_C_tag (isfun)
3186 bool isfun;
3188 /* This function should never be called when token.valid is FALSE, but
3189 we must protect against invalid input or internal errors. */
3190 if (!DEBUG && !token.valid)
3191 return;
3193 if (token.valid)
3194 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3195 token.offset+token.length+1, token.lineno, token.linepos);
3196 else /* this case is optimised away if !DEBUG */
3197 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3198 token_name.len + 17, isfun, token.line,
3199 token.offset+token.length+1, token.lineno, token.linepos);
3201 token.valid = FALSE;
3206 * C_entries ()
3207 * This routine finds functions, variables, typedefs,
3208 * #define's, enum constants and struct/union/enum definitions in
3209 * C syntax and adds them to the list.
3211 static void
3212 C_entries (c_ext, inf)
3213 int c_ext; /* extension of C */
3214 FILE *inf; /* input file */
3216 register char c; /* latest char read; '\0' for end of line */
3217 register char *lp; /* pointer one beyond the character `c' */
3218 int curndx, newndx; /* indices for current and new lb */
3219 register int tokoff; /* offset in line of start of current token */
3220 register int toklen; /* length of current token */
3221 char *qualifier; /* string used to qualify names */
3222 int qlen; /* length of qualifier */
3223 int cblev; /* current curly brace level */
3224 int parlev; /* current parenthesis level */
3225 int typdefcblev; /* cblev where a typedef struct body begun */
3226 bool incomm, inquote, inchar, quotednl, midtoken;
3227 bool yacc_rules; /* in the rules part of a yacc file */
3228 struct tok savetoken; /* token saved during preprocessor handling */
3231 linebuffer_init (&lbs[0].lb);
3232 linebuffer_init (&lbs[1].lb);
3233 if (cstack.size == 0)
3235 cstack.size = (DEBUG) ? 1 : 4;
3236 cstack.nl = 0;
3237 cstack.cname = xnew (cstack.size, char *);
3238 cstack.cblev = xnew (cstack.size, int);
3241 tokoff = toklen = typdefcblev = 0; /* keep compiler quiet */
3242 curndx = newndx = 0;
3243 lp = curlb.buffer;
3244 *lp = 0;
3246 fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3247 structdef = snone; definedef = dnone; objdef = onone;
3248 yacc_rules = FALSE;
3249 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3250 token.valid = savetoken.valid = FALSE;
3251 cblev = 0;
3252 parlev = 0;
3253 if (cjava)
3254 { qualifier = "."; qlen = 1; }
3255 else
3256 { qualifier = "::"; qlen = 2; }
3259 while (!feof (inf))
3261 c = *lp++;
3262 if (c == '\\')
3264 /* If we're at the end of the line, the next character is a
3265 '\0'; don't skip it, because it's the thing that tells us
3266 to read the next line. */
3267 if (*lp == '\0')
3269 quotednl = TRUE;
3270 continue;
3272 lp++;
3273 c = ' ';
3275 else if (incomm)
3277 switch (c)
3279 case '*':
3280 if (*lp == '/')
3282 c = *lp++;
3283 incomm = FALSE;
3285 break;
3286 case '\0':
3287 /* Newlines inside comments do not end macro definitions in
3288 traditional cpp. */
3289 CNL_SAVE_DEFINEDEF ();
3290 break;
3292 continue;
3294 else if (inquote)
3296 switch (c)
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;
3308 continue;
3310 else if (inchar)
3312 switch (c)
3314 case '\0':
3315 /* Hmmm, something went wrong. */
3316 CNL ();
3317 /* FALLTHRU */
3318 case '\'':
3319 inchar = FALSE;
3320 break;
3322 continue;
3324 else
3325 switch (c)
3327 case '"':
3328 inquote = TRUE;
3329 switch (fvdef)
3331 case fdefunkey:
3332 case fstartlist:
3333 case finlist:
3334 case fignore:
3335 case vignore:
3336 break;
3337 default:
3338 fvextern = FALSE;
3339 fvdef = fvnone;
3341 continue;
3342 case '\'':
3343 inchar = TRUE;
3344 if (fvdef != finlist && fvdef != fignore && fvdef !=vignore)
3346 fvextern = FALSE;
3347 fvdef = fvnone;
3349 continue;
3350 case '/':
3351 if (*lp == '*')
3353 lp++;
3354 incomm = TRUE;
3355 continue;
3357 else if (/* cplpl && */ *lp == '/')
3359 c = '\0';
3360 break;
3362 else
3363 break;
3364 case '%':
3365 if ((c_ext & YACC) && *lp == '%')
3367 /* Entering or exiting rules section in yacc file. */
3368 lp++;
3369 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3370 typdef = tnone; structdef = snone;
3371 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3372 cblev = 0;
3373 yacc_rules = !yacc_rules;
3374 continue;
3376 else
3377 break;
3378 case '#':
3379 if (definedef == dnone)
3381 char *cp;
3382 bool cpptoken = TRUE;
3384 /* Look back on this line. If all blanks, or nonblanks
3385 followed by an end of comment, this is a preprocessor
3386 token. */
3387 for (cp = newlb.buffer; cp < lp-1; cp++)
3388 if (!iswhite (*cp))
3390 if (*cp == '*' && *(cp+1) == '/')
3392 cp++;
3393 cpptoken = TRUE;
3395 else
3396 cpptoken = FALSE;
3398 if (cpptoken)
3399 definedef = dsharpseen;
3400 } /* if (definedef == dnone) */
3402 continue;
3403 } /* switch (c) */
3406 /* Consider token only if some involved conditions are satisfied. */
3407 if (typdef != tignore
3408 && definedef != dignorerest
3409 && fvdef != finlist
3410 && structdef != sintemplate
3411 && (definedef != dnone
3412 || structdef != scolonseen))
3414 if (midtoken)
3416 if (endtoken (c))
3418 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3419 /* This handles :: in the middle,
3420 but not at the beginning of an identifier.
3421 Also, space-separated :: is not recognised. */
3423 if (c_ext & C_AUTO) /* automatic detection of C++ */
3424 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3425 lp += 2;
3426 toklen += 2;
3427 c = lp[-1];
3428 goto still_in_token;
3430 else
3432 bool funorvar = FALSE;
3434 if (yacc_rules
3435 || consider_token (newlb.buffer + tokoff, toklen, c,
3436 &c_ext, cblev, parlev, &funorvar))
3438 if (fvdef == foperator)
3440 char *oldlp = lp;
3441 lp = skip_spaces (lp-1);
3442 if (*lp != '\0')
3443 lp += 1;
3444 while (*lp != '\0'
3445 && !iswhite (*lp) && *lp != '(')
3446 lp += 1;
3447 c = *lp++;
3448 toklen += lp - oldlp;
3450 token.named = FALSE;
3451 if (!plainc
3452 && nestlev > 0 && definedef == dnone)
3453 /* in struct body */
3455 write_classname (&token_name, qualifier);
3456 linebuffer_setlen (&token_name,
3457 token_name.len+qlen+toklen);
3458 strcat (token_name.buffer, qualifier);
3459 strncat (token_name.buffer,
3460 newlb.buffer + tokoff, toklen);
3461 token.named = TRUE;
3463 else if (objdef == ocatseen)
3464 /* Objective C category */
3466 int len = strlen (objtag) + 2 + toklen;
3467 linebuffer_setlen (&token_name, len);
3468 strcpy (token_name.buffer, objtag);
3469 strcat (token_name.buffer, "(");
3470 strncat (token_name.buffer,
3471 newlb.buffer + tokoff, toklen);
3472 strcat (token_name.buffer, ")");
3473 token.named = TRUE;
3475 else if (objdef == omethodtag
3476 || objdef == omethodparm)
3477 /* Objective C method */
3479 token.named = TRUE;
3481 else if (fvdef == fdefunname)
3482 /* GNU DEFUN and similar macros */
3484 bool defun = (newlb.buffer[tokoff] == 'F');
3485 int off = tokoff;
3486 int len = toklen;
3488 /* Rewrite the tag so that emacs lisp DEFUNs
3489 can be found by their elisp name */
3490 if (defun)
3492 off += 1;
3493 len -= 1;
3495 len = toklen;
3496 linebuffer_setlen (&token_name, len);
3497 strncpy (token_name.buffer,
3498 newlb.buffer + off, len);
3499 token_name.buffer[len] = '\0';
3500 if (defun)
3501 while (--len >= 0)
3502 if (token_name.buffer[len] == '_')
3503 token_name.buffer[len] = '-';
3504 token.named = defun;
3506 else
3508 linebuffer_setlen (&token_name, toklen);
3509 strncpy (token_name.buffer,
3510 newlb.buffer + tokoff, toklen);
3511 token_name.buffer[toklen] = '\0';
3512 /* Name macros and members. */
3513 token.named = (structdef == stagseen
3514 || typdef == ttypeseen
3515 || typdef == tend
3516 || (funorvar
3517 && definedef == dignorerest)
3518 || (funorvar
3519 && definedef == dnone
3520 && structdef == snone
3521 && cblev > 0));
3523 token.lineno = lineno;
3524 token.offset = tokoff;
3525 token.length = toklen;
3526 token.line = newlb.buffer;
3527 token.linepos = newlinepos;
3528 token.valid = TRUE;
3530 if (definedef == dnone
3531 && (fvdef == fvnameseen
3532 || fvdef == foperator
3533 || structdef == stagseen
3534 || typdef == tend
3535 || typdef == ttypeseen
3536 || objdef != onone))
3538 if (current_lb_is_new)
3539 switch_line_buffers ();
3541 else if (definedef != dnone
3542 || fvdef == fdefunname
3543 || instruct)
3544 make_C_tag (funorvar);
3546 midtoken = FALSE;
3548 } /* if (endtoken (c)) */
3549 else if (intoken (c))
3550 still_in_token:
3552 toklen++;
3553 continue;
3555 } /* if (midtoken) */
3556 else if (begtoken (c))
3558 switch (definedef)
3560 case dnone:
3561 switch (fvdef)
3563 case fstartlist:
3564 fvdef = finlist;
3565 continue;
3566 case flistseen:
3567 if (plainc || declarations)
3569 make_C_tag (TRUE); /* a function */
3570 fvdef = fignore;
3572 break;
3573 case fvnameseen:
3574 fvdef = fvnone;
3575 break;
3577 if (structdef == stagseen && !cjava)
3579 popclass_above (cblev);
3580 structdef = snone;
3582 break;
3583 case dsharpseen:
3584 savetoken = token;
3585 break;
3587 if (!yacc_rules || lp == newlb.buffer + 1)
3589 tokoff = lp - 1 - newlb.buffer;
3590 toklen = 1;
3591 midtoken = TRUE;
3593 continue;
3594 } /* if (begtoken) */
3595 } /* if must look at token */
3598 /* Detect end of line, colon, comma, semicolon and various braces
3599 after having handled a token.*/
3600 switch (c)
3602 case ':':
3603 if (yacc_rules && token.offset == 0 && token.valid)
3605 make_C_tag (FALSE); /* a yacc function */
3606 break;
3608 if (definedef != dnone)
3609 break;
3610 switch (objdef)
3612 case otagseen:
3613 objdef = oignore;
3614 make_C_tag (TRUE); /* an Objective C class */
3615 break;
3616 case omethodtag:
3617 case omethodparm:
3618 objdef = omethodcolon;
3619 linebuffer_setlen (&token_name, token_name.len + 1);
3620 strcat (token_name.buffer, ":");
3621 break;
3623 if (structdef == stagseen)
3625 structdef = scolonseen;
3626 break;
3628 /* Should be useless, but may be work as a safety net. */
3629 if (cplpl && fvdef == flistseen)
3631 make_C_tag (TRUE); /* a function */
3632 fvdef = fignore;
3633 break;
3635 break;
3636 case ';':
3637 if (definedef != dnone)
3638 break;
3639 switch (typdef)
3641 case tend:
3642 case ttypeseen:
3643 make_C_tag (FALSE); /* a typedef */
3644 typdef = tnone;
3645 fvdef = fvnone;
3646 break;
3647 case tnone:
3648 case tinbody:
3649 case tignore:
3650 switch (fvdef)
3652 case fignore:
3653 if (typdef == tignore || cplpl)
3654 fvdef = fvnone;
3655 break;
3656 case fvnameseen:
3657 if ((globals && cblev == 0 && (!fvextern || declarations))
3658 || (members && instruct))
3659 make_C_tag (FALSE); /* a variable */
3660 fvextern = FALSE;
3661 fvdef = fvnone;
3662 token.valid = FALSE;
3663 break;
3664 case flistseen:
3665 if (declarations
3666 && (typdef == tnone || (typdef != tignore && instruct)))
3667 make_C_tag (TRUE); /* a function declaration */
3668 /* FALLTHRU */
3669 default:
3670 fvextern = FALSE;
3671 fvdef = fvnone;
3672 if (declarations
3673 && cplpl && structdef == stagseen)
3674 make_C_tag (FALSE); /* forward declaration */
3675 else
3676 token.valid = FALSE;
3677 } /* switch (fvdef) */
3678 /* FALLTHRU */
3679 default:
3680 if (!instruct)
3681 typdef = tnone;
3683 if (structdef == stagseen)
3684 structdef = snone;
3685 break;
3686 case ',':
3687 if (definedef != dnone)
3688 break;
3689 switch (objdef)
3691 case omethodtag:
3692 case omethodparm:
3693 make_C_tag (TRUE); /* an Objective C method */
3694 objdef = oinbody;
3695 break;
3697 switch (fvdef)
3699 case fdefunkey:
3700 case foperator:
3701 case fstartlist:
3702 case finlist:
3703 case fignore:
3704 case vignore:
3705 break;
3706 case fdefunname:
3707 fvdef = fignore;
3708 break;
3709 case fvnameseen: /* a variable */
3710 if ((globals && cblev == 0 && (!fvextern || declarations))
3711 || (members && instruct))
3712 make_C_tag (FALSE);
3713 break;
3714 case flistseen: /* a function */
3715 if ((declarations && typdef == tnone && !instruct)
3716 || (members && typdef != tignore && instruct))
3718 make_C_tag (TRUE); /* a function declaration */
3719 fvdef = fvnameseen;
3721 else if (!declarations)
3722 fvdef = fvnone;
3723 token.valid = FALSE;
3724 break;
3725 default:
3726 fvdef = fvnone;
3728 if (structdef == stagseen)
3729 structdef = snone;
3730 break;
3731 case '[':
3732 if (definedef != dnone)
3733 break;
3734 if (structdef == stagseen)
3735 structdef = snone;
3736 switch (typdef)
3738 case ttypeseen:
3739 case tend:
3740 typdef = tignore;
3741 make_C_tag (FALSE); /* a typedef */
3742 break;
3743 case tnone:
3744 case tinbody:
3745 switch (fvdef)
3747 case foperator:
3748 case finlist:
3749 case fignore:
3750 case vignore:
3751 break;
3752 case fvnameseen:
3753 if ((members && cblev == 1)
3754 || (globals && cblev == 0
3755 && (!fvextern || declarations)))
3756 make_C_tag (FALSE); /* a variable */
3757 /* FALLTHRU */
3758 default:
3759 fvdef = fvnone;
3761 break;
3763 break;
3764 case '(':
3765 if (definedef != dnone)
3766 break;
3767 if (objdef == otagseen && parlev == 0)
3768 objdef = oparenseen;
3769 switch (fvdef)
3771 case fvnameseen:
3772 if (typdef == ttypeseen
3773 && *lp != '*'
3774 && !instruct)
3776 /* This handles constructs like:
3777 typedef void OperatorFun (int fun); */
3778 make_C_tag (FALSE);
3779 typdef = tignore;
3780 fvdef = fignore;
3781 break;
3783 /* FALLTHRU */
3784 case foperator:
3785 fvdef = fstartlist;
3786 break;
3787 case flistseen:
3788 fvdef = finlist;
3789 break;
3791 parlev++;
3792 break;
3793 case ')':
3794 if (definedef != dnone)
3795 break;
3796 if (objdef == ocatseen && parlev == 1)
3798 make_C_tag (TRUE); /* an Objective C category */
3799 objdef = oignore;
3801 if (--parlev == 0)
3803 switch (fvdef)
3805 case fstartlist:
3806 case finlist:
3807 fvdef = flistseen;
3808 break;
3810 if (!instruct
3811 && (typdef == tend
3812 || typdef == ttypeseen))
3814 typdef = tignore;
3815 make_C_tag (FALSE); /* a typedef */
3818 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
3819 parlev = 0;
3820 break;
3821 case '{':
3822 if (definedef != dnone)
3823 break;
3824 if (typdef == ttypeseen)
3826 /* Whenever typdef is set to tinbody (currently only
3827 here), typdefcblev should be set to cblev. */
3828 typdef = tinbody;
3829 typdefcblev = cblev;
3831 switch (fvdef)
3833 case flistseen:
3834 make_C_tag (TRUE); /* a function */
3835 /* FALLTHRU */
3836 case fignore:
3837 fvdef = fvnone;
3838 break;
3839 case fvnone:
3840 switch (objdef)
3842 case otagseen:
3843 make_C_tag (TRUE); /* an Objective C class */
3844 objdef = oignore;
3845 break;
3846 case omethodtag:
3847 case omethodparm:
3848 make_C_tag (TRUE); /* an Objective C method */
3849 objdef = oinbody;
3850 break;
3851 default:
3852 /* Neutralize `extern "C" {' grot. */
3853 if (cblev == 0 && structdef == snone && nestlev == 0
3854 && typdef == tnone)
3855 cblev = -1;
3857 break;
3859 switch (structdef)
3861 case skeyseen: /* unnamed struct */
3862 pushclass_above (cblev, NULL, 0);
3863 structdef = snone;
3864 break;
3865 case stagseen: /* named struct or enum */
3866 case scolonseen: /* a class */
3867 pushclass_above (cblev, token.line+token.offset, token.length);
3868 structdef = snone;
3869 make_C_tag (FALSE); /* a struct or enum */
3870 break;
3872 cblev++;
3873 break;
3874 case '*':
3875 if (definedef != dnone)
3876 break;
3877 if (fvdef == fstartlist)
3879 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
3880 token.valid = FALSE;
3882 break;
3883 case '}':
3884 if (definedef != dnone)
3885 break;
3886 if (!ignoreindent && lp == newlb.buffer + 1)
3888 if (cblev != 0)
3889 token.valid = FALSE;
3890 cblev = 0; /* reset curly brace level if first column */
3891 parlev = 0; /* also reset paren level, just in case... */
3893 else if (cblev > 0)
3894 cblev--;
3895 else
3896 token.valid = FALSE; /* something gone amiss, token unreliable */
3897 popclass_above (cblev);
3898 structdef = snone;
3899 /* Only if typdef == tinbody is typdefcblev significant. */
3900 if (typdef == tinbody && cblev <= typdefcblev)
3902 assert (cblev == typdefcblev);
3903 typdef = tend;
3905 break;
3906 case '=':
3907 if (definedef != dnone)
3908 break;
3909 switch (fvdef)
3911 case foperator:
3912 case finlist:
3913 case fignore:
3914 case vignore:
3915 break;
3916 case fvnameseen:
3917 if ((members && cblev == 1)
3918 || (globals && cblev == 0 && (!fvextern || declarations)))
3919 make_C_tag (FALSE); /* a variable */
3920 /* FALLTHRU */
3921 default:
3922 fvdef = vignore;
3924 break;
3925 case '<':
3926 if (cplpl && structdef == stagseen)
3928 structdef = sintemplate;
3929 break;
3931 goto resetfvdef;
3932 case '>':
3933 if (structdef == sintemplate)
3935 structdef = stagseen;
3936 break;
3938 goto resetfvdef;
3939 case '+':
3940 case '-':
3941 if (objdef == oinbody && cblev == 0)
3943 objdef = omethodsign;
3944 break;
3946 /* FALLTHRU */
3947 resetfvdef:
3948 case '#': case '~': case '&': case '%': case '/': case '|':
3949 case '^': case '!': case '.': case '?': case ']':
3950 if (definedef != dnone)
3951 break;
3952 /* These surely cannot follow a function tag in C. */
3953 switch (fvdef)
3955 case foperator:
3956 case finlist:
3957 case fignore:
3958 case vignore:
3959 break;
3960 default:
3961 fvdef = fvnone;
3963 break;
3964 case '\0':
3965 if (objdef == otagseen)
3967 make_C_tag (TRUE); /* an Objective C class */
3968 objdef = oignore;
3970 /* If a macro spans multiple lines don't reset its state. */
3971 if (quotednl)
3972 CNL_SAVE_DEFINEDEF ();
3973 else
3974 CNL ();
3975 break;
3976 } /* switch (c) */
3978 } /* while not eof */
3980 free (lbs[0].lb.buffer);
3981 free (lbs[1].lb.buffer);
3985 * Process either a C++ file or a C file depending on the setting
3986 * of a global flag.
3988 static void
3989 default_C_entries (inf)
3990 FILE *inf;
3992 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
3995 /* Always do plain C. */
3996 static void
3997 plain_C_entries (inf)
3998 FILE *inf;
4000 C_entries (0, inf);
4003 /* Always do C++. */
4004 static void
4005 Cplusplus_entries (inf)
4006 FILE *inf;
4008 C_entries (C_PLPL, inf);
4011 /* Always do Java. */
4012 static void
4013 Cjava_entries (inf)
4014 FILE *inf;
4016 C_entries (C_JAVA, inf);
4019 /* Always do C*. */
4020 static void
4021 Cstar_entries (inf)
4022 FILE *inf;
4024 C_entries (C_STAR, inf);
4027 /* Always do Yacc. */
4028 static void
4029 Yacc_entries (inf)
4030 FILE *inf;
4032 C_entries (YACC, inf);
4036 /* Useful macros. */
4037 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
4038 for (; /* loop initialization */ \
4039 !feof (file_pointer) /* loop test */ \
4040 && /* instructions at start of loop */ \
4041 (readline (&line_buffer, file_pointer), \
4042 char_pointer = line_buffer.buffer, \
4043 TRUE); \
4045 #define LOOKING_AT(cp, keyword) /* keyword is a constant string */ \
4046 (strneq ((cp), keyword, sizeof(keyword)-1) /* cp points at keyword */ \
4047 && notinname ((cp)[sizeof(keyword)-1]) /* end of keyword */ \
4048 && ((cp) = skip_spaces((cp)+sizeof(keyword)-1))) /* skip spaces */
4051 * Read a file, but do no processing. This is used to do regexp
4052 * matching on files that have no language defined.
4054 static void
4055 just_read_file (inf)
4056 FILE *inf;
4058 register char *dummy;
4060 LOOP_ON_INPUT_LINES (inf, lb, dummy)
4061 continue;
4065 /* Fortran parsing */
4067 static void F_takeprec __P((void));
4068 static void F_getit __P((FILE *));
4070 static void
4071 F_takeprec ()
4073 dbp = skip_spaces (dbp);
4074 if (*dbp != '*')
4075 return;
4076 dbp++;
4077 dbp = skip_spaces (dbp);
4078 if (strneq (dbp, "(*)", 3))
4080 dbp += 3;
4081 return;
4083 if (!ISDIGIT (*dbp))
4085 --dbp; /* force failure */
4086 return;
4089 dbp++;
4090 while (ISDIGIT (*dbp));
4093 static void
4094 F_getit (inf)
4095 FILE *inf;
4097 register char *cp;
4099 dbp = skip_spaces (dbp);
4100 if (*dbp == '\0')
4102 readline (&lb, inf);
4103 dbp = lb.buffer;
4104 if (dbp[5] != '&')
4105 return;
4106 dbp += 6;
4107 dbp = skip_spaces (dbp);
4109 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
4110 return;
4111 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
4112 continue;
4113 make_tag (dbp, cp-dbp, TRUE,
4114 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4118 static void
4119 Fortran_functions (inf)
4120 FILE *inf;
4122 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4124 if (*dbp == '%')
4125 dbp++; /* Ratfor escape to fortran */
4126 dbp = skip_spaces (dbp);
4127 if (*dbp == '\0')
4128 continue;
4129 switch (lowcase (*dbp))
4131 case 'i':
4132 if (nocase_tail ("integer"))
4133 F_takeprec ();
4134 break;
4135 case 'r':
4136 if (nocase_tail ("real"))
4137 F_takeprec ();
4138 break;
4139 case 'l':
4140 if (nocase_tail ("logical"))
4141 F_takeprec ();
4142 break;
4143 case 'c':
4144 if (nocase_tail ("complex") || nocase_tail ("character"))
4145 F_takeprec ();
4146 break;
4147 case 'd':
4148 if (nocase_tail ("double"))
4150 dbp = skip_spaces (dbp);
4151 if (*dbp == '\0')
4152 continue;
4153 if (nocase_tail ("precision"))
4154 break;
4155 continue;
4157 break;
4159 dbp = skip_spaces (dbp);
4160 if (*dbp == '\0')
4161 continue;
4162 switch (lowcase (*dbp))
4164 case 'f':
4165 if (nocase_tail ("function"))
4166 F_getit (inf);
4167 continue;
4168 case 's':
4169 if (nocase_tail ("subroutine"))
4170 F_getit (inf);
4171 continue;
4172 case 'e':
4173 if (nocase_tail ("entry"))
4174 F_getit (inf);
4175 continue;
4176 case 'b':
4177 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4179 dbp = skip_spaces (dbp);
4180 if (*dbp == '\0') /* assume un-named */
4181 make_tag ("blockdata", 9, TRUE,
4182 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4183 else
4184 F_getit (inf); /* look for name */
4186 continue;
4193 * Ada parsing
4194 * Original code by
4195 * Philippe Waroquiers (1998)
4198 static void Ada_getit __P((FILE *, char *));
4200 /* Once we are positioned after an "interesting" keyword, let's get
4201 the real tag value necessary. */
4202 static void
4203 Ada_getit (inf, name_qualifier)
4204 FILE *inf;
4205 char *name_qualifier;
4207 register char *cp;
4208 char *name;
4209 char c;
4211 while (!feof (inf))
4213 dbp = skip_spaces (dbp);
4214 if (*dbp == '\0'
4215 || (dbp[0] == '-' && dbp[1] == '-'))
4217 readline (&lb, inf);
4218 dbp = lb.buffer;
4220 switch (lowcase(*dbp))
4222 case 'b':
4223 if (nocase_tail ("body"))
4225 /* Skipping body of procedure body or package body or ....
4226 resetting qualifier to body instead of spec. */
4227 name_qualifier = "/b";
4228 continue;
4230 break;
4231 case 't':
4232 /* Skipping type of task type or protected type ... */
4233 if (nocase_tail ("type"))
4234 continue;
4235 break;
4237 if (*dbp == '"')
4239 dbp += 1;
4240 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4241 continue;
4243 else
4245 dbp = skip_spaces (dbp);
4246 for (cp = dbp;
4247 (*cp != '\0'
4248 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4249 cp++)
4250 continue;
4251 if (cp == dbp)
4252 return;
4254 c = *cp;
4255 *cp = '\0';
4256 name = concat (dbp, name_qualifier, "");
4257 *cp = c;
4258 make_tag (name, strlen (name), TRUE,
4259 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4260 free (name);
4261 if (c == '"')
4262 dbp = cp + 1;
4263 return;
4267 static void
4268 Ada_funcs (inf)
4269 FILE *inf;
4271 bool inquote = FALSE;
4272 bool skip_till_semicolumn = FALSE;
4274 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4276 while (*dbp != '\0')
4278 /* Skip a string i.e. "abcd". */
4279 if (inquote || (*dbp == '"'))
4281 dbp = etags_strchr ((inquote) ? dbp : dbp+1, '"');
4282 if (dbp != NULL)
4284 inquote = FALSE;
4285 dbp += 1;
4286 continue; /* advance char */
4288 else
4290 inquote = TRUE;
4291 break; /* advance line */
4295 /* Skip comments. */
4296 if (dbp[0] == '-' && dbp[1] == '-')
4297 break; /* advance line */
4299 /* Skip character enclosed in single quote i.e. 'a'
4300 and skip single quote starting an attribute i.e. 'Image. */
4301 if (*dbp == '\'')
4303 dbp++ ;
4304 if (*dbp != '\0')
4305 dbp++;
4306 continue;
4309 if (skip_till_semicolumn)
4311 if (*dbp == ';')
4312 skip_till_semicolumn = FALSE;
4313 dbp++;
4314 continue; /* advance char */
4317 /* Search for beginning of a token. */
4318 if (!begtoken (*dbp))
4320 dbp++;
4321 continue; /* advance char */
4324 /* We are at the beginning of a token. */
4325 switch (lowcase(*dbp))
4327 case 'f':
4328 if (!packages_only && nocase_tail ("function"))
4329 Ada_getit (inf, "/f");
4330 else
4331 break; /* from switch */
4332 continue; /* advance char */
4333 case 'p':
4334 if (!packages_only && nocase_tail ("procedure"))
4335 Ada_getit (inf, "/p");
4336 else if (nocase_tail ("package"))
4337 Ada_getit (inf, "/s");
4338 else if (nocase_tail ("protected")) /* protected type */
4339 Ada_getit (inf, "/t");
4340 else
4341 break; /* from switch */
4342 continue; /* advance char */
4344 case 'u':
4345 if (typedefs && !packages_only && nocase_tail ("use"))
4347 /* when tagging types, avoid tagging use type Pack.Typename;
4348 for this, we will skip everything till a ; */
4349 skip_till_semicolumn = TRUE;
4350 continue; /* advance char */
4353 case 't':
4354 if (!packages_only && nocase_tail ("task"))
4355 Ada_getit (inf, "/k");
4356 else if (typedefs && !packages_only && nocase_tail ("type"))
4358 Ada_getit (inf, "/t");
4359 while (*dbp != '\0')
4360 dbp += 1;
4362 else
4363 break; /* from switch */
4364 continue; /* advance char */
4367 /* Look for the end of the token. */
4368 while (!endtoken (*dbp))
4369 dbp++;
4371 } /* advance char */
4372 } /* advance line */
4377 * Unix and microcontroller assembly tag handling
4378 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4379 * Idea by Bob Weiner, Motorola Inc. (1994)
4381 static void
4382 Asm_labels (inf)
4383 FILE *inf;
4385 register char *cp;
4387 LOOP_ON_INPUT_LINES (inf, lb, cp)
4389 /* If first char is alphabetic or one of [_.$], test for colon
4390 following identifier. */
4391 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4393 /* Read past label. */
4394 cp++;
4395 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4396 cp++;
4397 if (*cp == ':' || iswhite (*cp))
4398 /* Found end of label, so copy it and add it to the table. */
4399 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4400 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4407 * Perl support
4408 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4409 * Perl variable names: /^(my|local).../
4410 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4411 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4412 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4414 static void
4415 Perl_functions (inf)
4416 FILE *inf;
4418 char *package = savestr ("main"); /* current package name */
4419 register char *cp;
4421 LOOP_ON_INPUT_LINES (inf, lb, cp)
4423 skip_spaces(cp);
4425 if (LOOKING_AT (cp, "package"))
4427 free (package);
4428 get_tag (cp, &package);
4430 else if (LOOKING_AT (cp, "sub"))
4432 char *pos;
4433 char *sp = cp;
4435 while (!notinname (*cp))
4436 cp++;
4437 if (cp == sp)
4438 continue; /* nothing found */
4439 if ((pos = etags_strchr (sp, ':')) != NULL
4440 && pos < cp && pos[1] == ':')
4441 /* The name is already qualified. */
4442 make_tag (sp, cp - sp, TRUE,
4443 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4444 else
4445 /* Qualify it. */
4447 char savechar, *name;
4449 savechar = *cp;
4450 *cp = '\0';
4451 name = concat (package, "::", sp);
4452 *cp = savechar;
4453 make_tag (name, strlen(name), TRUE,
4454 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4455 free (name);
4458 else if (globals) /* only if we are tagging global vars */
4460 /* Skip a qualifier, if any. */
4461 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4462 /* After "my" or "local", but before any following paren or space. */
4463 char *varstart = cp;
4465 if (qual /* should this be removed? If yes, how? */
4466 && (*cp == '$' || *cp == '@' || *cp == '%'))
4468 varstart += 1;
4470 cp++;
4471 while (ISALNUM (*cp) || *cp == '_');
4473 else if (qual)
4475 /* Should be examining a variable list at this point;
4476 could insist on seeing an open parenthesis. */
4477 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4478 cp++;
4480 else
4481 continue;
4483 make_tag (varstart, cp - varstart, FALSE,
4484 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4491 * Python support
4492 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4493 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4494 * More ideas by seb bacon <seb@jamkit.com> (2002)
4496 static void
4497 Python_functions (inf)
4498 FILE *inf;
4500 register char *cp;
4502 LOOP_ON_INPUT_LINES (inf, lb, cp)
4504 cp = skip_spaces (cp);
4505 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4507 char *name = cp;
4508 while (!notinname (*cp) && *cp != ':')
4509 cp++;
4510 make_tag (name, cp - name, TRUE,
4511 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4518 * PHP support
4519 * Look for:
4520 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4521 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4522 * - /^[ \t]*define\(\"[^\"]+/
4523 * Only with --members:
4524 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4525 * Idea by Diez B. Roggisch (2001)
4527 static void
4528 PHP_functions (inf)
4529 FILE *inf;
4531 register char *cp, *name;
4532 bool search_identifier = FALSE;
4534 LOOP_ON_INPUT_LINES (inf, lb, cp)
4536 cp = skip_spaces (cp);
4537 name = cp;
4538 if (search_identifier
4539 && *cp != '\0')
4541 while (!notinname (*cp))
4542 cp++;
4543 make_tag (name, cp - name, TRUE,
4544 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4545 search_identifier = FALSE;
4547 else if (LOOKING_AT (cp, "function"))
4549 if(*cp == '&')
4550 cp = skip_spaces (cp+1);
4551 if(*cp != '\0')
4553 name = cp;
4554 while (!notinname (*cp))
4555 cp++;
4556 make_tag (name, cp - name, TRUE,
4557 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4559 else
4560 search_identifier = TRUE;
4562 else if (LOOKING_AT (cp, "class"))
4564 if (*cp != '\0')
4566 name = cp;
4567 while (*cp != '\0' && !iswhite (*cp))
4568 cp++;
4569 make_tag (name, cp - name, FALSE,
4570 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4572 else
4573 search_identifier = TRUE;
4575 else if (strneq (cp, "define", 6)
4576 && (cp = skip_spaces (cp+6))
4577 && *cp++ == '('
4578 && (*cp == '"' || *cp == '\''))
4580 char quote = *cp++;
4581 name = cp;
4582 while (*cp != quote && *cp != '\0')
4583 cp++;
4584 make_tag (name, cp - name, FALSE,
4585 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4587 else if (members
4588 && LOOKING_AT (cp, "var")
4589 && *cp == '$')
4591 name = cp;
4592 while (!notinname(*cp))
4593 cp++;
4594 make_tag (name, cp - name, FALSE,
4595 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4602 * Cobol tag functions
4603 * We could look for anything that could be a paragraph name.
4604 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4605 * Idea by Corny de Souza (1993)
4607 static void
4608 Cobol_paragraphs (inf)
4609 FILE *inf;
4611 register char *bp, *ep;
4613 LOOP_ON_INPUT_LINES (inf, lb, bp)
4615 if (lb.len < 9)
4616 continue;
4617 bp += 8;
4619 /* If eoln, compiler option or comment ignore whole line. */
4620 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4621 continue;
4623 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4624 continue;
4625 if (*ep++ == '.')
4626 make_tag (bp, ep - bp, TRUE,
4627 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4633 * Makefile support
4634 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4636 static void
4637 Makefile_targets (inf)
4638 FILE *inf;
4640 register char *bp;
4642 LOOP_ON_INPUT_LINES (inf, lb, bp)
4644 if (*bp == '\t' || *bp == '#')
4645 continue;
4646 while (*bp != '\0' && *bp != '=' && *bp != ':')
4647 bp++;
4648 if (*bp == ':' || (globals && *bp == '='))
4649 make_tag (lb.buffer, bp - lb.buffer, TRUE,
4650 lb.buffer, bp - lb.buffer + 1, lineno, linecharno);
4656 * Pascal parsing
4657 * Original code by Mosur K. Mohan (1989)
4659 * Locates tags for procedures & functions. Doesn't do any type- or
4660 * var-definitions. It does look for the keyword "extern" or
4661 * "forward" immediately following the procedure statement; if found,
4662 * the tag is skipped.
4664 static void
4665 Pascal_functions (inf)
4666 FILE *inf;
4668 linebuffer tline; /* mostly copied from C_entries */
4669 long save_lcno;
4670 int save_lineno, namelen, taglen;
4671 char c, *name;
4673 bool /* each of these flags is TRUE iff: */
4674 incomment, /* point is inside a comment */
4675 inquote, /* point is inside '..' string */
4676 get_tagname, /* point is after PROCEDURE/FUNCTION
4677 keyword, so next item = potential tag */
4678 found_tag, /* point is after a potential tag */
4679 inparms, /* point is within parameter-list */
4680 verify_tag; /* point has passed the parm-list, so the
4681 next token will determine whether this
4682 is a FORWARD/EXTERN to be ignored, or
4683 whether it is a real tag */
4685 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4686 name = NULL; /* keep compiler quiet */
4687 dbp = lb.buffer;
4688 *dbp = '\0';
4689 linebuffer_init (&tline);
4691 incomment = inquote = FALSE;
4692 found_tag = FALSE; /* have a proc name; check if extern */
4693 get_tagname = FALSE; /* found "procedure" keyword */
4694 inparms = FALSE; /* found '(' after "proc" */
4695 verify_tag = FALSE; /* check if "extern" is ahead */
4698 while (!feof (inf)) /* long main loop to get next char */
4700 c = *dbp++;
4701 if (c == '\0') /* if end of line */
4703 readline (&lb, inf);
4704 dbp = lb.buffer;
4705 if (*dbp == '\0')
4706 continue;
4707 if (!((found_tag && verify_tag)
4708 || get_tagname))
4709 c = *dbp++; /* only if don't need *dbp pointing
4710 to the beginning of the name of
4711 the procedure or function */
4713 if (incomment)
4715 if (c == '}') /* within { } comments */
4716 incomment = FALSE;
4717 else if (c == '*' && *dbp == ')') /* within (* *) comments */
4719 dbp++;
4720 incomment = FALSE;
4722 continue;
4724 else if (inquote)
4726 if (c == '\'')
4727 inquote = FALSE;
4728 continue;
4730 else
4731 switch (c)
4733 case '\'':
4734 inquote = TRUE; /* found first quote */
4735 continue;
4736 case '{': /* found open { comment */
4737 incomment = TRUE;
4738 continue;
4739 case '(':
4740 if (*dbp == '*') /* found open (* comment */
4742 incomment = TRUE;
4743 dbp++;
4745 else if (found_tag) /* found '(' after tag, i.e., parm-list */
4746 inparms = TRUE;
4747 continue;
4748 case ')': /* end of parms list */
4749 if (inparms)
4750 inparms = FALSE;
4751 continue;
4752 case ';':
4753 if (found_tag && !inparms) /* end of proc or fn stmt */
4755 verify_tag = TRUE;
4756 break;
4758 continue;
4760 if (found_tag && verify_tag && (*dbp != ' '))
4762 /* Check if this is an "extern" declaration. */
4763 if (*dbp == '\0')
4764 continue;
4765 if (lowcase (*dbp == 'e'))
4767 if (nocase_tail ("extern")) /* superfluous, really! */
4769 found_tag = FALSE;
4770 verify_tag = FALSE;
4773 else if (lowcase (*dbp) == 'f')
4775 if (nocase_tail ("forward")) /* check for forward reference */
4777 found_tag = FALSE;
4778 verify_tag = FALSE;
4781 if (found_tag && verify_tag) /* not external proc, so make tag */
4783 found_tag = FALSE;
4784 verify_tag = FALSE;
4785 make_tag (name, namelen, TRUE,
4786 tline.buffer, taglen, save_lineno, save_lcno);
4787 continue;
4790 if (get_tagname) /* grab name of proc or fn */
4792 char *cp;
4794 if (*dbp == '\0')
4795 continue;
4797 /* Find block name. */
4798 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
4799 continue;
4801 /* Save all values for later tagging. */
4802 linebuffer_setlen (&tline, lb.len);
4803 strcpy (tline.buffer, lb.buffer);
4804 save_lineno = lineno;
4805 save_lcno = linecharno;
4806 name = tline.buffer + (dbp - lb.buffer);
4807 namelen = cp - dbp;
4808 taglen = cp - lb.buffer + 1;
4810 dbp = cp; /* set dbp to e-o-token */
4811 get_tagname = FALSE;
4812 found_tag = TRUE;
4813 continue;
4815 /* And proceed to check for "extern". */
4817 else if (!incomment && !inquote && !found_tag)
4819 /* Check for proc/fn keywords. */
4820 switch (lowcase (c))
4822 case 'p':
4823 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
4824 get_tagname = TRUE;
4825 continue;
4826 case 'f':
4827 if (nocase_tail ("unction"))
4828 get_tagname = TRUE;
4829 continue;
4832 } /* while not eof */
4834 free (tline.buffer);
4839 * Lisp tag functions
4840 * look for (def or (DEF, quote or QUOTE
4843 static void L_getit __P((void));
4845 static void
4846 L_getit ()
4848 if (*dbp == '\'') /* Skip prefix quote */
4849 dbp++;
4850 else if (*dbp == '(')
4852 dbp++;
4853 /* Try to skip "(quote " */
4854 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
4855 /* Ok, then skip "(" before name in (defstruct (foo)) */
4856 dbp = skip_spaces (dbp);
4858 get_tag (dbp, NULL);
4861 static void
4862 Lisp_functions (inf)
4863 FILE *inf;
4865 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4867 if (dbp[0] != '(')
4868 continue;
4870 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
4872 dbp = skip_non_spaces (dbp);
4873 dbp = skip_spaces (dbp);
4874 L_getit ();
4876 else
4878 /* Check for (foo::defmumble name-defined ... */
4880 dbp++;
4881 while (!notinname (*dbp) && *dbp != ':');
4882 if (*dbp == ':')
4885 dbp++;
4886 while (*dbp == ':');
4888 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
4890 dbp = skip_non_spaces (dbp);
4891 dbp = skip_spaces (dbp);
4892 L_getit ();
4901 * Postscript tag functions
4902 * Just look for lines where the first character is '/'
4903 * Also look at "defineps" for PSWrap
4904 * Ideas by:
4905 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
4906 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
4908 static void
4909 PS_functions (inf)
4910 FILE *inf;
4912 register char *bp, *ep;
4914 LOOP_ON_INPUT_LINES (inf, lb, bp)
4916 if (bp[0] == '/')
4918 for (ep = bp+1;
4919 *ep != '\0' && *ep != ' ' && *ep != '{';
4920 ep++)
4921 continue;
4922 make_tag (bp, ep - bp, TRUE,
4923 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4925 else if (LOOKING_AT (bp, "defineps"))
4926 get_tag (bp, NULL);
4932 * Scheme tag functions
4933 * look for (def... xyzzy
4934 * (def... (xyzzy
4935 * (def ... ((...(xyzzy ....
4936 * (set! xyzzy
4937 * Original code by Ken Haase (1985?)
4940 static void
4941 Scheme_functions (inf)
4942 FILE *inf;
4944 register char *bp;
4946 LOOP_ON_INPUT_LINES (inf, lb, bp)
4948 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
4950 bp = skip_non_spaces (bp+4);
4951 /* Skip over open parens and white space */
4952 while (notinname (*bp))
4953 bp++;
4954 get_tag (bp, NULL);
4956 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
4957 get_tag (bp, NULL);
4962 /* Find tags in TeX and LaTeX input files. */
4964 /* TEX_toktab is a table of TeX control sequences that define tags.
4965 * Each entry records one such control sequence.
4967 * Original code from who knows whom.
4968 * Ideas by:
4969 * Stefan Monnier (2002)
4972 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
4974 /* Default set of control sequences to put into TEX_toktab.
4975 The value of environment var TEXTAGS is prepended to this. */
4976 static char *TEX_defenv = "\
4977 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
4978 :part:appendix:entry:index:def\
4979 :newcommand:renewcommand:newenvironment:renewenvironment";
4981 static void TEX_mode __P((FILE *));
4982 static void TEX_decode_env __P((char *, char *));
4984 static char TEX_esc = '\\';
4985 static char TEX_opgrp = '{';
4986 static char TEX_clgrp = '}';
4989 * TeX/LaTeX scanning loop.
4991 static void
4992 TeX_commands (inf)
4993 FILE *inf;
4995 char *cp;
4996 linebuffer *key;
4998 /* Select either \ or ! as escape character. */
4999 TEX_mode (inf);
5001 /* Initialize token table once from environment. */
5002 if (TEX_toktab == NULL)
5003 TEX_decode_env ("TEXTAGS", TEX_defenv);
5005 LOOP_ON_INPUT_LINES (inf, lb, cp)
5007 /* Look at each TEX keyword in line. */
5008 for (;;)
5010 /* Look for a TEX escape. */
5011 while (*cp++ != TEX_esc)
5012 if (cp[-1] == '\0' || cp[-1] == '%')
5013 goto tex_next_line;
5015 for (key = TEX_toktab; key->buffer != NULL; key++)
5016 if (strneq (cp, key->buffer, key->len))
5018 register char *p;
5019 int namelen, linelen;
5020 bool opgrp = FALSE;
5022 cp = skip_spaces (cp + key->len);
5023 if (*cp == TEX_opgrp)
5025 opgrp = TRUE;
5026 cp++;
5028 for (p = cp;
5029 (!iswhite (*p) && *p != '#' &&
5030 *p != TEX_opgrp && *p != TEX_clgrp);
5031 p++)
5032 continue;
5033 namelen = p - cp;
5034 linelen = lb.len;
5035 if (!opgrp || *p == TEX_clgrp)
5037 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
5038 *p++;
5039 linelen = p - lb.buffer + 1;
5041 make_tag (cp, namelen, TRUE,
5042 lb.buffer, linelen, lineno, linecharno);
5043 goto tex_next_line; /* We only tag a line once */
5046 tex_next_line:
5051 #define TEX_LESC '\\'
5052 #define TEX_SESC '!'
5054 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5055 chars accordingly. */
5056 static void
5057 TEX_mode (inf)
5058 FILE *inf;
5060 int c;
5062 while ((c = getc (inf)) != EOF)
5064 /* Skip to next line if we hit the TeX comment char. */
5065 if (c == '%')
5066 while (c != '\n')
5067 c = getc (inf);
5068 else if (c == TEX_LESC || c == TEX_SESC )
5069 break;
5072 if (c == TEX_LESC)
5074 TEX_esc = TEX_LESC;
5075 TEX_opgrp = '{';
5076 TEX_clgrp = '}';
5078 else
5080 TEX_esc = TEX_SESC;
5081 TEX_opgrp = '<';
5082 TEX_clgrp = '>';
5084 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5085 No attempt is made to correct the situation. */
5086 rewind (inf);
5089 /* Read environment and prepend it to the default string.
5090 Build token table. */
5091 static void
5092 TEX_decode_env (evarname, defenv)
5093 char *evarname;
5094 char *defenv;
5096 register char *env, *p;
5097 int i, len;
5099 /* Append default string to environment. */
5100 env = getenv (evarname);
5101 if (!env)
5102 env = defenv;
5103 else
5105 char *oldenv = env;
5106 env = concat (oldenv, defenv, "");
5109 /* Allocate a token table */
5110 for (len = 1, p = env; p;)
5111 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5112 len++;
5113 TEX_toktab = xnew (len, linebuffer);
5115 /* Unpack environment string into token table. Be careful about */
5116 /* zero-length strings (leading ':', "::" and trailing ':') */
5117 for (i = 0; *env != '\0';)
5119 p = etags_strchr (env, ':');
5120 if (!p) /* End of environment string. */
5121 p = env + strlen (env);
5122 if (p - env > 0)
5123 { /* Only non-zero strings. */
5124 TEX_toktab[i].buffer = savenstr (env, p - env);
5125 TEX_toktab[i].len = p - env;
5126 i++;
5128 if (*p)
5129 env = p + 1;
5130 else
5132 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5133 TEX_toktab[i].len = 0;
5134 break;
5140 /* Texinfo support. Dave Love, Mar. 2000. */
5141 static void
5142 Texinfo_nodes (inf)
5143 FILE * inf;
5145 char *cp, *start;
5146 LOOP_ON_INPUT_LINES (inf, lb, cp)
5147 if (LOOKING_AT (cp, "@node"))
5149 start = cp;
5150 while (*cp != '\0' && *cp != ',')
5151 cp++;
5152 make_tag (start, cp - start, TRUE,
5153 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5158 /* Similar to LOOKING_AT but does not use notinname, does not skip */
5159 #define LOOKING_AT_NOCASE(cp, kw) /* kw is a constant string */ \
5160 (strncaseeq ((cp), kw, sizeof(kw)-1) /* cp points at kw */ \
5161 && ((cp) += sizeof(kw)-1)) /* skip spaces */
5164 * HTML support.
5165 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5166 * Contents of <a name=xxx> are tags with name xxx.
5168 * Francesco Potortì, 2002.
5170 static void
5171 HTML_labels (inf)
5172 FILE * inf;
5174 bool getnext = FALSE; /* next text outside of HTML tags is a tag */
5175 bool skiptag = FALSE; /* skip to the end of the current HTML tag */
5176 bool intag = FALSE; /* inside an html tag, looking for ID= */
5177 bool inanchor = FALSE; /* when INTAG, is an anchor, look for NAME= */
5178 char *end;
5181 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5183 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5184 for (;;) /* loop on the same line */
5186 if (skiptag) /* skip HTML tag */
5188 while (*dbp != '\0' && *dbp != '>')
5189 dbp++;
5190 if (*dbp == '>')
5192 dbp += 1;
5193 skiptag = FALSE;
5194 continue; /* look on the same line */
5196 break; /* go to next line */
5199 else if (intag) /* look for "name=" or "id=" */
5201 while (*dbp != '\0' && *dbp != '>'
5202 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5203 dbp++;
5204 if (*dbp == '\0')
5205 break; /* go to next line */
5206 if (*dbp == '>')
5208 dbp += 1;
5209 intag = FALSE;
5210 continue; /* look on the same line */
5212 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5213 || LOOKING_AT_NOCASE (dbp, "id="))
5215 bool quoted = (dbp[0] == '"');
5217 if (quoted)
5218 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5219 continue;
5220 else
5221 for (end = dbp; *end != '\0' && intoken (*end); end++)
5222 continue;
5223 linebuffer_setlen (&token_name, end - dbp);
5224 strncpy (token_name.buffer, dbp, end - dbp);
5225 token_name.buffer[end - dbp] = '\0';
5227 dbp = end;
5228 intag = FALSE; /* we found what we looked for */
5229 skiptag = TRUE; /* skip to the end of the tag */
5230 getnext = TRUE; /* then grab the text */
5231 continue; /* look on the same line */
5233 dbp += 1;
5236 else if (getnext) /* grab next tokens and tag them */
5238 dbp = skip_spaces (dbp);
5239 if (*dbp == '\0')
5240 break; /* go to next line */
5241 if (*dbp == '<')
5243 intag = TRUE;
5244 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5245 continue; /* look on the same line */
5248 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5249 continue;
5250 make_tag (token_name.buffer, token_name.len, TRUE,
5251 dbp, end - dbp, lineno, linecharno);
5252 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5253 getnext = FALSE;
5254 break; /* go to next line */
5257 else /* look for an interesting HTML tag */
5259 while (*dbp != '\0' && *dbp != '<')
5260 dbp++;
5261 if (*dbp == '\0')
5262 break; /* go to next line */
5263 intag = TRUE;
5264 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5266 inanchor = TRUE;
5267 continue; /* look on the same line */
5269 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5270 || LOOKING_AT_NOCASE (dbp, "<h1>")
5271 || LOOKING_AT_NOCASE (dbp, "<h2>")
5272 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5274 intag = FALSE;
5275 getnext = TRUE;
5276 continue; /* look on the same line */
5278 dbp += 1;
5285 * Prolog support
5287 * Assumes that the predicate or rule starts at column 0.
5288 * Only the first clause of a predicate or rule is added.
5289 * Original code by Sunichirou Sugou (1989)
5290 * Rewritten by Anders Lindgren (1996)
5292 static int prolog_pr __P((char *, char *));
5293 static void prolog_skip_comment __P((linebuffer *, FILE *));
5294 static int prolog_atom __P((char *, int));
5296 static void
5297 Prolog_functions (inf)
5298 FILE *inf;
5300 char *cp, *last;
5301 int len;
5302 int allocated;
5304 allocated = 0;
5305 len = 0;
5306 last = NULL;
5308 LOOP_ON_INPUT_LINES (inf, lb, cp)
5310 if (cp[0] == '\0') /* Empty line */
5311 continue;
5312 else if (iswhite (cp[0])) /* Not a predicate */
5313 continue;
5314 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5315 prolog_skip_comment (&lb, inf);
5316 else if ((len = prolog_pr (cp, last)) > 0)
5318 /* Predicate or rule. Store the function name so that we
5319 only generate a tag for the first clause. */
5320 if (last == NULL)
5321 last = xnew(len + 1, char);
5322 else if (len + 1 > allocated)
5323 xrnew (last, len + 1, char);
5324 allocated = len + 1;
5325 strncpy (last, cp, len);
5326 last[len] = '\0';
5332 static void
5333 prolog_skip_comment (plb, inf)
5334 linebuffer *plb;
5335 FILE *inf;
5337 char *cp;
5341 for (cp = plb->buffer; *cp != '\0'; cp++)
5342 if (cp[0] == '*' && cp[1] == '/')
5343 return;
5344 readline (plb, inf);
5346 while (!feof(inf));
5350 * A predicate or rule definition is added if it matches:
5351 * <beginning of line><Prolog Atom><whitespace>(
5352 * or <beginning of line><Prolog Atom><whitespace>:-
5354 * It is added to the tags database if it doesn't match the
5355 * name of the previous clause header.
5357 * Return the size of the name of the predicate or rule, or 0 if no
5358 * header was found.
5360 static int
5361 prolog_pr (s, last)
5362 char *s;
5363 char *last; /* Name of last clause. */
5365 int pos;
5366 int len;
5368 pos = prolog_atom (s, 0);
5369 if (pos < 1)
5370 return 0;
5372 len = pos;
5373 pos = skip_spaces (s + pos) - s;
5375 if ((s[pos] == '.'
5376 || (s[pos] == '(' && (pos += 1))
5377 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5378 && (last == NULL /* save only the first clause */
5379 || len != strlen (last)
5380 || !strneq (s, last, len)))
5382 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5383 return len;
5385 else
5386 return 0;
5390 * Consume a Prolog atom.
5391 * Return the number of bytes consumed, or -1 if there was an error.
5393 * A prolog atom, in this context, could be one of:
5394 * - An alphanumeric sequence, starting with a lower case letter.
5395 * - A quoted arbitrary string. Single quotes can escape themselves.
5396 * Backslash quotes everything.
5398 static int
5399 prolog_atom (s, pos)
5400 char *s;
5401 int pos;
5403 int origpos;
5405 origpos = pos;
5407 if (ISLOWER(s[pos]) || (s[pos] == '_'))
5409 /* The atom is unquoted. */
5410 pos++;
5411 while (ISALNUM(s[pos]) || (s[pos] == '_'))
5413 pos++;
5415 return pos - origpos;
5417 else if (s[pos] == '\'')
5419 pos++;
5421 for (;;)
5423 if (s[pos] == '\'')
5425 pos++;
5426 if (s[pos] != '\'')
5427 break;
5428 pos++; /* A double quote */
5430 else if (s[pos] == '\0')
5431 /* Multiline quoted atoms are ignored. */
5432 return -1;
5433 else if (s[pos] == '\\')
5435 if (s[pos+1] == '\0')
5436 return -1;
5437 pos += 2;
5439 else
5440 pos++;
5442 return pos - origpos;
5444 else
5445 return -1;
5450 * Support for Erlang
5452 * Generates tags for functions, defines, and records.
5453 * Assumes that Erlang functions start at column 0.
5454 * Original code by Anders Lindgren (1996)
5456 static int erlang_func __P((char *, char *));
5457 static void erlang_attribute __P((char *));
5458 static int erlang_atom __P((char *));
5460 static void
5461 Erlang_functions (inf)
5462 FILE *inf;
5464 char *cp, *last;
5465 int len;
5466 int allocated;
5468 allocated = 0;
5469 len = 0;
5470 last = NULL;
5472 LOOP_ON_INPUT_LINES (inf, lb, cp)
5474 if (cp[0] == '\0') /* Empty line */
5475 continue;
5476 else if (iswhite (cp[0])) /* Not function nor attribute */
5477 continue;
5478 else if (cp[0] == '%') /* comment */
5479 continue;
5480 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5481 continue;
5482 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5484 erlang_attribute (cp);
5485 last = NULL;
5487 else if ((len = erlang_func (cp, last)) > 0)
5490 * Function. Store the function name so that we only
5491 * generates a tag for the first clause.
5493 if (last == NULL)
5494 last = xnew (len + 1, char);
5495 else if (len + 1 > allocated)
5496 xrnew (last, len + 1, char);
5497 allocated = len + 1;
5498 strncpy (last, cp, len);
5499 last[len] = '\0';
5506 * A function definition is added if it matches:
5507 * <beginning of line><Erlang Atom><whitespace>(
5509 * It is added to the tags database if it doesn't match the
5510 * name of the previous clause header.
5512 * Return the size of the name of the function, or 0 if no function
5513 * was found.
5515 static int
5516 erlang_func (s, last)
5517 char *s;
5518 char *last; /* Name of last clause. */
5520 int pos;
5521 int len;
5523 pos = erlang_atom (s);
5524 if (pos < 1)
5525 return 0;
5527 len = pos;
5528 pos = skip_spaces (s + pos) - s;
5530 /* Save only the first clause. */
5531 if (s[pos++] == '('
5532 && (last == NULL
5533 || len != (int)strlen (last)
5534 || !strneq (s, last, len)))
5536 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5537 return len;
5540 return 0;
5545 * Handle attributes. Currently, tags are generated for defines
5546 * and records.
5548 * They are on the form:
5549 * -define(foo, bar).
5550 * -define(Foo(M, N), M+N).
5551 * -record(graph, {vtab = notable, cyclic = true}).
5553 static void
5554 erlang_attribute (s)
5555 char *s;
5557 char *cp = s;
5559 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5560 && *cp++ == '(')
5562 int len = erlang_atom (skip_spaces (cp));
5563 if (len > 0)
5564 make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5566 return;
5571 * Consume an Erlang atom (or variable).
5572 * Return the number of bytes consumed, or -1 if there was an error.
5574 static int
5575 erlang_atom (s)
5576 char *s;
5578 int pos = 0;
5580 if (ISALPHA (s[pos]) || s[pos] == '_')
5582 /* The atom is unquoted. */
5584 pos++;
5585 while (ISALNUM (s[pos]) || s[pos] == '_');
5587 else if (s[pos] == '\'')
5589 for (pos++; s[pos] != '\''; pos++)
5590 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5591 || (s[pos] == '\\' && s[++pos] == '\0'))
5592 return 0;
5593 pos++;
5596 return pos;
5600 #ifdef ETAGS_REGEXPS
5602 static char *scan_separators __P((char *));
5603 static void add_regex __P((char *, language *));
5604 static char *substitute __P((char *, char *, struct re_registers *));
5607 * Take a string like "/blah/" and turn it into "blah", verifying
5608 * that the first and last characters are the same, and handling
5609 * quoted separator characters. Actually, stops on the occurrence of
5610 * an unquoted separator. Also process \t, \n, etc. and turn into
5611 * appropriate characters. Works in place. Null terminates name string.
5612 * Returns pointer to terminating separator, or NULL for
5613 * unterminated regexps.
5615 static char *
5616 scan_separators (name)
5617 char *name;
5619 char sep = name[0];
5620 char *copyto = name;
5621 bool quoted = FALSE;
5623 for (++name; *name != '\0'; ++name)
5625 if (quoted)
5627 switch (*name)
5629 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
5630 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
5631 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
5632 case 'e': *copyto++ = 033; break; /* ESC (delete) */
5633 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
5634 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
5635 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
5636 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
5637 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
5638 default:
5639 if (*name == sep)
5640 *copyto++ = sep;
5641 else
5643 /* Something else is quoted, so preserve the quote. */
5644 *copyto++ = '\\';
5645 *copyto++ = *name;
5647 break;
5649 quoted = FALSE;
5651 else if (*name == '\\')
5652 quoted = TRUE;
5653 else if (*name == sep)
5654 break;
5655 else
5656 *copyto++ = *name;
5658 if (*name != sep)
5659 name = NULL; /* signal unterminated regexp */
5661 /* Terminate copied string. */
5662 *copyto = '\0';
5663 return name;
5666 /* Look at the argument of --regex or --no-regex and do the right
5667 thing. Same for each line of a regexp file. */
5668 static void
5669 analyse_regex (regex_arg)
5670 char *regex_arg;
5672 if (regex_arg == NULL)
5674 free_regexps (); /* --no-regex: remove existing regexps */
5675 return;
5678 /* A real --regexp option or a line in a regexp file. */
5679 switch (regex_arg[0])
5681 /* Comments in regexp file or null arg to --regex. */
5682 case '\0':
5683 case ' ':
5684 case '\t':
5685 break;
5687 /* Read a regex file. This is recursive and may result in a
5688 loop, which will stop when the file descriptors are exhausted. */
5689 case '@':
5691 FILE *regexfp;
5692 linebuffer regexbuf;
5693 char *regexfile = regex_arg + 1;
5695 /* regexfile is a file containing regexps, one per line. */
5696 regexfp = fopen (regexfile, "r");
5697 if (regexfp == NULL)
5699 pfatal (regexfile);
5700 return;
5702 linebuffer_init (&regexbuf);
5703 while (readline_internal (&regexbuf, regexfp) > 0)
5704 analyse_regex (regexbuf.buffer);
5705 free (regexbuf.buffer);
5706 fclose (regexfp);
5708 break;
5710 /* Regexp to be used for a specific language only. */
5711 case '{':
5713 language *lang;
5714 char *lang_name = regex_arg + 1;
5715 char *cp;
5717 for (cp = lang_name; *cp != '}'; cp++)
5718 if (*cp == '\0')
5720 error ("unterminated language name in regex: %s", regex_arg);
5721 return;
5723 *cp++ = '\0';
5724 lang = get_language_from_langname (lang_name);
5725 if (lang == NULL)
5726 return;
5727 add_regex (cp, lang);
5729 break;
5731 /* Regexp to be used for any language. */
5732 default:
5733 add_regex (regex_arg, NULL);
5734 break;
5738 /* Separate the regexp pattern, compile it,
5739 and care for optional name and modifiers. */
5740 static void
5741 add_regex (regexp_pattern, lang)
5742 char *regexp_pattern;
5743 language *lang;
5745 static struct re_pattern_buffer zeropattern;
5746 char sep, *pat, *name, *modifiers;
5747 const char *err;
5748 struct re_pattern_buffer *patbuf;
5749 regexp *rp;
5750 bool
5751 force_explicit_name = TRUE, /* do not use implicit tag names */
5752 ignore_case = FALSE, /* case is significant */
5753 multi_line = FALSE, /* matches are done one line at a time */
5754 single_line = FALSE; /* dot does not match newline */
5757 if (strlen(regexp_pattern) < 3)
5759 error ("null regexp", (char *)NULL);
5760 return;
5762 sep = regexp_pattern[0];
5763 name = scan_separators (regexp_pattern);
5764 if (name == NULL)
5766 error ("%s: unterminated regexp", regexp_pattern);
5767 return;
5769 if (name[1] == sep)
5771 error ("null name for regexp \"%s\"", regexp_pattern);
5772 return;
5774 modifiers = scan_separators (name);
5775 if (modifiers == NULL) /* no terminating separator --> no name */
5777 modifiers = name;
5778 name = "";
5780 else
5781 modifiers += 1; /* skip separator */
5783 /* Parse regex modifiers. */
5784 for (; modifiers[0] != '\0'; modifiers++)
5785 switch (modifiers[0])
5787 case 'N':
5788 if (modifiers == name)
5789 error ("forcing explicit tag name but no name, ignoring", NULL);
5790 force_explicit_name = TRUE;
5791 break;
5792 case 'i':
5793 ignore_case = TRUE;
5794 break;
5795 case 's':
5796 single_line = TRUE;
5797 /* FALLTHRU */
5798 case 'm':
5799 multi_line = TRUE;
5800 need_filebuf = TRUE;
5801 break;
5802 default:
5804 char wrongmod [2];
5805 wrongmod[0] = modifiers[0];
5806 wrongmod[1] = '\0';
5807 error ("invalid regexp modifier `%s', ignoring", wrongmod);
5809 break;
5812 patbuf = xnew (1, struct re_pattern_buffer);
5813 *patbuf = zeropattern;
5814 if (ignore_case)
5816 static char lc_trans[CHARS];
5817 int i;
5818 for (i = 0; i < CHARS; i++)
5819 lc_trans[i] = lowcase (i);
5820 patbuf->translate = lc_trans; /* translation table to fold case */
5823 if (multi_line)
5824 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
5825 else
5826 pat = regexp_pattern;
5828 if (single_line)
5829 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
5830 else
5831 re_set_syntax (RE_SYNTAX_EMACS);
5833 err = re_compile_pattern (pat, strlen (regexp_pattern), patbuf);
5834 if (multi_line)
5835 free (pat);
5836 if (err != NULL)
5838 error ("%s while compiling pattern", err);
5839 return;
5842 rp = p_head;
5843 p_head = xnew (1, regexp);
5844 p_head->pattern = savestr (regexp_pattern);
5845 p_head->p_next = rp;
5846 p_head->lang = lang;
5847 p_head->pat = patbuf;
5848 p_head->name = savestr (name);
5849 p_head->error_signaled = FALSE;
5850 p_head->force_explicit_name = force_explicit_name;
5851 p_head->ignore_case = ignore_case;
5852 p_head->multi_line = multi_line;
5856 * Do the substitutions indicated by the regular expression and
5857 * arguments.
5859 static char *
5860 substitute (in, out, regs)
5861 char *in, *out;
5862 struct re_registers *regs;
5864 char *result, *t;
5865 int size, dig, diglen;
5867 result = NULL;
5868 size = strlen (out);
5870 /* Pass 1: figure out how much to allocate by finding all \N strings. */
5871 if (out[size - 1] == '\\')
5872 fatal ("pattern error in \"%s\"", out);
5873 for (t = etags_strchr (out, '\\');
5874 t != NULL;
5875 t = etags_strchr (t + 2, '\\'))
5876 if (ISDIGIT (t[1]))
5878 dig = t[1] - '0';
5879 diglen = regs->end[dig] - regs->start[dig];
5880 size += diglen - 2;
5882 else
5883 size -= 1;
5885 /* Allocate space and do the substitutions. */
5886 assert (size >= 0);
5887 result = xnew (size + 1, char);
5889 for (t = result; *out != '\0'; out++)
5890 if (*out == '\\' && ISDIGIT (*++out))
5892 dig = *out - '0';
5893 diglen = regs->end[dig] - regs->start[dig];
5894 strncpy (t, in + regs->start[dig], diglen);
5895 t += diglen;
5897 else
5898 *t++ = *out;
5899 *t = '\0';
5901 assert (t <= result + size);
5902 assert (t - result == (int)strlen (result));
5904 return result;
5907 /* Deallocate all regexps. */
5908 static void
5909 free_regexps ()
5911 regexp *rp;
5912 while (p_head != NULL)
5914 rp = p_head->p_next;
5915 free (p_head->pattern);
5916 free (p_head->name);
5917 free (p_head);
5918 p_head = rp;
5920 return;
5924 * Reads the whole file as a single string from `filebuf' and looks for
5925 * multi-line regular expressions, creating tags on matches.
5926 * readline already dealt with normal regexps.
5928 * Idea by Ben Wing <ben@666.com> (2002).
5930 static void
5931 regex_tag_multiline ()
5933 char *buffer = filebuf.buffer;
5934 regexp *rp;
5935 char *name;
5937 for (rp = p_head; rp != NULL; rp = rp->p_next)
5939 int match = 0;
5941 if (!rp->multi_line)
5942 continue; /* skip normal regexps */
5944 /* Generic initialisations before parsing file from memory. */
5945 lineno = 1; /* reset global line number */
5946 charno = 0; /* reset global char number */
5947 linecharno = 0; /* reset global char number of line start */
5949 /* Only use generic regexps or those for the current language. */
5950 if (rp->lang != NULL && rp->lang != curfdp->lang)
5951 continue;
5953 while (match >= 0 && match < filebuf.len)
5955 match = re_search (rp->pat, buffer, filebuf.len, charno,
5956 filebuf.len - match, &rp->regs);
5957 switch (match)
5959 case -2:
5960 /* Some error. */
5961 if (!rp->error_signaled)
5963 error ("regexp stack overflow while matching \"%s\"",
5964 rp->pattern);
5965 rp->error_signaled = TRUE;
5967 break;
5968 case -1:
5969 /* No match. */
5970 break;
5971 default:
5972 if (match == rp->regs.end[0])
5974 if (!rp->error_signaled)
5976 error ("regexp matches the empty string: \"%s\"",
5977 rp->pattern);
5978 rp->error_signaled = TRUE;
5980 match = -3; /* exit from while loop */
5981 break;
5984 /* Match occurred. Construct a tag. */
5985 while (charno < rp->regs.end[0])
5986 if (buffer[charno++] == '\n')
5987 lineno++, linecharno = charno;
5988 name = rp->name;
5989 if (name[0] == '\0')
5990 name = NULL;
5991 else /* make a named tag */
5992 name = substitute (buffer, rp->name, &rp->regs);
5993 if (rp->force_explicit_name)
5994 /* Force explicit tag name, if a name is there. */
5995 pfnote (name, TRUE, buffer + linecharno,
5996 charno - linecharno + 1, lineno, linecharno);
5997 else
5998 make_tag (name, strlen (name), TRUE, buffer + linecharno,
5999 charno - linecharno + 1, lineno, linecharno);
6000 break;
6006 #endif /* ETAGS_REGEXPS */
6009 static bool
6010 nocase_tail (cp)
6011 char *cp;
6013 register int len = 0;
6015 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
6016 cp++, len++;
6017 if (*cp == '\0' && !intoken (dbp[len]))
6019 dbp += len;
6020 return TRUE;
6022 return FALSE;
6025 static void
6026 get_tag (bp, namepp)
6027 register char *bp;
6028 char **namepp;
6030 register char *cp = bp;
6032 if (*bp != '\0')
6034 /* Go till you get to white space or a syntactic break */
6035 for (cp = bp + 1; !notinname (*cp); cp++)
6036 continue;
6037 make_tag (bp, cp - bp, TRUE,
6038 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
6041 if (namepp != NULL)
6042 *namepp = savenstr (bp, cp - bp);
6046 * Read a line of text from `stream' into `lbp', excluding the
6047 * newline or CR-NL, if any. Return the number of characters read from
6048 * `stream', which is the length of the line including the newline.
6050 * On DOS or Windows we do not count the CR character, if any before the
6051 * NL, in the returned length; this mirrors the behavior of Emacs on those
6052 * platforms (for text files, it translates CR-NL to NL as it reads in the
6053 * file).
6055 * If multi-line regular expressions are requested, each line read is
6056 * appended to `filebuf'.
6058 static long
6059 readline_internal (lbp, stream)
6060 linebuffer *lbp;
6061 register FILE *stream;
6063 char *buffer = lbp->buffer;
6064 register char *p = lbp->buffer;
6065 register char *pend;
6066 int chars_deleted;
6068 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
6070 for (;;)
6072 register int c = getc (stream);
6073 if (p == pend)
6075 /* We're at the end of linebuffer: expand it. */
6076 lbp->size *= 2;
6077 xrnew (buffer, lbp->size, char);
6078 p += buffer - lbp->buffer;
6079 pend = buffer + lbp->size;
6080 lbp->buffer = buffer;
6082 if (c == EOF)
6084 *p = '\0';
6085 chars_deleted = 0;
6086 break;
6088 if (c == '\n')
6090 if (p > buffer && p[-1] == '\r')
6092 p -= 1;
6093 #ifdef DOS_NT
6094 /* Assume CRLF->LF translation will be performed by Emacs
6095 when loading this file, so CRs won't appear in the buffer.
6096 It would be cleaner to compensate within Emacs;
6097 however, Emacs does not know how many CRs were deleted
6098 before any given point in the file. */
6099 chars_deleted = 1;
6100 #else
6101 chars_deleted = 2;
6102 #endif
6104 else
6106 chars_deleted = 1;
6108 *p = '\0';
6109 break;
6111 *p++ = c;
6113 lbp->len = p - buffer;
6115 if (need_filebuf /* we need filebuf for multi-line regexps */
6116 && chars_deleted > 0) /* not at EOF */
6118 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6120 /* Expand filebuf. */
6121 filebuf.size *= 2;
6122 xrnew (filebuf.buffer, filebuf.size, char);
6124 strncpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6125 filebuf.len += lbp->len;
6126 filebuf.buffer[filebuf.len++] = '\n';
6127 filebuf.buffer[filebuf.len] = '\0';
6130 return lbp->len + chars_deleted;
6134 * Like readline_internal, above, but in addition try to match the
6135 * input line against relevant regular expressions and manage #line
6136 * directives.
6138 static void
6139 readline (lbp, stream)
6140 linebuffer *lbp;
6141 FILE *stream;
6143 long result;
6145 linecharno = charno; /* update global char number of line start */
6146 result = readline_internal (lbp, stream); /* read line */
6147 lineno += 1; /* increment global line number */
6148 charno += result; /* increment global char number */
6150 /* Honour #line directives. */
6151 if (!no_line_directive)
6153 static bool discard_until_line_directive;
6155 /* Check whether this is a #line directive. */
6156 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6158 int start, lno;
6160 if (DEBUG) start = 0; /* shut up the compiler */
6161 if (sscanf (lbp->buffer, "#line %d \"%n", &lno, &start) == 1)
6163 char *endp = lbp->buffer + start;
6165 assert (start > 0);
6166 while ((endp = etags_strchr (endp, '"')) != NULL
6167 && endp[-1] == '\\')
6168 endp++;
6169 if (endp != NULL)
6170 /* Ok, this is a real #line directive. Let's deal with it. */
6172 char *taggedabsname; /* absolute name of original file */
6173 char *taggedfname; /* name of original file as given */
6174 char *name; /* temp var */
6176 discard_until_line_directive = FALSE; /* found it */
6177 name = lbp->buffer + start;
6178 *endp = '\0';
6179 canonicalize_filename (name); /* for DOS */
6180 taggedabsname = absolute_filename (name, curfdp->infabsdir);
6181 if (filename_is_absolute (name)
6182 || filename_is_absolute (curfdp->infname))
6183 taggedfname = savestr (taggedabsname);
6184 else
6185 taggedfname = relative_filename (taggedabsname,tagfiledir);
6187 if (streq (curfdp->taggedfname, taggedfname))
6188 /* The #line directive is only a line number change. We
6189 deal with this afterwards. */
6190 free (taggedfname);
6191 else
6192 /* The tags following this #line directive should be
6193 attributed to taggedfname. In order to do this, set
6194 curfdp accordingly. */
6196 fdesc *fdp; /* file description pointer */
6198 /* Go look for a file description already set up for the
6199 file indicated in the #line directive. If there is
6200 one, use it from now until the next #line
6201 directive. */
6202 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6203 if (streq (fdp->infname, curfdp->infname)
6204 && streq (fdp->taggedfname, taggedfname))
6205 /* If we remove the second test above (after the &&)
6206 then all entries pertaining to the same file are
6207 coalesced in the tags file. If we use it, then
6208 entries pertaining to the same file but generated
6209 from different files (via #line directives) will
6210 go into separate sections in the tags file. These
6211 alternatives look equivalent. The first one
6212 destroys some apparently useless information. */
6214 curfdp = fdp;
6215 free (taggedfname);
6216 break;
6218 /* Else, if we already tagged the real file, skip all
6219 input lines until the next #line directive. */
6220 if (fdp == NULL) /* not found */
6221 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6222 if (streq (fdp->infabsname, taggedabsname))
6224 discard_until_line_directive = TRUE;
6225 free (taggedfname);
6226 break;
6228 /* Else create a new file description and use that from
6229 now on, until the next #line directive. */
6230 if (fdp == NULL) /* not found */
6232 fdp = fdhead;
6233 fdhead = xnew (1, fdesc);
6234 *fdhead = *curfdp; /* copy curr. file description */
6235 fdhead->next = fdp;
6236 fdhead->infname = savestr (curfdp->infname);
6237 fdhead->infabsname = savestr (curfdp->infabsname);
6238 fdhead->infabsdir = savestr (curfdp->infabsdir);
6239 fdhead->taggedfname = taggedfname;
6240 fdhead->usecharno = FALSE;
6241 fdhead->prop = NULL;
6242 fdhead->written = FALSE;
6243 curfdp = fdhead;
6246 free (taggedabsname);
6247 lineno = lno - 1;
6248 readline (lbp, stream);
6249 return;
6250 } /* if a real #line directive */
6251 } /* if #line is followed by a a number */
6252 } /* if line begins with "#line " */
6254 /* If we are here, no #line directive was found. */
6255 if (discard_until_line_directive)
6257 if (result > 0)
6259 /* Do a tail recursion on ourselves, thus discarding the contents
6260 of the line buffer. */
6261 readline (lbp, stream);
6262 return;
6264 /* End of file. */
6265 discard_until_line_directive = FALSE;
6266 return;
6268 } /* if #line directives should be considered */
6270 #ifdef ETAGS_REGEXPS
6272 int match;
6273 regexp *rp;
6274 char *name;
6276 /* Match against relevant regexps. */
6277 if (lbp->len > 0)
6278 for (rp = p_head; rp != NULL; rp = rp->p_next)
6280 /* Only use generic regexps or those for the current language.
6281 Also do not use multiline regexps, which is the job of
6282 regex_tag_multiline. */
6283 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6284 || rp->multi_line)
6285 continue;
6287 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6288 switch (match)
6290 case -2:
6291 /* Some error. */
6292 if (!rp->error_signaled)
6294 error ("regexp stack overflow while matching \"%s\"",
6295 rp->pattern);
6296 rp->error_signaled = TRUE;
6298 break;
6299 case -1:
6300 /* No match. */
6301 break;
6302 case 0:
6303 /* Empty string matched. */
6304 if (!rp->error_signaled)
6306 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6307 rp->error_signaled = TRUE;
6309 break;
6310 default:
6311 /* Match occurred. Construct a tag. */
6312 name = rp->name;
6313 if (name[0] == '\0')
6314 name = NULL;
6315 else /* make a named tag */
6316 name = substitute (lbp->buffer, rp->name, &rp->regs);
6317 if (rp->force_explicit_name)
6318 /* Force explicit tag name, if a name is there. */
6319 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6320 else
6321 make_tag (name, strlen (name), TRUE,
6322 lbp->buffer, match, lineno, linecharno);
6323 break;
6327 #endif /* ETAGS_REGEXPS */
6332 * Return a pointer to a space of size strlen(cp)+1 allocated
6333 * with xnew where the string CP has been copied.
6335 static char *
6336 savestr (cp)
6337 char *cp;
6339 return savenstr (cp, strlen (cp));
6343 * Return a pointer to a space of size LEN+1 allocated with xnew where
6344 * the string CP has been copied for at most the first LEN characters.
6346 static char *
6347 savenstr (cp, len)
6348 char *cp;
6349 int len;
6351 register char *dp;
6353 dp = xnew (len + 1, char);
6354 strncpy (dp, cp, len);
6355 dp[len] = '\0';
6356 return dp;
6360 * Return the ptr in sp at which the character c last
6361 * appears; NULL if not found
6363 * Identical to POSIX strrchr, included for portability.
6365 static char *
6366 etags_strrchr (sp, c)
6367 register const char *sp;
6368 register int c;
6370 register const char *r;
6372 r = NULL;
6375 if (*sp == c)
6376 r = sp;
6377 } while (*sp++);
6378 return (char *)r;
6382 * Return the ptr in sp at which the character c first
6383 * appears; NULL if not found
6385 * Identical to POSIX strchr, included for portability.
6387 static char *
6388 etags_strchr (sp, c)
6389 register const char *sp;
6390 register int c;
6394 if (*sp == c)
6395 return (char *)sp;
6396 } while (*sp++);
6397 return NULL;
6401 * Compare two strings, ignoring case for alphabetic characters.
6403 * Same as BSD's strcasecmp, included for portability.
6405 static int
6406 etags_strcasecmp (s1, s2)
6407 register const char *s1;
6408 register const char *s2;
6410 while (*s1 != '\0'
6411 && (ISALPHA (*s1) && ISALPHA (*s2)
6412 ? lowcase (*s1) == lowcase (*s2)
6413 : *s1 == *s2))
6414 s1++, s2++;
6416 return (ISALPHA (*s1) && ISALPHA (*s2)
6417 ? lowcase (*s1) - lowcase (*s2)
6418 : *s1 - *s2);
6422 * Compare two strings, ignoring case for alphabetic characters.
6423 * Stop after a given number of characters
6425 * Same as BSD's strncasecmp, included for portability.
6427 static int
6428 etags_strncasecmp (s1, s2, n)
6429 register const char *s1;
6430 register const char *s2;
6431 register int n;
6433 while (*s1 != '\0' && n-- > 0
6434 && (ISALPHA (*s1) && ISALPHA (*s2)
6435 ? lowcase (*s1) == lowcase (*s2)
6436 : *s1 == *s2))
6437 s1++, s2++;
6439 if (n < 0)
6440 return 0;
6441 else
6442 return (ISALPHA (*s1) && ISALPHA (*s2)
6443 ? lowcase (*s1) - lowcase (*s2)
6444 : *s1 - *s2);
6447 /* Skip spaces, return new pointer. */
6448 static char *
6449 skip_spaces (cp)
6450 char *cp;
6452 while (iswhite (*cp))
6453 cp++;
6454 return cp;
6457 /* Skip non spaces, return new pointer. */
6458 static char *
6459 skip_non_spaces (cp)
6460 char *cp;
6462 while (*cp != '\0' && !iswhite (*cp))
6463 cp++;
6464 return cp;
6467 /* Print error message and exit. */
6468 void
6469 fatal (s1, s2)
6470 char *s1, *s2;
6472 error (s1, s2);
6473 exit (BAD);
6476 static void
6477 pfatal (s1)
6478 char *s1;
6480 perror (s1);
6481 exit (BAD);
6484 static void
6485 suggest_asking_for_help ()
6487 fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6488 progname,
6489 #ifdef LONG_OPTIONS
6490 "--help"
6491 #else
6492 "-h"
6493 #endif
6495 exit (BAD);
6498 /* Print error message. `s1' is printf control string, `s2' is arg for it. */
6499 static void
6500 error (s1, s2)
6501 const char *s1, *s2;
6503 fprintf (stderr, "%s: ", progname);
6504 fprintf (stderr, s1, s2);
6505 fprintf (stderr, "\n");
6508 /* Return a newly-allocated string whose contents
6509 concatenate those of s1, s2, s3. */
6510 static char *
6511 concat (s1, s2, s3)
6512 char *s1, *s2, *s3;
6514 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6515 char *result = xnew (len1 + len2 + len3 + 1, char);
6517 strcpy (result, s1);
6518 strcpy (result + len1, s2);
6519 strcpy (result + len1 + len2, s3);
6520 result[len1 + len2 + len3] = '\0';
6522 return result;
6526 /* Does the same work as the system V getcwd, but does not need to
6527 guess the buffer size in advance. */
6528 static char *
6529 etags_getcwd ()
6531 #ifdef HAVE_GETCWD
6532 int bufsize = 200;
6533 char *path = xnew (bufsize, char);
6535 while (getcwd (path, bufsize) == NULL)
6537 if (errno != ERANGE)
6538 pfatal ("getcwd");
6539 bufsize *= 2;
6540 free (path);
6541 path = xnew (bufsize, char);
6544 canonicalize_filename (path);
6545 return path;
6547 #else /* not HAVE_GETCWD */
6548 #if MSDOS
6550 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
6552 getwd (path);
6554 for (p = path; *p != '\0'; p++)
6555 if (*p == '\\')
6556 *p = '/';
6557 else
6558 *p = lowcase (*p);
6560 return strdup (path);
6561 #else /* not MSDOS */
6562 linebuffer path;
6563 FILE *pipe;
6565 linebuffer_init (&path);
6566 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6567 if (pipe == NULL || readline_internal (&path, pipe) == 0)
6568 pfatal ("pwd");
6569 pclose (pipe);
6571 return path.buffer;
6572 #endif /* not MSDOS */
6573 #endif /* not HAVE_GETCWD */
6576 /* Return a newly allocated string containing the file name of FILE
6577 relative to the absolute directory DIR (which should end with a slash). */
6578 static char *
6579 relative_filename (file, dir)
6580 char *file, *dir;
6582 char *fp, *dp, *afn, *res;
6583 int i;
6585 /* Find the common root of file and dir (with a trailing slash). */
6586 afn = absolute_filename (file, cwd);
6587 fp = afn;
6588 dp = dir;
6589 while (*fp++ == *dp++)
6590 continue;
6591 fp--, dp--; /* back to the first differing char */
6592 #ifdef DOS_NT
6593 if (fp == afn && afn[0] != '/') /* cannot build a relative name */
6594 return afn;
6595 #endif
6596 do /* look at the equal chars until '/' */
6597 fp--, dp--;
6598 while (*fp != '/');
6600 /* Build a sequence of "../" strings for the resulting relative file name. */
6601 i = 0;
6602 while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6603 i += 1;
6604 res = xnew (3*i + strlen (fp + 1) + 1, char);
6605 res[0] = '\0';
6606 while (i-- > 0)
6607 strcat (res, "../");
6609 /* Add the file name relative to the common root of file and dir. */
6610 strcat (res, fp + 1);
6611 free (afn);
6613 return res;
6616 /* Return a newly allocated string containing the absolute file name
6617 of FILE given DIR (which should end with a slash). */
6618 static char *
6619 absolute_filename (file, dir)
6620 char *file, *dir;
6622 char *slashp, *cp, *res;
6624 if (filename_is_absolute (file))
6625 res = savestr (file);
6626 #ifdef DOS_NT
6627 /* We don't support non-absolute file names with a drive
6628 letter, like `d:NAME' (it's too much hassle). */
6629 else if (file[1] == ':')
6630 fatal ("%s: relative file names with drive letters not supported", file);
6631 #endif
6632 else
6633 res = concat (dir, file, "");
6635 /* Delete the "/dirname/.." and "/." substrings. */
6636 slashp = etags_strchr (res, '/');
6637 while (slashp != NULL && slashp[0] != '\0')
6639 if (slashp[1] == '.')
6641 if (slashp[2] == '.'
6642 && (slashp[3] == '/' || slashp[3] == '\0'))
6644 cp = slashp;
6646 cp--;
6647 while (cp >= res && !filename_is_absolute (cp));
6648 if (cp < res)
6649 cp = slashp; /* the absolute name begins with "/.." */
6650 #ifdef DOS_NT
6651 /* Under MSDOS and NT we get `d:/NAME' as absolute
6652 file name, so the luser could say `d:/../NAME'.
6653 We silently treat this as `d:/NAME'. */
6654 else if (cp[0] != '/')
6655 cp = slashp;
6656 #endif
6657 strcpy (cp, slashp + 3);
6658 slashp = cp;
6659 continue;
6661 else if (slashp[2] == '/' || slashp[2] == '\0')
6663 strcpy (slashp, slashp + 2);
6664 continue;
6668 slashp = etags_strchr (slashp + 1, '/');
6671 if (res[0] == '\0')
6672 return savestr ("/");
6673 else
6674 return res;
6677 /* Return a newly allocated string containing the absolute
6678 file name of dir where FILE resides given DIR (which should
6679 end with a slash). */
6680 static char *
6681 absolute_dirname (file, dir)
6682 char *file, *dir;
6684 char *slashp, *res;
6685 char save;
6687 canonicalize_filename (file);
6688 slashp = etags_strrchr (file, '/');
6689 if (slashp == NULL)
6690 return savestr (dir);
6691 save = slashp[1];
6692 slashp[1] = '\0';
6693 res = absolute_filename (file, dir);
6694 slashp[1] = save;
6696 return res;
6699 /* Whether the argument string is an absolute file name. The argument
6700 string must have been canonicalized with canonicalize_filename. */
6701 static bool
6702 filename_is_absolute (fn)
6703 char *fn;
6705 return (fn[0] == '/'
6706 #ifdef DOS_NT
6707 || (ISALPHA(fn[0]) && fn[1] == ':' && fn[2] == '/')
6708 #endif
6712 /* Translate backslashes into slashes. Works in place. */
6713 static void
6714 canonicalize_filename (fn)
6715 register char *fn;
6717 #ifdef DOS_NT
6718 /* Canonicalize drive letter case. */
6719 if (fn[0] != '\0' && fn[1] == ':' && ISLOWER (fn[0]))
6720 fn[0] = upcase (fn[0]);
6721 /* Convert backslashes to slashes. */
6722 for (; *fn != '\0'; fn++)
6723 if (*fn == '\\')
6724 *fn = '/';
6725 #else
6726 /* No action. */
6727 fn = NULL; /* shut up the compiler */
6728 #endif
6732 /* Initialize a linebuffer for use */
6733 static void
6734 linebuffer_init (lbp)
6735 linebuffer *lbp;
6737 lbp->size = (DEBUG) ? 3 : 200;
6738 lbp->buffer = xnew (lbp->size, char);
6739 lbp->buffer[0] = '\0';
6740 lbp->len = 0;
6743 /* Set the minimum size of a string contained in a linebuffer. */
6744 static void
6745 linebuffer_setlen (lbp, toksize)
6746 linebuffer *lbp;
6747 int toksize;
6749 while (lbp->size <= toksize)
6751 lbp->size *= 2;
6752 xrnew (lbp->buffer, lbp->size, char);
6754 lbp->len = toksize;
6757 /* Like malloc but get fatal error if memory is exhausted. */
6758 static PTR
6759 xmalloc (size)
6760 unsigned int size;
6762 PTR result = (PTR) malloc (size);
6763 if (result == NULL)
6764 fatal ("virtual memory exhausted", (char *)NULL);
6765 return result;
6768 static PTR
6769 xrealloc (ptr, size)
6770 char *ptr;
6771 unsigned int size;
6773 PTR result = (PTR) realloc (ptr, size);
6774 if (result == NULL)
6775 fatal ("virtual memory exhausted", (char *)NULL);
6776 return result;
6780 * Local Variables:
6781 * c-indentation-style: gnu
6782 * indent-tabs-mode: t
6783 * tab-width: 8
6784 * fill-column: 79
6785 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
6786 * End: