Remove NEWS markup so that file-attributes etc get rechecked
[emacs.git] / lib-src / etags.c
blobec415e9905f889d55103f5e8efa35ff77e8978fa
1 /* Tags file maker to go with GNU Emacs -*- coding: latin-1 -*-
3 Copyright (C) 1984 The Regents of the University of California
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
7 met:
8 1. Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright
11 notice, this list of conditions and the following disclaimer in the
12 documentation and/or other materials provided with the
13 distribution.
14 3. Neither the name of the University nor the names of its
15 contributors may be used to endorse or promote products derived
16 from this software without specific prior written permission.
18 THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
19 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
22 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
27 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
28 IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 Copyright (C) 1984, 1987-1989, 1993-1995, 1998-2012
32 Free Software Foundation, Inc.
34 This file is not considered part of GNU Emacs.
36 This program is free software: you can redistribute it and/or modify
37 it under the terms of the GNU General Public License as published by
38 the Free Software Foundation, either version 3 of the License, or
39 (at your option) any later version.
41 This program is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 GNU General Public License for more details.
46 You should have received a copy of the GNU General Public License
47 along with this program. If not, see <http://www.gnu.org/licenses/>. */
50 /* NB To comply with the above BSD license, copyright information is
51 reproduced in etc/ETAGS.README. That file should be updated when the
52 above notices are.
54 To the best of our knowledge, this code was originally based on the
55 ctags.c distributed with BSD4.2, which was copyrighted by the
56 University of California, as described above. */
60 * Authors:
61 * 1983 Ctags originally by Ken Arnold.
62 * 1984 Fortran added by Jim Kleckner.
63 * 1984 Ed Pelegri-Llopart added C typedefs.
64 * 1985 Emacs TAGS format by Richard Stallman.
65 * 1989 Sam Kendall added C++.
66 * 1992 Joseph B. Wells improved C and C++ parsing.
67 * 1993 Francesco Potortì reorganized C and C++.
68 * 1994 Line-by-line regexp tags by Tom Tromey.
69 * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba).
70 * 2002 #line directives by Francesco Potortì.
72 * Francesco Potortì <pot@gnu.org> has maintained and improved it since 1993.
76 * If you want to add support for a new language, start by looking at the LUA
77 * language, which is the simplest. Alternatively, consider distributing etags
78 * together with a configuration file containing regexp definitions for etags.
81 char pot_etags_version[] = "@(#) pot revision number is 17.38.1.4";
83 #define TRUE 1
84 #define FALSE 0
86 #ifdef DEBUG
87 # undef DEBUG
88 # define DEBUG TRUE
89 #else
90 # define DEBUG FALSE
91 # define NDEBUG /* disable assert */
92 #endif
94 #include <config.h>
96 #ifndef _GNU_SOURCE
97 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
98 #endif
100 /* WIN32_NATIVE is for XEmacs.
101 MSDOS, WINDOWSNT, DOS_NT are for Emacs. */
102 #ifdef WIN32_NATIVE
103 # undef MSDOS
104 # undef WINDOWSNT
105 # define WINDOWSNT
106 #endif /* WIN32_NATIVE */
108 #ifdef MSDOS
109 # undef MSDOS
110 # define MSDOS TRUE
111 # include <fcntl.h>
112 # include <sys/param.h>
113 # include <io.h>
114 #else
115 # define MSDOS FALSE
116 #endif /* MSDOS */
118 #ifdef WINDOWSNT
119 # include <fcntl.h>
120 # include <direct.h>
121 # include <io.h>
122 # define MAXPATHLEN _MAX_PATH
123 # undef HAVE_NTGUI
124 # undef DOS_NT
125 # define DOS_NT
126 # ifndef HAVE_GETCWD
127 # define HAVE_GETCWD
128 # endif /* undef HAVE_GETCWD */
129 #else /* not WINDOWSNT */
130 #endif /* !WINDOWSNT */
132 #include <unistd.h>
133 #ifndef HAVE_UNISTD_H
134 # if defined (HAVE_GETCWD) && !defined (WINDOWSNT)
135 extern char *getcwd (char *buf, size_t size);
136 # endif
137 #endif /* HAVE_UNISTD_H */
139 #include <stdarg.h>
140 #include <stdlib.h>
141 #include <string.h>
142 #include <stdio.h>
143 #include <ctype.h>
144 #include <errno.h>
145 #include <sys/types.h>
146 #include <sys/stat.h>
147 #include <c-strcase.h>
149 #include <assert.h>
150 #ifdef NDEBUG
151 # undef assert /* some systems have a buggy assert.h */
152 # define assert(x) ((void) 0)
153 #endif
155 #ifdef NO_LONG_OPTIONS /* define this if you don't have GNU getopt */
156 # define NO_LONG_OPTIONS TRUE
157 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
158 extern char *optarg;
159 extern int optind, opterr;
160 #else
161 # define NO_LONG_OPTIONS FALSE
162 # include <getopt.h>
163 #endif /* NO_LONG_OPTIONS */
165 #include <regex.h>
167 /* Define CTAGS to make the program "ctags" compatible with the usual one.
168 Leave it undefined to make the program "etags", which makes emacs-style
169 tag tables and tags typedefs, #defines and struct/union/enum by default. */
170 #ifdef CTAGS
171 # undef CTAGS
172 # define CTAGS TRUE
173 #else
174 # define CTAGS FALSE
175 #endif
177 #define streq(s,t) (assert ((s)!=NULL || (t)!=NULL), !strcmp (s, t))
178 #define strcaseeq(s,t) (assert ((s)!=NULL && (t)!=NULL), !c_strcasecmp (s, t))
179 #define strneq(s,t,n) (assert ((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
180 #define strncaseeq(s,t,n) (assert ((s)!=NULL && (t)!=NULL), !c_strncasecmp (s, t, n))
182 #define CHARS 256 /* 2^sizeof(char) */
183 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
184 #define iswhite(c) (_wht[CHAR (c)]) /* c is white (see white) */
185 #define notinname(c) (_nin[CHAR (c)]) /* c is not in a name (see nonam) */
186 #define begtoken(c) (_btk[CHAR (c)]) /* c can start token (see begtk) */
187 #define intoken(c) (_itk[CHAR (c)]) /* c can be in token (see midtk) */
188 #define endtoken(c) (_etk[CHAR (c)]) /* c ends tokens (see endtk) */
190 #define ISALNUM(c) isalnum (CHAR (c))
191 #define ISALPHA(c) isalpha (CHAR (c))
192 #define ISDIGIT(c) isdigit (CHAR (c))
193 #define ISLOWER(c) islower (CHAR (c))
195 #define lowcase(c) tolower (CHAR (c))
199 * xnew, xrnew -- allocate, reallocate storage
201 * SYNOPSIS: Type *xnew (int n, Type);
202 * void xrnew (OldPointer, int n, Type);
204 #if DEBUG
205 # include "chkmalloc.h"
206 # define xnew(n,Type) ((Type *) trace_malloc (__FILE__, __LINE__, \
207 (n) * sizeof (Type)))
208 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
209 (char *) (op), (n) * sizeof (Type)))
210 #else
211 # define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
212 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
213 (char *) (op), (n) * sizeof (Type)))
214 #endif
216 #define bool int
218 typedef void Lang_function (FILE *);
220 typedef struct
222 const char *suffix; /* file name suffix for this compressor */
223 const char *command; /* takes one arg and decompresses to stdout */
224 } compressor;
226 typedef struct
228 const char *name; /* language name */
229 const char *help; /* detailed help for the language */
230 Lang_function *function; /* parse function */
231 const char **suffixes; /* name suffixes of this language's files */
232 const char **filenames; /* names of this language's files */
233 const char **interpreters; /* interpreters for this language */
234 bool metasource; /* source used to generate other sources */
235 } language;
237 typedef struct fdesc
239 struct fdesc *next; /* for the linked list */
240 char *infname; /* uncompressed input file name */
241 char *infabsname; /* absolute uncompressed input file name */
242 char *infabsdir; /* absolute dir of input file */
243 char *taggedfname; /* file name to write in tagfile */
244 language *lang; /* language of file */
245 char *prop; /* file properties to write in tagfile */
246 bool usecharno; /* etags tags shall contain char number */
247 bool written; /* entry written in the tags file */
248 } fdesc;
250 typedef struct node_st
251 { /* sorting structure */
252 struct node_st *left, *right; /* left and right sons */
253 fdesc *fdp; /* description of file to whom tag belongs */
254 char *name; /* tag name */
255 char *regex; /* search regexp */
256 bool valid; /* write this tag on the tag file */
257 bool is_func; /* function tag: use regexp in CTAGS mode */
258 bool been_warned; /* warning already given for duplicated tag */
259 int lno; /* line number tag is on */
260 long cno; /* character number line starts on */
261 } node;
264 * A `linebuffer' is a structure which holds a line of text.
265 * `readline_internal' reads a line from a stream into a linebuffer
266 * and works regardless of the length of the line.
267 * SIZE is the size of BUFFER, LEN is the length of the string in
268 * BUFFER after readline reads it.
270 typedef struct
272 long size;
273 int len;
274 char *buffer;
275 } linebuffer;
277 /* Used to support mixing of --lang and file names. */
278 typedef struct
280 enum {
281 at_language, /* a language specification */
282 at_regexp, /* a regular expression */
283 at_filename, /* a file name */
284 at_stdin, /* read from stdin here */
285 at_end /* stop parsing the list */
286 } arg_type; /* argument type */
287 language *lang; /* language associated with the argument */
288 char *what; /* the argument itself */
289 } argument;
291 /* Structure defining a regular expression. */
292 typedef struct regexp
294 struct regexp *p_next; /* pointer to next in list */
295 language *lang; /* if set, use only for this language */
296 char *pattern; /* the regexp pattern */
297 char *name; /* tag name */
298 struct re_pattern_buffer *pat; /* the compiled pattern */
299 struct re_registers regs; /* re registers */
300 bool error_signaled; /* already signaled for this regexp */
301 bool force_explicit_name; /* do not allow implicit tag name */
302 bool ignore_case; /* ignore case when matching */
303 bool multi_line; /* do a multi-line match on the whole file */
304 } regexp;
307 /* Many compilers barf on this:
308 Lang_function Ada_funcs;
309 so let's write it this way */
310 static void Ada_funcs (FILE *);
311 static void Asm_labels (FILE *);
312 static void C_entries (int c_ext, FILE *);
313 static void default_C_entries (FILE *);
314 static void plain_C_entries (FILE *);
315 static void Cjava_entries (FILE *);
316 static void Cobol_paragraphs (FILE *);
317 static void Cplusplus_entries (FILE *);
318 static void Cstar_entries (FILE *);
319 static void Erlang_functions (FILE *);
320 static void Forth_words (FILE *);
321 static void Fortran_functions (FILE *);
322 static void HTML_labels (FILE *);
323 static void Lisp_functions (FILE *);
324 static void Lua_functions (FILE *);
325 static void Makefile_targets (FILE *);
326 static void Pascal_functions (FILE *);
327 static void Perl_functions (FILE *);
328 static void PHP_functions (FILE *);
329 static void PS_functions (FILE *);
330 static void Prolog_functions (FILE *);
331 static void Python_functions (FILE *);
332 static void Scheme_functions (FILE *);
333 static void TeX_commands (FILE *);
334 static void Texinfo_nodes (FILE *);
335 static void Yacc_entries (FILE *);
336 static void just_read_file (FILE *);
338 static void print_language_names (void);
339 static void print_version (void);
340 static void print_help (argument *);
341 int main (int, char **);
343 static compressor *get_compressor_from_suffix (char *, char **);
344 static language *get_language_from_langname (const char *);
345 static language *get_language_from_interpreter (char *);
346 static language *get_language_from_filename (char *, bool);
347 static void readline (linebuffer *, FILE *);
348 static long readline_internal (linebuffer *, FILE *);
349 static bool nocase_tail (const char *);
350 static void get_tag (char *, char **);
352 static void analyse_regex (char *);
353 static void free_regexps (void);
354 static void regex_tag_multiline (void);
355 static void error (const char *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2);
356 static _Noreturn void suggest_asking_for_help (void);
357 _Noreturn void fatal (const char *, const char *);
358 static _Noreturn void pfatal (const char *);
359 static void add_node (node *, node **);
361 static void init (void);
362 static void process_file_name (char *, language *);
363 static void process_file (FILE *, char *, language *);
364 static void find_entries (FILE *);
365 static void free_tree (node *);
366 static void free_fdesc (fdesc *);
367 static void pfnote (char *, bool, char *, int, int, long);
368 static void make_tag (const char *, int, bool, char *, int, int, long);
369 static void invalidate_nodes (fdesc *, node **);
370 static void put_entries (node *);
372 static char *concat (const char *, const char *, const char *);
373 static char *skip_spaces (char *);
374 static char *skip_non_spaces (char *);
375 static char *savenstr (const char *, int);
376 static char *savestr (const char *);
377 static char *etags_strchr (const char *, int);
378 static char *etags_strrchr (const char *, int);
379 static char *etags_getcwd (void);
380 static char *relative_filename (char *, char *);
381 static char *absolute_filename (char *, char *);
382 static char *absolute_dirname (char *, char *);
383 static bool filename_is_absolute (char *f);
384 static void canonicalize_filename (char *);
385 static void linebuffer_init (linebuffer *);
386 static void linebuffer_setlen (linebuffer *, int);
387 static void *xmalloc (size_t);
388 static void *xrealloc (char *, size_t);
391 static char searchar = '/'; /* use /.../ searches */
393 static char *tagfile; /* output file */
394 static char *progname; /* name this program was invoked with */
395 static char *cwd; /* current working directory */
396 static char *tagfiledir; /* directory of tagfile */
397 static FILE *tagf; /* ioptr for tags file */
398 static ptrdiff_t whatlen_max; /* maximum length of any 'what' member */
400 static fdesc *fdhead; /* head of file description list */
401 static fdesc *curfdp; /* current file description */
402 static int lineno; /* line number of current line */
403 static long charno; /* current character number */
404 static long linecharno; /* charno of start of current line */
405 static char *dbp; /* pointer to start of current tag */
407 static const int invalidcharno = -1;
409 static node *nodehead; /* the head of the binary tree of tags */
410 static node *last_node; /* the last node created */
412 static linebuffer lb; /* the current line */
413 static linebuffer filebuf; /* a buffer containing the whole file */
414 static linebuffer token_name; /* a buffer containing a tag name */
416 /* boolean "functions" (see init) */
417 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
418 static const char
419 /* white chars */
420 *white = " \f\t\n\r\v",
421 /* not in a name */
422 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
423 /* token ending chars */
424 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
425 /* token starting chars */
426 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
427 /* valid in-token chars */
428 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
430 static bool append_to_tagfile; /* -a: append to tags */
431 /* The next five default to TRUE in C and derived languages. */
432 static bool typedefs; /* -t: create tags for C and Ada typedefs */
433 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
434 /* 0 struct/enum/union decls, and C++ */
435 /* member functions. */
436 static bool constantypedefs; /* -d: create tags for C #define, enum */
437 /* constants and variables. */
438 /* -D: opposite of -d. Default under ctags. */
439 static bool globals; /* create tags for global variables */
440 static bool members; /* create tags for C member variables */
441 static bool declarations; /* --declarations: tag them and extern in C&Co*/
442 static bool no_line_directive; /* ignore #line directives (undocumented) */
443 static bool no_duplicates; /* no duplicate tags for ctags (undocumented) */
444 static bool update; /* -u: update tags */
445 static bool vgrind_style; /* -v: create vgrind style index output */
446 static bool no_warnings; /* -w: suppress warnings (undocumented) */
447 static bool cxref_style; /* -x: create cxref style output */
448 static bool cplusplus; /* .[hc] means C++, not C (undocumented) */
449 static bool ignoreindent; /* -I: ignore indentation in C */
450 static bool packages_only; /* --packages-only: in Ada, only tag packages*/
452 /* STDIN is defined in LynxOS system headers */
453 #ifdef STDIN
454 # undef STDIN
455 #endif
457 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
458 static bool parsing_stdin; /* --parse-stdin used */
460 static regexp *p_head; /* list of all regexps */
461 static bool need_filebuf; /* some regexes are multi-line */
463 static struct option longopts[] =
465 { "append", no_argument, NULL, 'a' },
466 { "packages-only", no_argument, &packages_only, TRUE },
467 { "c++", no_argument, NULL, 'C' },
468 { "declarations", no_argument, &declarations, TRUE },
469 { "no-line-directive", no_argument, &no_line_directive, TRUE },
470 { "no-duplicates", no_argument, &no_duplicates, TRUE },
471 { "help", no_argument, NULL, 'h' },
472 { "help", no_argument, NULL, 'H' },
473 { "ignore-indentation", no_argument, NULL, 'I' },
474 { "language", required_argument, NULL, 'l' },
475 { "members", no_argument, &members, TRUE },
476 { "no-members", no_argument, &members, FALSE },
477 { "output", required_argument, NULL, 'o' },
478 { "regex", required_argument, NULL, 'r' },
479 { "no-regex", no_argument, NULL, 'R' },
480 { "ignore-case-regex", required_argument, NULL, 'c' },
481 { "parse-stdin", required_argument, NULL, STDIN },
482 { "version", no_argument, NULL, 'V' },
484 #if CTAGS /* Ctags options */
485 { "backward-search", no_argument, NULL, 'B' },
486 { "cxref", no_argument, NULL, 'x' },
487 { "defines", no_argument, NULL, 'd' },
488 { "globals", no_argument, &globals, TRUE },
489 { "typedefs", no_argument, NULL, 't' },
490 { "typedefs-and-c++", no_argument, NULL, 'T' },
491 { "update", no_argument, NULL, 'u' },
492 { "vgrind", no_argument, NULL, 'v' },
493 { "no-warn", no_argument, NULL, 'w' },
495 #else /* Etags options */
496 { "no-defines", no_argument, NULL, 'D' },
497 { "no-globals", no_argument, &globals, FALSE },
498 { "include", required_argument, NULL, 'i' },
499 #endif
500 { NULL }
503 static compressor compressors[] =
505 { "z", "gzip -d -c"},
506 { "Z", "gzip -d -c"},
507 { "gz", "gzip -d -c"},
508 { "GZ", "gzip -d -c"},
509 { "bz2", "bzip2 -d -c" },
510 { "xz", "xz -d -c" },
511 { NULL }
515 * Language stuff.
518 /* Ada code */
519 static const char *Ada_suffixes [] =
520 { "ads", "adb", "ada", NULL };
521 static const char Ada_help [] =
522 "In Ada code, functions, procedures, packages, tasks and types are\n\
523 tags. Use the `--packages-only' option to create tags for\n\
524 packages only.\n\
525 Ada tag names have suffixes indicating the type of entity:\n\
526 Entity type: Qualifier:\n\
527 ------------ ----------\n\
528 function /f\n\
529 procedure /p\n\
530 package spec /s\n\
531 package body /b\n\
532 type /t\n\
533 task /k\n\
534 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
535 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
536 will just search for any tag `bidule'.";
538 /* Assembly code */
539 static const char *Asm_suffixes [] =
540 { "a", /* Unix assembler */
541 "asm", /* Microcontroller assembly */
542 "def", /* BSO/Tasking definition includes */
543 "inc", /* Microcontroller include files */
544 "ins", /* Microcontroller include files */
545 "s", "sa", /* Unix assembler */
546 "S", /* cpp-processed Unix assembler */
547 "src", /* BSO/Tasking C compiler output */
548 NULL
550 static const char Asm_help [] =
551 "In assembler code, labels appearing at the beginning of a line,\n\
552 followed by a colon, are tags.";
555 /* Note that .c and .h can be considered C++, if the --c++ flag was
556 given, or if the `class' or `template' keywords are met inside the file.
557 That is why default_C_entries is called for these. */
558 static const char *default_C_suffixes [] =
559 { "c", "h", NULL };
560 #if CTAGS /* C help for Ctags */
561 static const char default_C_help [] =
562 "In C code, any C function is a tag. Use -t to tag typedefs.\n\
563 Use -T to tag definitions of `struct', `union' and `enum'.\n\
564 Use -d to tag `#define' macro definitions and `enum' constants.\n\
565 Use --globals to tag global variables.\n\
566 You can tag function declarations and external variables by\n\
567 using `--declarations', and struct members by using `--members'.";
568 #else /* C help for Etags */
569 static const char default_C_help [] =
570 "In C code, any C function or typedef is a tag, and so are\n\
571 definitions of `struct', `union' and `enum'. `#define' macro\n\
572 definitions and `enum' constants are tags unless you specify\n\
573 `--no-defines'. Global variables are tags unless you specify\n\
574 `--no-globals' and so are struct members unless you specify\n\
575 `--no-members'. Use of `--no-globals', `--no-defines' and\n\
576 `--no-members' can make the tags table file much smaller.\n\
577 You can tag function declarations and external variables by\n\
578 using `--declarations'.";
579 #endif /* C help for Ctags and Etags */
581 static const char *Cplusplus_suffixes [] =
582 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
583 "M", /* Objective C++ */
584 "pdb", /* PostScript with C syntax */
585 NULL };
586 static const char Cplusplus_help [] =
587 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
588 --help --lang=c --lang=c++ for full help.)\n\
589 In addition to C tags, member functions are also recognized. Member\n\
590 variables are recognized unless you use the `--no-members' option.\n\
591 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
592 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
593 `operator+'.";
595 static const char *Cjava_suffixes [] =
596 { "java", NULL };
597 static char Cjava_help [] =
598 "In Java code, all the tags constructs of C and C++ code are\n\
599 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
602 static const char *Cobol_suffixes [] =
603 { "COB", "cob", NULL };
604 static char Cobol_help [] =
605 "In Cobol code, tags are paragraph names; that is, any word\n\
606 starting in column 8 and followed by a period.";
608 static const char *Cstar_suffixes [] =
609 { "cs", "hs", NULL };
611 static const char *Erlang_suffixes [] =
612 { "erl", "hrl", NULL };
613 static const char Erlang_help [] =
614 "In Erlang code, the tags are the functions, records and macros\n\
615 defined in the file.";
617 const char *Forth_suffixes [] =
618 { "fth", "tok", NULL };
619 static const char Forth_help [] =
620 "In Forth code, tags are words defined by `:',\n\
621 constant, code, create, defer, value, variable, buffer:, field.";
623 static const char *Fortran_suffixes [] =
624 { "F", "f", "f90", "for", NULL };
625 static const char Fortran_help [] =
626 "In Fortran code, functions, subroutines and block data are tags.";
628 static const char *HTML_suffixes [] =
629 { "htm", "html", "shtml", NULL };
630 static const char HTML_help [] =
631 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
632 `h3' headers. Also, tags are `name=' in anchors and all\n\
633 occurrences of `id='.";
635 static const char *Lisp_suffixes [] =
636 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
637 static const char Lisp_help [] =
638 "In Lisp code, any function defined with `defun', any variable\n\
639 defined with `defvar' or `defconst', and in general the first\n\
640 argument of any expression that starts with `(def' in column zero\n\
641 is a tag.";
643 static const char *Lua_suffixes [] =
644 { "lua", "LUA", NULL };
645 static const char Lua_help [] =
646 "In Lua scripts, all functions are tags.";
648 static const char *Makefile_filenames [] =
649 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
650 static const char Makefile_help [] =
651 "In makefiles, targets are tags; additionally, variables are tags\n\
652 unless you specify `--no-globals'.";
654 static const char *Objc_suffixes [] =
655 { "lm", /* Objective lex file */
656 "m", /* Objective C file */
657 NULL };
658 static const char Objc_help [] =
659 "In Objective C code, tags include Objective C definitions for classes,\n\
660 class categories, methods and protocols. Tags for variables and\n\
661 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
662 (Use --help --lang=c --lang=objc --lang=java for full help.)";
664 static const char *Pascal_suffixes [] =
665 { "p", "pas", NULL };
666 static const char Pascal_help [] =
667 "In Pascal code, the tags are the functions and procedures defined\n\
668 in the file.";
669 /* " // this is for working around an Emacs highlighting bug... */
671 static const char *Perl_suffixes [] =
672 { "pl", "pm", NULL };
673 static const char *Perl_interpreters [] =
674 { "perl", "@PERL@", NULL };
675 static const char Perl_help [] =
676 "In Perl code, the tags are the packages, subroutines and variables\n\
677 defined by the `package', `sub', `my' and `local' keywords. Use\n\
678 `--globals' if you want to tag global variables. Tags for\n\
679 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
680 defined in the default package is `main::SUB'.";
682 static const char *PHP_suffixes [] =
683 { "php", "php3", "php4", NULL };
684 static const char PHP_help [] =
685 "In PHP code, tags are functions, classes and defines. Unless you use\n\
686 the `--no-members' option, vars are tags too.";
688 static const char *plain_C_suffixes [] =
689 { "pc", /* Pro*C file */
690 NULL };
692 static const char *PS_suffixes [] =
693 { "ps", "psw", NULL }; /* .psw is for PSWrap */
694 static const char PS_help [] =
695 "In PostScript code, the tags are the functions.";
697 static const char *Prolog_suffixes [] =
698 { "prolog", NULL };
699 static const char Prolog_help [] =
700 "In Prolog code, tags are predicates and rules at the beginning of\n\
701 line.";
703 static const char *Python_suffixes [] =
704 { "py", NULL };
705 static const char Python_help [] =
706 "In Python code, `def' or `class' at the beginning of a line\n\
707 generate a tag.";
709 /* Can't do the `SCM' or `scm' prefix with a version number. */
710 static const char *Scheme_suffixes [] =
711 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
712 static const char Scheme_help [] =
713 "In Scheme code, tags include anything defined with `def' or with a\n\
714 construct whose name starts with `def'. They also include\n\
715 variables set with `set!' at top level in the file.";
717 static const char *TeX_suffixes [] =
718 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
719 static const char TeX_help [] =
720 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
721 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
722 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
723 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
724 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
726 Other commands can be specified by setting the environment variable\n\
727 `TEXTAGS' to a colon-separated list like, for example,\n\
728 TEXTAGS=\"mycommand:myothercommand\".";
731 static const char *Texinfo_suffixes [] =
732 { "texi", "texinfo", "txi", NULL };
733 static const char Texinfo_help [] =
734 "for texinfo files, lines starting with @node are tagged.";
736 static const char *Yacc_suffixes [] =
737 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
738 static const char Yacc_help [] =
739 "In Bison or Yacc input files, each rule defines as a tag the\n\
740 nonterminal it constructs. The portions of the file that contain\n\
741 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
742 for full help).";
744 static const char auto_help [] =
745 "`auto' is not a real language, it indicates to use\n\
746 a default language for files base on file name suffix and file contents.";
748 static const char none_help [] =
749 "`none' is not a real language, it indicates to only do\n\
750 regexp processing on files.";
752 static const char no_lang_help [] =
753 "No detailed help available for this language.";
757 * Table of languages.
759 * It is ok for a given function to be listed under more than one
760 * name. I just didn't.
763 static language lang_names [] =
765 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
766 { "asm", Asm_help, Asm_labels, Asm_suffixes },
767 { "c", default_C_help, default_C_entries, default_C_suffixes },
768 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
769 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
770 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
771 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
772 { "forth", Forth_help, Forth_words, Forth_suffixes },
773 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
774 { "html", HTML_help, HTML_labels, HTML_suffixes },
775 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
776 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
777 { "lua", Lua_help, Lua_functions, Lua_suffixes },
778 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
779 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
780 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
781 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
782 { "php", PHP_help, PHP_functions, PHP_suffixes },
783 { "postscript",PS_help, PS_functions, PS_suffixes },
784 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
785 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
786 { "python", Python_help, Python_functions, Python_suffixes },
787 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
788 { "tex", TeX_help, TeX_commands, TeX_suffixes },
789 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
790 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
791 { "auto", auto_help }, /* default guessing scheme */
792 { "none", none_help, just_read_file }, /* regexp matching only */
793 { NULL } /* end of list */
797 static void
798 print_language_names (void)
800 language *lang;
801 const char **name, **ext;
803 puts ("\nThese are the currently supported languages, along with the\n\
804 default file names and dot suffixes:");
805 for (lang = lang_names; lang->name != NULL; lang++)
807 printf (" %-*s", 10, lang->name);
808 if (lang->filenames != NULL)
809 for (name = lang->filenames; *name != NULL; name++)
810 printf (" %s", *name);
811 if (lang->suffixes != NULL)
812 for (ext = lang->suffixes; *ext != NULL; ext++)
813 printf (" .%s", *ext);
814 puts ("");
816 puts ("where `auto' means use default language for files based on file\n\
817 name suffix, and `none' means only do regexp processing on files.\n\
818 If no language is specified and no matching suffix is found,\n\
819 the first line of the file is read for a sharp-bang (#!) sequence\n\
820 followed by the name of an interpreter. If no such sequence is found,\n\
821 Fortran is tried first; if no tags are found, C is tried next.\n\
822 When parsing any C file, a \"class\" or \"template\" keyword\n\
823 switches to C++.");
824 puts ("Compressed files are supported using gzip, bzip2, and xz.\n\
826 For detailed help on a given language use, for example,\n\
827 etags --help --lang=ada.");
830 #ifndef EMACS_NAME
831 # define EMACS_NAME "standalone"
832 #endif
833 #ifndef VERSION
834 # define VERSION "17.38.1.4"
835 #endif
836 static void
837 print_version (void)
839 char emacs_copyright[] = COPYRIGHT;
841 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION);
842 puts (emacs_copyright);
843 puts ("This program is distributed under the terms in ETAGS.README");
845 exit (EXIT_SUCCESS);
848 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
849 # define PRINT_UNDOCUMENTED_OPTIONS_HELP FALSE
850 #endif
852 static void
853 print_help (argument *argbuffer)
855 bool help_for_lang = FALSE;
857 for (; argbuffer->arg_type != at_end; argbuffer++)
858 if (argbuffer->arg_type == at_language)
860 if (help_for_lang)
861 puts ("");
862 puts (argbuffer->lang->help);
863 help_for_lang = TRUE;
866 if (help_for_lang)
867 exit (EXIT_SUCCESS);
869 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
871 These are the options accepted by %s.\n", progname, progname);
872 if (NO_LONG_OPTIONS)
873 puts ("WARNING: long option names do not work with this executable,\n\
874 as it is not linked with GNU getopt.");
875 else
876 puts ("You may use unambiguous abbreviations for the long option names.");
877 puts (" A - as file name means read names from stdin (one per line).\n\
878 Absolute names are stored in the output file as they are.\n\
879 Relative ones are stored relative to the output file's directory.\n");
881 puts ("-a, --append\n\
882 Append tag entries to existing tags file.");
884 puts ("--packages-only\n\
885 For Ada files, only generate tags for packages.");
887 if (CTAGS)
888 puts ("-B, --backward-search\n\
889 Write the search commands for the tag entries using '?', the\n\
890 backward-search command instead of '/', the forward-search command.");
892 /* This option is mostly obsolete, because etags can now automatically
893 detect C++. Retained for backward compatibility and for debugging and
894 experimentation. In principle, we could want to tag as C++ even
895 before any "class" or "template" keyword.
896 puts ("-C, --c++\n\
897 Treat files whose name suffix defaults to C language as C++ files.");
900 puts ("--declarations\n\
901 In C and derived languages, create tags for function declarations,");
902 if (CTAGS)
903 puts ("\tand create tags for extern variables if --globals is used.");
904 else
905 puts
906 ("\tand create tags for extern variables unless --no-globals is used.");
908 if (CTAGS)
909 puts ("-d, --defines\n\
910 Create tag entries for C #define constants and enum constants, too.");
911 else
912 puts ("-D, --no-defines\n\
913 Don't create tag entries for C #define constants and enum constants.\n\
914 This makes the tags file smaller.");
916 if (!CTAGS)
917 puts ("-i FILE, --include=FILE\n\
918 Include a note in tag file indicating that, when searching for\n\
919 a tag, one should also consult the tags file FILE after\n\
920 checking the current file.");
922 puts ("-l LANG, --language=LANG\n\
923 Force the following files to be considered as written in the\n\
924 named language up to the next --language=LANG option.");
926 if (CTAGS)
927 puts ("--globals\n\
928 Create tag entries for global variables in some languages.");
929 else
930 puts ("--no-globals\n\
931 Do not create tag entries for global variables in some\n\
932 languages. This makes the tags file smaller.");
934 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
935 puts ("--no-line-directive\n\
936 Ignore #line preprocessor directives in C and derived languages.");
938 if (CTAGS)
939 puts ("--members\n\
940 Create tag entries for members of structures in some languages.");
941 else
942 puts ("--no-members\n\
943 Do not create tag entries for members of structures\n\
944 in some languages.");
946 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
947 Make a tag for each line matching a regular expression pattern\n\
948 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
949 files only. REGEXFILE is a file containing one REGEXP per line.\n\
950 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
951 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
952 puts (" If TAGNAME/ is present, the tags created are named.\n\
953 For example Tcl named tags can be created with:\n\
954 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
955 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
956 `m' means to allow multi-line matches, `s' implies `m' and\n\
957 causes dot to match any character, including newline.");
959 puts ("-R, --no-regex\n\
960 Don't create tags from regexps for the following files.");
962 puts ("-I, --ignore-indentation\n\
963 In C and C++ do not assume that a closing brace in the first\n\
964 column is the final brace of a function or structure definition.");
966 puts ("-o FILE, --output=FILE\n\
967 Write the tags to FILE.");
969 puts ("--parse-stdin=NAME\n\
970 Read from standard input and record tags as belonging to file NAME.");
972 if (CTAGS)
974 puts ("-t, --typedefs\n\
975 Generate tag entries for C and Ada typedefs.");
976 puts ("-T, --typedefs-and-c++\n\
977 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
978 and C++ member functions.");
981 if (CTAGS)
982 puts ("-u, --update\n\
983 Update the tag entries for the given files, leaving tag\n\
984 entries for other files in place. Currently, this is\n\
985 implemented by deleting the existing entries for the given\n\
986 files and then rewriting the new entries at the end of the\n\
987 tags file. It is often faster to simply rebuild the entire\n\
988 tag file than to use this.");
990 if (CTAGS)
992 puts ("-v, --vgrind\n\
993 Print on the standard output an index of items intended for\n\
994 human consumption, similar to the output of vgrind. The index\n\
995 is sorted, and gives the page number of each item.");
997 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
998 puts ("-w, --no-duplicates\n\
999 Do not create duplicate tag entries, for compatibility with\n\
1000 traditional ctags.");
1002 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1003 puts ("-w, --no-warn\n\
1004 Suppress warning messages about duplicate tag entries.");
1006 puts ("-x, --cxref\n\
1007 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
1008 The output uses line numbers instead of page numbers, but\n\
1009 beyond that the differences are cosmetic; try both to see\n\
1010 which you like.");
1013 puts ("-V, --version\n\
1014 Print the version of the program.\n\
1015 -h, --help\n\
1016 Print this help message.\n\
1017 Followed by one or more `--language' options prints detailed\n\
1018 help about tag generation for the specified languages.");
1020 print_language_names ();
1022 puts ("");
1023 puts ("Report bugs to bug-gnu-emacs@gnu.org");
1025 exit (EXIT_SUCCESS);
1030 main (int argc, char **argv)
1032 int i;
1033 unsigned int nincluded_files;
1034 char **included_files;
1035 argument *argbuffer;
1036 int current_arg, file_count;
1037 linebuffer filename_lb;
1038 bool help_asked = FALSE;
1039 ptrdiff_t len;
1040 char *optstring;
1041 int opt;
1044 #ifdef DOS_NT
1045 _fmode = O_BINARY; /* all of files are treated as binary files */
1046 #endif /* DOS_NT */
1048 progname = argv[0];
1049 nincluded_files = 0;
1050 included_files = xnew (argc, char *);
1051 current_arg = 0;
1052 file_count = 0;
1054 /* Allocate enough no matter what happens. Overkill, but each one
1055 is small. */
1056 argbuffer = xnew (argc, argument);
1059 * Always find typedefs and structure tags.
1060 * Also default to find macro constants, enum constants, struct
1061 * members and global variables. Do it for both etags and ctags.
1063 typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1064 globals = members = TRUE;
1066 /* When the optstring begins with a '-' getopt_long does not rearrange the
1067 non-options arguments to be at the end, but leaves them alone. */
1068 optstring = concat (NO_LONG_OPTIONS ? "" : "-",
1069 "ac:Cf:Il:o:r:RSVhH",
1070 (CTAGS) ? "BxdtTuvw" : "Di:");
1072 while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1073 switch (opt)
1075 case 0:
1076 /* If getopt returns 0, then it has already processed a
1077 long-named option. We should do nothing. */
1078 break;
1080 case 1:
1081 /* This means that a file name has been seen. Record it. */
1082 argbuffer[current_arg].arg_type = at_filename;
1083 argbuffer[current_arg].what = optarg;
1084 len = strlen (optarg);
1085 if (whatlen_max < len)
1086 whatlen_max = len;
1087 ++current_arg;
1088 ++file_count;
1089 break;
1091 case STDIN:
1092 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1093 argbuffer[current_arg].arg_type = at_stdin;
1094 argbuffer[current_arg].what = optarg;
1095 len = strlen (optarg);
1096 if (whatlen_max < len)
1097 whatlen_max = len;
1098 ++current_arg;
1099 ++file_count;
1100 if (parsing_stdin)
1101 fatal ("cannot parse standard input more than once", (char *)NULL);
1102 parsing_stdin = TRUE;
1103 break;
1105 /* Common options. */
1106 case 'a': append_to_tagfile = TRUE; break;
1107 case 'C': cplusplus = TRUE; break;
1108 case 'f': /* for compatibility with old makefiles */
1109 case 'o':
1110 if (tagfile)
1112 error ("-o option may only be given once.");
1113 suggest_asking_for_help ();
1114 /* NOTREACHED */
1116 tagfile = optarg;
1117 break;
1118 case 'I':
1119 case 'S': /* for backward compatibility */
1120 ignoreindent = TRUE;
1121 break;
1122 case 'l':
1124 language *lang = get_language_from_langname (optarg);
1125 if (lang != NULL)
1127 argbuffer[current_arg].lang = lang;
1128 argbuffer[current_arg].arg_type = at_language;
1129 ++current_arg;
1132 break;
1133 case 'c':
1134 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1135 optarg = concat (optarg, "i", ""); /* memory leak here */
1136 /* FALLTHRU */
1137 case 'r':
1138 argbuffer[current_arg].arg_type = at_regexp;
1139 argbuffer[current_arg].what = optarg;
1140 len = strlen (optarg);
1141 if (whatlen_max < len)
1142 whatlen_max = len;
1143 ++current_arg;
1144 break;
1145 case 'R':
1146 argbuffer[current_arg].arg_type = at_regexp;
1147 argbuffer[current_arg].what = NULL;
1148 ++current_arg;
1149 break;
1150 case 'V':
1151 print_version ();
1152 break;
1153 case 'h':
1154 case 'H':
1155 help_asked = TRUE;
1156 break;
1158 /* Etags options */
1159 case 'D': constantypedefs = FALSE; break;
1160 case 'i': included_files[nincluded_files++] = optarg; break;
1162 /* Ctags options. */
1163 case 'B': searchar = '?'; break;
1164 case 'd': constantypedefs = TRUE; break;
1165 case 't': typedefs = TRUE; break;
1166 case 'T': typedefs = typedefs_or_cplusplus = TRUE; break;
1167 case 'u': update = TRUE; break;
1168 case 'v': vgrind_style = TRUE; /*FALLTHRU*/
1169 case 'x': cxref_style = TRUE; break;
1170 case 'w': no_warnings = TRUE; break;
1171 default:
1172 suggest_asking_for_help ();
1173 /* NOTREACHED */
1176 /* No more options. Store the rest of arguments. */
1177 for (; optind < argc; optind++)
1179 argbuffer[current_arg].arg_type = at_filename;
1180 argbuffer[current_arg].what = argv[optind];
1181 len = strlen (argv[optind]);
1182 if (whatlen_max < len)
1183 whatlen_max = len;
1184 ++current_arg;
1185 ++file_count;
1188 argbuffer[current_arg].arg_type = at_end;
1190 if (help_asked)
1191 print_help (argbuffer);
1192 /* NOTREACHED */
1194 if (nincluded_files == 0 && file_count == 0)
1196 error ("no input files specified.");
1197 suggest_asking_for_help ();
1198 /* NOTREACHED */
1201 if (tagfile == NULL)
1202 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1203 cwd = etags_getcwd (); /* the current working directory */
1204 if (cwd[strlen (cwd) - 1] != '/')
1206 char *oldcwd = cwd;
1207 cwd = concat (oldcwd, "/", "");
1208 free (oldcwd);
1211 /* Compute base directory for relative file names. */
1212 if (streq (tagfile, "-")
1213 || strneq (tagfile, "/dev/", 5))
1214 tagfiledir = cwd; /* relative file names are relative to cwd */
1215 else
1217 canonicalize_filename (tagfile);
1218 tagfiledir = absolute_dirname (tagfile, cwd);
1221 init (); /* set up boolean "functions" */
1223 linebuffer_init (&lb);
1224 linebuffer_init (&filename_lb);
1225 linebuffer_init (&filebuf);
1226 linebuffer_init (&token_name);
1228 if (!CTAGS)
1230 if (streq (tagfile, "-"))
1232 tagf = stdout;
1233 #ifdef DOS_NT
1234 /* Switch redirected `stdout' to binary mode (setting `_fmode'
1235 doesn't take effect until after `stdout' is already open). */
1236 if (!isatty (fileno (stdout)))
1237 setmode (fileno (stdout), O_BINARY);
1238 #endif /* DOS_NT */
1240 else
1241 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1242 if (tagf == NULL)
1243 pfatal (tagfile);
1247 * Loop through files finding functions.
1249 for (i = 0; i < current_arg; i++)
1251 static language *lang; /* non-NULL if language is forced */
1252 char *this_file;
1254 switch (argbuffer[i].arg_type)
1256 case at_language:
1257 lang = argbuffer[i].lang;
1258 break;
1259 case at_regexp:
1260 analyse_regex (argbuffer[i].what);
1261 break;
1262 case at_filename:
1263 this_file = argbuffer[i].what;
1264 /* Input file named "-" means read file names from stdin
1265 (one per line) and use them. */
1266 if (streq (this_file, "-"))
1268 if (parsing_stdin)
1269 fatal ("cannot parse standard input AND read file names from it",
1270 (char *)NULL);
1271 while (readline_internal (&filename_lb, stdin) > 0)
1272 process_file_name (filename_lb.buffer, lang);
1274 else
1275 process_file_name (this_file, lang);
1276 break;
1277 case at_stdin:
1278 this_file = argbuffer[i].what;
1279 process_file (stdin, this_file, lang);
1280 break;
1284 free_regexps ();
1285 free (lb.buffer);
1286 free (filebuf.buffer);
1287 free (token_name.buffer);
1289 if (!CTAGS || cxref_style)
1291 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1292 put_entries (nodehead);
1293 free_tree (nodehead);
1294 nodehead = NULL;
1295 if (!CTAGS)
1297 fdesc *fdp;
1299 /* Output file entries that have no tags. */
1300 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1301 if (!fdp->written)
1302 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1304 while (nincluded_files-- > 0)
1305 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1307 if (fclose (tagf) == EOF)
1308 pfatal (tagfile);
1311 exit (EXIT_SUCCESS);
1314 /* From here on, we are in (CTAGS && !cxref_style) */
1315 if (update)
1317 char *cmd =
1318 xmalloc (strlen (tagfile) + whatlen_max +
1319 sizeof "mv..OTAGS;fgrep -v '\t\t' OTAGS >;rm OTAGS");
1320 for (i = 0; i < current_arg; ++i)
1322 switch (argbuffer[i].arg_type)
1324 case at_filename:
1325 case at_stdin:
1326 break;
1327 default:
1328 continue; /* the for loop */
1330 strcpy (cmd, "mv ");
1331 strcat (cmd, tagfile);
1332 strcat (cmd, " OTAGS;fgrep -v '\t");
1333 strcat (cmd, argbuffer[i].what);
1334 strcat (cmd, "\t' OTAGS >");
1335 strcat (cmd, tagfile);
1336 strcat (cmd, ";rm OTAGS");
1337 if (system (cmd) != EXIT_SUCCESS)
1338 fatal ("failed to execute shell command", (char *)NULL);
1340 free (cmd);
1341 append_to_tagfile = TRUE;
1344 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1345 if (tagf == NULL)
1346 pfatal (tagfile);
1347 put_entries (nodehead); /* write all the tags (CTAGS) */
1348 free_tree (nodehead);
1349 nodehead = NULL;
1350 if (fclose (tagf) == EOF)
1351 pfatal (tagfile);
1353 if (CTAGS)
1354 if (append_to_tagfile || update)
1356 char *cmd = xmalloc (2 * strlen (tagfile) + sizeof "sort -u -o..");
1357 /* Maybe these should be used:
1358 setenv ("LC_COLLATE", "C", 1);
1359 setenv ("LC_ALL", "C", 1); */
1360 strcpy (cmd, "sort -u -o ");
1361 strcat (cmd, tagfile);
1362 strcat (cmd, " ");
1363 strcat (cmd, tagfile);
1364 exit (system (cmd));
1366 return EXIT_SUCCESS;
1371 * Return a compressor given the file name. If EXTPTR is non-zero,
1372 * return a pointer into FILE where the compressor-specific
1373 * extension begins. If no compressor is found, NULL is returned
1374 * and EXTPTR is not significant.
1375 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1377 static compressor *
1378 get_compressor_from_suffix (char *file, char **extptr)
1380 compressor *compr;
1381 char *slash, *suffix;
1383 /* File has been processed by canonicalize_filename,
1384 so we don't need to consider backslashes on DOS_NT. */
1385 slash = etags_strrchr (file, '/');
1386 suffix = etags_strrchr (file, '.');
1387 if (suffix == NULL || suffix < slash)
1388 return NULL;
1389 if (extptr != NULL)
1390 *extptr = suffix;
1391 suffix += 1;
1392 /* Let those poor souls who live with DOS 8+3 file name limits get
1393 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1394 Only the first do loop is run if not MSDOS */
1397 for (compr = compressors; compr->suffix != NULL; compr++)
1398 if (streq (compr->suffix, suffix))
1399 return compr;
1400 if (!MSDOS)
1401 break; /* do it only once: not really a loop */
1402 if (extptr != NULL)
1403 *extptr = ++suffix;
1404 } while (*suffix != '\0');
1405 return NULL;
1411 * Return a language given the name.
1413 static language *
1414 get_language_from_langname (const char *name)
1416 language *lang;
1418 if (name == NULL)
1419 error ("empty language name");
1420 else
1422 for (lang = lang_names; lang->name != NULL; lang++)
1423 if (streq (name, lang->name))
1424 return lang;
1425 error ("unknown language \"%s\"", name);
1428 return NULL;
1433 * Return a language given the interpreter name.
1435 static language *
1436 get_language_from_interpreter (char *interpreter)
1438 language *lang;
1439 const char **iname;
1441 if (interpreter == NULL)
1442 return NULL;
1443 for (lang = lang_names; lang->name != NULL; lang++)
1444 if (lang->interpreters != NULL)
1445 for (iname = lang->interpreters; *iname != NULL; iname++)
1446 if (streq (*iname, interpreter))
1447 return lang;
1449 return NULL;
1455 * Return a language given the file name.
1457 static language *
1458 get_language_from_filename (char *file, int case_sensitive)
1460 language *lang;
1461 const char **name, **ext, *suffix;
1463 /* Try whole file name first. */
1464 for (lang = lang_names; lang->name != NULL; lang++)
1465 if (lang->filenames != NULL)
1466 for (name = lang->filenames; *name != NULL; name++)
1467 if ((case_sensitive)
1468 ? streq (*name, file)
1469 : strcaseeq (*name, file))
1470 return lang;
1472 /* If not found, try suffix after last dot. */
1473 suffix = etags_strrchr (file, '.');
1474 if (suffix == NULL)
1475 return NULL;
1476 suffix += 1;
1477 for (lang = lang_names; lang->name != NULL; lang++)
1478 if (lang->suffixes != NULL)
1479 for (ext = lang->suffixes; *ext != NULL; ext++)
1480 if ((case_sensitive)
1481 ? streq (*ext, suffix)
1482 : strcaseeq (*ext, suffix))
1483 return lang;
1484 return NULL;
1489 * This routine is called on each file argument.
1491 static void
1492 process_file_name (char *file, language *lang)
1494 struct stat stat_buf;
1495 FILE *inf;
1496 fdesc *fdp;
1497 compressor *compr;
1498 char *compressed_name, *uncompressed_name;
1499 char *ext, *real_name;
1500 int retval;
1502 canonicalize_filename (file);
1503 if (streq (file, tagfile) && !streq (tagfile, "-"))
1505 error ("skipping inclusion of %s in self.", file);
1506 return;
1508 if ((compr = get_compressor_from_suffix (file, &ext)) == NULL)
1510 compressed_name = NULL;
1511 real_name = uncompressed_name = savestr (file);
1513 else
1515 real_name = compressed_name = savestr (file);
1516 uncompressed_name = savenstr (file, ext - file);
1519 /* If the canonicalized uncompressed name
1520 has already been dealt with, skip it silently. */
1521 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1523 assert (fdp->infname != NULL);
1524 if (streq (uncompressed_name, fdp->infname))
1525 goto cleanup;
1528 if (stat (real_name, &stat_buf) != 0)
1530 /* Reset real_name and try with a different name. */
1531 real_name = NULL;
1532 if (compressed_name != NULL) /* try with the given suffix */
1534 if (stat (uncompressed_name, &stat_buf) == 0)
1535 real_name = uncompressed_name;
1537 else /* try all possible suffixes */
1539 for (compr = compressors; compr->suffix != NULL; compr++)
1541 compressed_name = concat (file, ".", compr->suffix);
1542 if (stat (compressed_name, &stat_buf) != 0)
1544 if (MSDOS)
1546 char *suf = compressed_name + strlen (file);
1547 size_t suflen = strlen (compr->suffix) + 1;
1548 for ( ; suf[1]; suf++, suflen--)
1550 memmove (suf, suf + 1, suflen);
1551 if (stat (compressed_name, &stat_buf) == 0)
1553 real_name = compressed_name;
1554 break;
1557 if (real_name != NULL)
1558 break;
1559 } /* MSDOS */
1560 free (compressed_name);
1561 compressed_name = NULL;
1563 else
1565 real_name = compressed_name;
1566 break;
1570 if (real_name == NULL)
1572 perror (file);
1573 goto cleanup;
1575 } /* try with a different name */
1577 if (!S_ISREG (stat_buf.st_mode))
1579 error ("skipping %s: it is not a regular file.", real_name);
1580 goto cleanup;
1582 if (real_name == compressed_name)
1584 char *cmd = concat (compr->command, " ", real_name);
1585 inf = (FILE *) popen (cmd, "r");
1586 free (cmd);
1588 else
1589 inf = fopen (real_name, "r");
1590 if (inf == NULL)
1592 perror (real_name);
1593 goto cleanup;
1596 process_file (inf, uncompressed_name, lang);
1598 if (real_name == compressed_name)
1599 retval = pclose (inf);
1600 else
1601 retval = fclose (inf);
1602 if (retval < 0)
1603 pfatal (file);
1605 cleanup:
1606 free (compressed_name);
1607 free (uncompressed_name);
1608 last_node = NULL;
1609 curfdp = NULL;
1610 return;
1613 static void
1614 process_file (FILE *fh, char *fn, language *lang)
1616 static const fdesc emptyfdesc;
1617 fdesc *fdp;
1619 /* Create a new input file description entry. */
1620 fdp = xnew (1, fdesc);
1621 *fdp = emptyfdesc;
1622 fdp->next = fdhead;
1623 fdp->infname = savestr (fn);
1624 fdp->lang = lang;
1625 fdp->infabsname = absolute_filename (fn, cwd);
1626 fdp->infabsdir = absolute_dirname (fn, cwd);
1627 if (filename_is_absolute (fn))
1629 /* An absolute file name. Canonicalize it. */
1630 fdp->taggedfname = absolute_filename (fn, NULL);
1632 else
1634 /* A file name relative to cwd. Make it relative
1635 to the directory of the tags file. */
1636 fdp->taggedfname = relative_filename (fn, tagfiledir);
1638 fdp->usecharno = TRUE; /* use char position when making tags */
1639 fdp->prop = NULL;
1640 fdp->written = FALSE; /* not written on tags file yet */
1642 fdhead = fdp;
1643 curfdp = fdhead; /* the current file description */
1645 find_entries (fh);
1647 /* If not Ctags, and if this is not metasource and if it contained no #line
1648 directives, we can write the tags and free all nodes pointing to
1649 curfdp. */
1650 if (!CTAGS
1651 && curfdp->usecharno /* no #line directives in this file */
1652 && !curfdp->lang->metasource)
1654 node *np, *prev;
1656 /* Look for the head of the sublist relative to this file. See add_node
1657 for the structure of the node tree. */
1658 prev = NULL;
1659 for (np = nodehead; np != NULL; prev = np, np = np->left)
1660 if (np->fdp == curfdp)
1661 break;
1663 /* If we generated tags for this file, write and delete them. */
1664 if (np != NULL)
1666 /* This is the head of the last sublist, if any. The following
1667 instructions depend on this being true. */
1668 assert (np->left == NULL);
1670 assert (fdhead == curfdp);
1671 assert (last_node->fdp == curfdp);
1672 put_entries (np); /* write tags for file curfdp->taggedfname */
1673 free_tree (np); /* remove the written nodes */
1674 if (prev == NULL)
1675 nodehead = NULL; /* no nodes left */
1676 else
1677 prev->left = NULL; /* delete the pointer to the sublist */
1683 * This routine sets up the boolean pseudo-functions which work
1684 * by setting boolean flags dependent upon the corresponding character.
1685 * Every char which is NOT in that string is not a white char. Therefore,
1686 * all of the array "_wht" is set to FALSE, and then the elements
1687 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1688 * of a char is TRUE if it is the string "white", else FALSE.
1690 static void
1691 init (void)
1693 register const char *sp;
1694 register int i;
1696 for (i = 0; i < CHARS; i++)
1697 iswhite (i) = notinname (i) = begtoken (i) = intoken (i) = endtoken (i) = FALSE;
1698 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1699 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1700 notinname ('\0') = notinname ('\n');
1701 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1702 begtoken ('\0') = begtoken ('\n');
1703 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1704 intoken ('\0') = intoken ('\n');
1705 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1706 endtoken ('\0') = endtoken ('\n');
1710 * This routine opens the specified file and calls the function
1711 * which finds the function and type definitions.
1713 static void
1714 find_entries (FILE *inf)
1716 char *cp;
1717 language *lang = curfdp->lang;
1718 Lang_function *parser = NULL;
1720 /* If user specified a language, use it. */
1721 if (lang != NULL && lang->function != NULL)
1723 parser = lang->function;
1726 /* Else try to guess the language given the file name. */
1727 if (parser == NULL)
1729 lang = get_language_from_filename (curfdp->infname, TRUE);
1730 if (lang != NULL && lang->function != NULL)
1732 curfdp->lang = lang;
1733 parser = lang->function;
1737 /* Else look for sharp-bang as the first two characters. */
1738 if (parser == NULL
1739 && readline_internal (&lb, inf) > 0
1740 && lb.len >= 2
1741 && lb.buffer[0] == '#'
1742 && lb.buffer[1] == '!')
1744 char *lp;
1746 /* Set lp to point at the first char after the last slash in the
1747 line or, if no slashes, at the first nonblank. Then set cp to
1748 the first successive blank and terminate the string. */
1749 lp = etags_strrchr (lb.buffer+2, '/');
1750 if (lp != NULL)
1751 lp += 1;
1752 else
1753 lp = skip_spaces (lb.buffer + 2);
1754 cp = skip_non_spaces (lp);
1755 *cp = '\0';
1757 if (strlen (lp) > 0)
1759 lang = get_language_from_interpreter (lp);
1760 if (lang != NULL && lang->function != NULL)
1762 curfdp->lang = lang;
1763 parser = lang->function;
1768 /* We rewind here, even if inf may be a pipe. We fail if the
1769 length of the first line is longer than the pipe block size,
1770 which is unlikely. */
1771 rewind (inf);
1773 /* Else try to guess the language given the case insensitive file name. */
1774 if (parser == NULL)
1776 lang = get_language_from_filename (curfdp->infname, FALSE);
1777 if (lang != NULL && lang->function != NULL)
1779 curfdp->lang = lang;
1780 parser = lang->function;
1784 /* Else try Fortran or C. */
1785 if (parser == NULL)
1787 node *old_last_node = last_node;
1789 curfdp->lang = get_language_from_langname ("fortran");
1790 find_entries (inf);
1792 if (old_last_node == last_node)
1793 /* No Fortran entries found. Try C. */
1795 /* We do not tag if rewind fails.
1796 Only the file name will be recorded in the tags file. */
1797 rewind (inf);
1798 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1799 find_entries (inf);
1801 return;
1804 if (!no_line_directive
1805 && curfdp->lang != NULL && curfdp->lang->metasource)
1806 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1807 file, or anyway we parsed a file that is automatically generated from
1808 this one. If this is the case, the bingo.c file contained #line
1809 directives that generated tags pointing to this file. Let's delete
1810 them all before parsing this file, which is the real source. */
1812 fdesc **fdpp = &fdhead;
1813 while (*fdpp != NULL)
1814 if (*fdpp != curfdp
1815 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1816 /* We found one of those! We must delete both the file description
1817 and all tags referring to it. */
1819 fdesc *badfdp = *fdpp;
1821 /* Delete the tags referring to badfdp->taggedfname
1822 that were obtained from badfdp->infname. */
1823 invalidate_nodes (badfdp, &nodehead);
1825 *fdpp = badfdp->next; /* remove the bad description from the list */
1826 free_fdesc (badfdp);
1828 else
1829 fdpp = &(*fdpp)->next; /* advance the list pointer */
1832 assert (parser != NULL);
1834 /* Generic initializations before reading from file. */
1835 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1837 /* Generic initializations before parsing file with readline. */
1838 lineno = 0; /* reset global line number */
1839 charno = 0; /* reset global char number */
1840 linecharno = 0; /* reset global char number of line start */
1842 parser (inf);
1844 regex_tag_multiline ();
1849 * Check whether an implicitly named tag should be created,
1850 * then call `pfnote'.
1851 * NAME is a string that is internally copied by this function.
1853 * TAGS format specification
1854 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1855 * The following is explained in some more detail in etc/ETAGS.EBNF.
1857 * make_tag creates tags with "implicit tag names" (unnamed tags)
1858 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1859 * 1. NAME does not contain any of the characters in NONAM;
1860 * 2. LINESTART contains name as either a rightmost, or rightmost but
1861 * one character, substring;
1862 * 3. the character, if any, immediately before NAME in LINESTART must
1863 * be a character in NONAM;
1864 * 4. the character, if any, immediately after NAME in LINESTART must
1865 * also be a character in NONAM.
1867 * The implementation uses the notinname() macro, which recognizes the
1868 * characters stored in the string `nonam'.
1869 * etags.el needs to use the same characters that are in NONAM.
1871 static void
1872 make_tag (const char *name, /* tag name, or NULL if unnamed */
1873 int namelen, /* tag length */
1874 int is_func, /* tag is a function */
1875 char *linestart, /* start of the line where tag is */
1876 int linelen, /* length of the line where tag is */
1877 int lno, /* line number */
1878 long int cno) /* character number */
1880 bool named = (name != NULL && namelen > 0);
1881 char *nname = NULL;
1883 if (!CTAGS && named) /* maybe set named to false */
1884 /* Let's try to make an implicit tag name, that is, create an unnamed tag
1885 such that etags.el can guess a name from it. */
1887 int i;
1888 register const char *cp = name;
1890 for (i = 0; i < namelen; i++)
1891 if (notinname (*cp++))
1892 break;
1893 if (i == namelen) /* rule #1 */
1895 cp = linestart + linelen - namelen;
1896 if (notinname (linestart[linelen-1]))
1897 cp -= 1; /* rule #4 */
1898 if (cp >= linestart /* rule #2 */
1899 && (cp == linestart
1900 || notinname (cp[-1])) /* rule #3 */
1901 && strneq (name, cp, namelen)) /* rule #2 */
1902 named = FALSE; /* use implicit tag name */
1906 if (named)
1907 nname = savenstr (name, namelen);
1909 pfnote (nname, is_func, linestart, linelen, lno, cno);
1912 /* Record a tag. */
1913 static void
1914 pfnote (char *name, int is_func, char *linestart, int linelen, int lno, long int cno)
1915 /* tag name, or NULL if unnamed */
1916 /* tag is a function */
1917 /* start of the line where tag is */
1918 /* length of the line where tag is */
1919 /* line number */
1920 /* character number */
1922 register node *np;
1924 assert (name == NULL || name[0] != '\0');
1925 if (CTAGS && name == NULL)
1926 return;
1928 np = xnew (1, node);
1930 /* If ctags mode, change name "main" to M<thisfilename>. */
1931 if (CTAGS && !cxref_style && streq (name, "main"))
1933 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
1934 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
1935 fp = etags_strrchr (np->name, '.');
1936 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
1937 fp[0] = '\0';
1939 else
1940 np->name = name;
1941 np->valid = TRUE;
1942 np->been_warned = FALSE;
1943 np->fdp = curfdp;
1944 np->is_func = is_func;
1945 np->lno = lno;
1946 if (np->fdp->usecharno)
1947 /* Our char numbers are 0-base, because of C language tradition?
1948 ctags compatibility? old versions compatibility? I don't know.
1949 Anyway, since emacs's are 1-base we expect etags.el to take care
1950 of the difference. If we wanted to have 1-based numbers, we would
1951 uncomment the +1 below. */
1952 np->cno = cno /* + 1 */ ;
1953 else
1954 np->cno = invalidcharno;
1955 np->left = np->right = NULL;
1956 if (CTAGS && !cxref_style)
1958 if (strlen (linestart) < 50)
1959 np->regex = concat (linestart, "$", "");
1960 else
1961 np->regex = savenstr (linestart, 50);
1963 else
1964 np->regex = savenstr (linestart, linelen);
1966 add_node (np, &nodehead);
1970 * free_tree ()
1971 * recurse on left children, iterate on right children.
1973 static void
1974 free_tree (register node *np)
1976 while (np)
1978 register node *node_right = np->right;
1979 free_tree (np->left);
1980 free (np->name);
1981 free (np->regex);
1982 free (np);
1983 np = node_right;
1988 * free_fdesc ()
1989 * delete a file description
1991 static void
1992 free_fdesc (register fdesc *fdp)
1994 free (fdp->infname);
1995 free (fdp->infabsname);
1996 free (fdp->infabsdir);
1997 free (fdp->taggedfname);
1998 free (fdp->prop);
1999 free (fdp);
2003 * add_node ()
2004 * Adds a node to the tree of nodes. In etags mode, sort by file
2005 * name. In ctags mode, sort by tag name. Make no attempt at
2006 * balancing.
2008 * add_node is the only function allowed to add nodes, so it can
2009 * maintain state.
2011 static void
2012 add_node (node *np, node **cur_node_p)
2014 register int dif;
2015 register node *cur_node = *cur_node_p;
2017 if (cur_node == NULL)
2019 *cur_node_p = np;
2020 last_node = np;
2021 return;
2024 if (!CTAGS)
2025 /* Etags Mode */
2027 /* For each file name, tags are in a linked sublist on the right
2028 pointer. The first tags of different files are a linked list
2029 on the left pointer. last_node points to the end of the last
2030 used sublist. */
2031 if (last_node != NULL && last_node->fdp == np->fdp)
2033 /* Let's use the same sublist as the last added node. */
2034 assert (last_node->right == NULL);
2035 last_node->right = np;
2036 last_node = np;
2038 else if (cur_node->fdp == np->fdp)
2040 /* Scanning the list we found the head of a sublist which is
2041 good for us. Let's scan this sublist. */
2042 add_node (np, &cur_node->right);
2044 else
2045 /* The head of this sublist is not good for us. Let's try the
2046 next one. */
2047 add_node (np, &cur_node->left);
2048 } /* if ETAGS mode */
2050 else
2052 /* Ctags Mode */
2053 dif = strcmp (np->name, cur_node->name);
2056 * If this tag name matches an existing one, then
2057 * do not add the node, but maybe print a warning.
2059 if (no_duplicates && !dif)
2061 if (np->fdp == cur_node->fdp)
2063 if (!no_warnings)
2065 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2066 np->fdp->infname, lineno, np->name);
2067 fprintf (stderr, "Second entry ignored\n");
2070 else if (!cur_node->been_warned && !no_warnings)
2072 fprintf
2073 (stderr,
2074 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2075 np->fdp->infname, cur_node->fdp->infname, np->name);
2076 cur_node->been_warned = TRUE;
2078 return;
2081 /* Actually add the node */
2082 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2083 } /* if CTAGS mode */
2087 * invalidate_nodes ()
2088 * Scan the node tree and invalidate all nodes pointing to the
2089 * given file description (CTAGS case) or free them (ETAGS case).
2091 static void
2092 invalidate_nodes (fdesc *badfdp, node **npp)
2094 node *np = *npp;
2096 if (np == NULL)
2097 return;
2099 if (CTAGS)
2101 if (np->left != NULL)
2102 invalidate_nodes (badfdp, &np->left);
2103 if (np->fdp == badfdp)
2104 np->valid = FALSE;
2105 if (np->right != NULL)
2106 invalidate_nodes (badfdp, &np->right);
2108 else
2110 assert (np->fdp != NULL);
2111 if (np->fdp == badfdp)
2113 *npp = np->left; /* detach the sublist from the list */
2114 np->left = NULL; /* isolate it */
2115 free_tree (np); /* free it */
2116 invalidate_nodes (badfdp, npp);
2118 else
2119 invalidate_nodes (badfdp, &np->left);
2124 static int total_size_of_entries (node *);
2125 static int number_len (long) ATTRIBUTE_CONST;
2127 /* Length of a non-negative number's decimal representation. */
2128 static int
2129 number_len (long int num)
2131 int len = 1;
2132 while ((num /= 10) > 0)
2133 len += 1;
2134 return len;
2138 * Return total number of characters that put_entries will output for
2139 * the nodes in the linked list at the right of the specified node.
2140 * This count is irrelevant with etags.el since emacs 19.34 at least,
2141 * but is still supplied for backward compatibility.
2143 static int
2144 total_size_of_entries (register node *np)
2146 register int total = 0;
2148 for (; np != NULL; np = np->right)
2149 if (np->valid)
2151 total += strlen (np->regex) + 1; /* pat\177 */
2152 if (np->name != NULL)
2153 total += strlen (np->name) + 1; /* name\001 */
2154 total += number_len ((long) np->lno) + 1; /* lno, */
2155 if (np->cno != invalidcharno) /* cno */
2156 total += number_len (np->cno);
2157 total += 1; /* newline */
2160 return total;
2163 static void
2164 put_entries (register node *np)
2166 register char *sp;
2167 static fdesc *fdp = NULL;
2169 if (np == NULL)
2170 return;
2172 /* Output subentries that precede this one */
2173 if (CTAGS)
2174 put_entries (np->left);
2176 /* Output this entry */
2177 if (np->valid)
2179 if (!CTAGS)
2181 /* Etags mode */
2182 if (fdp != np->fdp)
2184 fdp = np->fdp;
2185 fprintf (tagf, "\f\n%s,%d\n",
2186 fdp->taggedfname, total_size_of_entries (np));
2187 fdp->written = TRUE;
2189 fputs (np->regex, tagf);
2190 fputc ('\177', tagf);
2191 if (np->name != NULL)
2193 fputs (np->name, tagf);
2194 fputc ('\001', tagf);
2196 fprintf (tagf, "%d,", np->lno);
2197 if (np->cno != invalidcharno)
2198 fprintf (tagf, "%ld", np->cno);
2199 fputs ("\n", tagf);
2201 else
2203 /* Ctags mode */
2204 if (np->name == NULL)
2205 error ("internal error: NULL name in ctags mode.");
2207 if (cxref_style)
2209 if (vgrind_style)
2210 fprintf (stdout, "%s %s %d\n",
2211 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2212 else
2213 fprintf (stdout, "%-16s %3d %-16s %s\n",
2214 np->name, np->lno, np->fdp->taggedfname, np->regex);
2216 else
2218 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2220 if (np->is_func)
2221 { /* function or #define macro with args */
2222 putc (searchar, tagf);
2223 putc ('^', tagf);
2225 for (sp = np->regex; *sp; sp++)
2227 if (*sp == '\\' || *sp == searchar)
2228 putc ('\\', tagf);
2229 putc (*sp, tagf);
2231 putc (searchar, tagf);
2233 else
2234 { /* anything else; text pattern inadequate */
2235 fprintf (tagf, "%d", np->lno);
2237 putc ('\n', tagf);
2240 } /* if this node contains a valid tag */
2242 /* Output subentries that follow this one */
2243 put_entries (np->right);
2244 if (!CTAGS)
2245 put_entries (np->left);
2249 /* C extensions. */
2250 #define C_EXT 0x00fff /* C extensions */
2251 #define C_PLAIN 0x00000 /* C */
2252 #define C_PLPL 0x00001 /* C++ */
2253 #define C_STAR 0x00003 /* C* */
2254 #define C_JAVA 0x00005 /* JAVA */
2255 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2256 #define YACC 0x10000 /* yacc file */
2259 * The C symbol tables.
2261 enum sym_type
2263 st_none,
2264 st_C_objprot, st_C_objimpl, st_C_objend,
2265 st_C_gnumacro,
2266 st_C_ignore, st_C_attribute,
2267 st_C_javastruct,
2268 st_C_operator,
2269 st_C_class, st_C_template,
2270 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2273 static unsigned int hash (const char *, unsigned int);
2274 static struct C_stab_entry * in_word_set (const char *, unsigned int);
2275 static enum sym_type C_symtype (char *, int, int);
2277 /* Feed stuff between (but not including) %[ and %] lines to:
2278 gperf -m 5
2280 %compare-strncmp
2281 %enum
2282 %struct-type
2283 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2285 if, 0, st_C_ignore
2286 for, 0, st_C_ignore
2287 while, 0, st_C_ignore
2288 switch, 0, st_C_ignore
2289 return, 0, st_C_ignore
2290 __attribute__, 0, st_C_attribute
2291 GTY, 0, st_C_attribute
2292 @interface, 0, st_C_objprot
2293 @protocol, 0, st_C_objprot
2294 @implementation,0, st_C_objimpl
2295 @end, 0, st_C_objend
2296 import, (C_JAVA & ~C_PLPL), st_C_ignore
2297 package, (C_JAVA & ~C_PLPL), st_C_ignore
2298 friend, C_PLPL, st_C_ignore
2299 extends, (C_JAVA & ~C_PLPL), st_C_javastruct
2300 implements, (C_JAVA & ~C_PLPL), st_C_javastruct
2301 interface, (C_JAVA & ~C_PLPL), st_C_struct
2302 class, 0, st_C_class
2303 namespace, C_PLPL, st_C_struct
2304 domain, C_STAR, st_C_struct
2305 union, 0, st_C_struct
2306 struct, 0, st_C_struct
2307 extern, 0, st_C_extern
2308 enum, 0, st_C_enum
2309 typedef, 0, st_C_typedef
2310 define, 0, st_C_define
2311 undef, 0, st_C_define
2312 operator, C_PLPL, st_C_operator
2313 template, 0, st_C_template
2314 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2315 DEFUN, 0, st_C_gnumacro
2316 SYSCALL, 0, st_C_gnumacro
2317 ENTRY, 0, st_C_gnumacro
2318 PSEUDO, 0, st_C_gnumacro
2319 # These are defined inside C functions, so currently they are not met.
2320 # EXFUN used in glibc, DEFVAR_* in emacs.
2321 #EXFUN, 0, st_C_gnumacro
2322 #DEFVAR_, 0, st_C_gnumacro
2324 and replace lines between %< and %> with its output, then:
2325 - remove the #if characterset check
2326 - make in_word_set static and not inline. */
2327 /*%<*/
2328 /* C code produced by gperf version 3.0.1 */
2329 /* Command-line: gperf -m 5 */
2330 /* Computed positions: -k'2-3' */
2332 struct C_stab_entry { const char *name; int c_ext; enum sym_type type; };
2333 /* maximum key range = 33, duplicates = 0 */
2335 static inline unsigned int
2336 hash (register const char *str, register unsigned int len)
2338 static unsigned char asso_values[] =
2340 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2341 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2342 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2343 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2344 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2345 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2346 35, 35, 35, 35, 35, 35, 35, 35, 35, 3,
2347 26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2348 35, 35, 35, 24, 0, 35, 35, 35, 35, 0,
2349 35, 35, 35, 35, 35, 1, 35, 16, 35, 6,
2350 23, 0, 0, 35, 22, 0, 35, 35, 5, 0,
2351 0, 15, 1, 35, 6, 35, 8, 19, 35, 16,
2352 4, 5, 35, 35, 35, 35, 35, 35, 35, 35,
2353 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2354 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2355 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2356 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2357 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2358 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2359 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2360 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2361 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2362 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2363 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2364 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2365 35, 35, 35, 35, 35, 35
2367 register int hval = len;
2369 switch (hval)
2371 default:
2372 hval += asso_values[(unsigned char)str[2]];
2373 /*FALLTHROUGH*/
2374 case 2:
2375 hval += asso_values[(unsigned char)str[1]];
2376 break;
2378 return hval;
2381 static struct C_stab_entry *
2382 in_word_set (register const char *str, register unsigned int len)
2384 enum
2386 TOTAL_KEYWORDS = 33,
2387 MIN_WORD_LENGTH = 2,
2388 MAX_WORD_LENGTH = 15,
2389 MIN_HASH_VALUE = 2,
2390 MAX_HASH_VALUE = 34
2393 static struct C_stab_entry wordlist[] =
2395 {""}, {""},
2396 {"if", 0, st_C_ignore},
2397 {"GTY", 0, st_C_attribute},
2398 {"@end", 0, st_C_objend},
2399 {"union", 0, st_C_struct},
2400 {"define", 0, st_C_define},
2401 {"import", (C_JAVA & ~C_PLPL), st_C_ignore},
2402 {"template", 0, st_C_template},
2403 {"operator", C_PLPL, st_C_operator},
2404 {"@interface", 0, st_C_objprot},
2405 {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct},
2406 {"friend", C_PLPL, st_C_ignore},
2407 {"typedef", 0, st_C_typedef},
2408 {"return", 0, st_C_ignore},
2409 {"@implementation",0, st_C_objimpl},
2410 {"@protocol", 0, st_C_objprot},
2411 {"interface", (C_JAVA & ~C_PLPL), st_C_struct},
2412 {"extern", 0, st_C_extern},
2413 {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct},
2414 {"struct", 0, st_C_struct},
2415 {"domain", C_STAR, st_C_struct},
2416 {"switch", 0, st_C_ignore},
2417 {"enum", 0, st_C_enum},
2418 {"for", 0, st_C_ignore},
2419 {"namespace", C_PLPL, st_C_struct},
2420 {"class", 0, st_C_class},
2421 {"while", 0, st_C_ignore},
2422 {"undef", 0, st_C_define},
2423 {"package", (C_JAVA & ~C_PLPL), st_C_ignore},
2424 {"__attribute__", 0, st_C_attribute},
2425 {"SYSCALL", 0, st_C_gnumacro},
2426 {"ENTRY", 0, st_C_gnumacro},
2427 {"PSEUDO", 0, st_C_gnumacro},
2428 {"DEFUN", 0, st_C_gnumacro}
2431 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2433 register int key = hash (str, len);
2435 if (key <= MAX_HASH_VALUE && key >= 0)
2437 register const char *s = wordlist[key].name;
2439 if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2440 return &wordlist[key];
2443 return 0;
2445 /*%>*/
2447 static enum sym_type
2448 C_symtype (char *str, int len, int c_ext)
2450 register struct C_stab_entry *se = in_word_set (str, len);
2452 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2453 return st_none;
2454 return se->type;
2459 * Ignoring __attribute__ ((list))
2461 static bool inattribute; /* looking at an __attribute__ construct */
2464 * C functions and variables are recognized using a simple
2465 * finite automaton. fvdef is its state variable.
2467 static enum
2469 fvnone, /* nothing seen */
2470 fdefunkey, /* Emacs DEFUN keyword seen */
2471 fdefunname, /* Emacs DEFUN name seen */
2472 foperator, /* func: operator keyword seen (cplpl) */
2473 fvnameseen, /* function or variable name seen */
2474 fstartlist, /* func: just after open parenthesis */
2475 finlist, /* func: in parameter list */
2476 flistseen, /* func: after parameter list */
2477 fignore, /* func: before open brace */
2478 vignore /* var-like: ignore until ';' */
2479 } fvdef;
2481 static bool fvextern; /* func or var: extern keyword seen; */
2484 * typedefs are recognized using a simple finite automaton.
2485 * typdef is its state variable.
2487 static enum
2489 tnone, /* nothing seen */
2490 tkeyseen, /* typedef keyword seen */
2491 ttypeseen, /* defined type seen */
2492 tinbody, /* inside typedef body */
2493 tend, /* just before typedef tag */
2494 tignore /* junk after typedef tag */
2495 } typdef;
2498 * struct-like structures (enum, struct and union) are recognized
2499 * using another simple finite automaton. `structdef' is its state
2500 * variable.
2502 static enum
2504 snone, /* nothing seen yet,
2505 or in struct body if bracelev > 0 */
2506 skeyseen, /* struct-like keyword seen */
2507 stagseen, /* struct-like tag seen */
2508 scolonseen /* colon seen after struct-like tag */
2509 } structdef;
2512 * When objdef is different from onone, objtag is the name of the class.
2514 static const char *objtag = "<uninited>";
2517 * Yet another little state machine to deal with preprocessor lines.
2519 static enum
2521 dnone, /* nothing seen */
2522 dsharpseen, /* '#' seen as first char on line */
2523 ddefineseen, /* '#' and 'define' seen */
2524 dignorerest /* ignore rest of line */
2525 } definedef;
2528 * State machine for Objective C protocols and implementations.
2529 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2531 static enum
2533 onone, /* nothing seen */
2534 oprotocol, /* @interface or @protocol seen */
2535 oimplementation, /* @implementations seen */
2536 otagseen, /* class name seen */
2537 oparenseen, /* parenthesis before category seen */
2538 ocatseen, /* category name seen */
2539 oinbody, /* in @implementation body */
2540 omethodsign, /* in @implementation body, after +/- */
2541 omethodtag, /* after method name */
2542 omethodcolon, /* after method colon */
2543 omethodparm, /* after method parameter */
2544 oignore /* wait for @end */
2545 } objdef;
2549 * Use this structure to keep info about the token read, and how it
2550 * should be tagged. Used by the make_C_tag function to build a tag.
2552 static struct tok
2554 char *line; /* string containing the token */
2555 int offset; /* where the token starts in LINE */
2556 int length; /* token length */
2558 The previous members can be used to pass strings around for generic
2559 purposes. The following ones specifically refer to creating tags. In this
2560 case the token contained here is the pattern that will be used to create a
2561 tag.
2563 bool valid; /* do not create a tag; the token should be
2564 invalidated whenever a state machine is
2565 reset prematurely */
2566 bool named; /* create a named tag */
2567 int lineno; /* source line number of tag */
2568 long linepos; /* source char number of tag */
2569 } token; /* latest token read */
2572 * Variables and functions for dealing with nested structures.
2573 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2575 static void pushclass_above (int, char *, int);
2576 static void popclass_above (int);
2577 static void write_classname (linebuffer *, const char *qualifier);
2579 static struct {
2580 char **cname; /* nested class names */
2581 int *bracelev; /* nested class brace level */
2582 int nl; /* class nesting level (elements used) */
2583 int size; /* length of the array */
2584 } cstack; /* stack for nested declaration tags */
2585 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2586 #define nestlev (cstack.nl)
2587 /* After struct keyword or in struct body, not inside a nested function. */
2588 #define instruct (structdef == snone && nestlev > 0 \
2589 && bracelev == cstack.bracelev[nestlev-1] + 1)
2591 static void
2592 pushclass_above (int bracelev, char *str, int len)
2594 int nl;
2596 popclass_above (bracelev);
2597 nl = cstack.nl;
2598 if (nl >= cstack.size)
2600 int size = cstack.size *= 2;
2601 xrnew (cstack.cname, size, char *);
2602 xrnew (cstack.bracelev, size, int);
2604 assert (nl == 0 || cstack.bracelev[nl-1] < bracelev);
2605 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2606 cstack.bracelev[nl] = bracelev;
2607 cstack.nl = nl + 1;
2610 static void
2611 popclass_above (int bracelev)
2613 int nl;
2615 for (nl = cstack.nl - 1;
2616 nl >= 0 && cstack.bracelev[nl] >= bracelev;
2617 nl--)
2619 free (cstack.cname[nl]);
2620 cstack.nl = nl;
2624 static void
2625 write_classname (linebuffer *cn, const char *qualifier)
2627 int i, len;
2628 int qlen = strlen (qualifier);
2630 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2632 len = 0;
2633 cn->len = 0;
2634 cn->buffer[0] = '\0';
2636 else
2638 len = strlen (cstack.cname[0]);
2639 linebuffer_setlen (cn, len);
2640 strcpy (cn->buffer, cstack.cname[0]);
2642 for (i = 1; i < cstack.nl; i++)
2644 char *s = cstack.cname[i];
2645 if (s == NULL)
2646 continue;
2647 linebuffer_setlen (cn, len + qlen + strlen (s));
2648 len += sprintf (cn->buffer + len, "%s%s", qualifier, s);
2653 static bool consider_token (char *, int, int, int *, int, int, bool *);
2654 static void make_C_tag (bool);
2657 * consider_token ()
2658 * checks to see if the current token is at the start of a
2659 * function or variable, or corresponds to a typedef, or
2660 * is a struct/union/enum tag, or #define, or an enum constant.
2662 * *IS_FUNC gets TRUE if the token is a function or #define macro
2663 * with args. C_EXTP points to which language we are looking at.
2665 * Globals
2666 * fvdef IN OUT
2667 * structdef IN OUT
2668 * definedef IN OUT
2669 * typdef IN OUT
2670 * objdef IN OUT
2673 static bool
2674 consider_token (register char *str, register int len, register int c, int *c_extp, int bracelev, int parlev, int *is_func_or_var)
2675 /* IN: token pointer */
2676 /* IN: token length */
2677 /* IN: first char after the token */
2678 /* IN, OUT: C extensions mask */
2679 /* IN: brace level */
2680 /* IN: parenthesis level */
2681 /* OUT: function or variable found */
2683 /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2684 structtype is the type of the preceding struct-like keyword, and
2685 structbracelev is the brace level where it has been seen. */
2686 static enum sym_type structtype;
2687 static int structbracelev;
2688 static enum sym_type toktype;
2691 toktype = C_symtype (str, len, *c_extp);
2694 * Skip __attribute__
2696 if (toktype == st_C_attribute)
2698 inattribute = TRUE;
2699 return FALSE;
2703 * Advance the definedef state machine.
2705 switch (definedef)
2707 case dnone:
2708 /* We're not on a preprocessor line. */
2709 if (toktype == st_C_gnumacro)
2711 fvdef = fdefunkey;
2712 return FALSE;
2714 break;
2715 case dsharpseen:
2716 if (toktype == st_C_define)
2718 definedef = ddefineseen;
2720 else
2722 definedef = dignorerest;
2724 return FALSE;
2725 case ddefineseen:
2727 * Make a tag for any macro, unless it is a constant
2728 * and constantypedefs is FALSE.
2730 definedef = dignorerest;
2731 *is_func_or_var = (c == '(');
2732 if (!*is_func_or_var && !constantypedefs)
2733 return FALSE;
2734 else
2735 return TRUE;
2736 case dignorerest:
2737 return FALSE;
2738 default:
2739 error ("internal error: definedef value.");
2743 * Now typedefs
2745 switch (typdef)
2747 case tnone:
2748 if (toktype == st_C_typedef)
2750 if (typedefs)
2751 typdef = tkeyseen;
2752 fvextern = FALSE;
2753 fvdef = fvnone;
2754 return FALSE;
2756 break;
2757 case tkeyseen:
2758 switch (toktype)
2760 case st_none:
2761 case st_C_class:
2762 case st_C_struct:
2763 case st_C_enum:
2764 typdef = ttypeseen;
2766 break;
2767 case ttypeseen:
2768 if (structdef == snone && fvdef == fvnone)
2770 fvdef = fvnameseen;
2771 return TRUE;
2773 break;
2774 case tend:
2775 switch (toktype)
2777 case st_C_class:
2778 case st_C_struct:
2779 case st_C_enum:
2780 return FALSE;
2782 return TRUE;
2785 switch (toktype)
2787 case st_C_javastruct:
2788 if (structdef == stagseen)
2789 structdef = scolonseen;
2790 return FALSE;
2791 case st_C_template:
2792 case st_C_class:
2793 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2794 && bracelev == 0
2795 && definedef == dnone && structdef == snone
2796 && typdef == tnone && fvdef == fvnone)
2797 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2798 if (toktype == st_C_template)
2799 break;
2800 /* FALLTHRU */
2801 case st_C_struct:
2802 case st_C_enum:
2803 if (parlev == 0
2804 && fvdef != vignore
2805 && (typdef == tkeyseen
2806 || (typedefs_or_cplusplus && structdef == snone)))
2808 structdef = skeyseen;
2809 structtype = toktype;
2810 structbracelev = bracelev;
2811 if (fvdef == fvnameseen)
2812 fvdef = fvnone;
2814 return FALSE;
2817 if (structdef == skeyseen)
2819 structdef = stagseen;
2820 return TRUE;
2823 if (typdef != tnone)
2824 definedef = dnone;
2826 /* Detect Objective C constructs. */
2827 switch (objdef)
2829 case onone:
2830 switch (toktype)
2832 case st_C_objprot:
2833 objdef = oprotocol;
2834 return FALSE;
2835 case st_C_objimpl:
2836 objdef = oimplementation;
2837 return FALSE;
2839 break;
2840 case oimplementation:
2841 /* Save the class tag for functions or variables defined inside. */
2842 objtag = savenstr (str, len);
2843 objdef = oinbody;
2844 return FALSE;
2845 case oprotocol:
2846 /* Save the class tag for categories. */
2847 objtag = savenstr (str, len);
2848 objdef = otagseen;
2849 *is_func_or_var = TRUE;
2850 return TRUE;
2851 case oparenseen:
2852 objdef = ocatseen;
2853 *is_func_or_var = TRUE;
2854 return TRUE;
2855 case oinbody:
2856 break;
2857 case omethodsign:
2858 if (parlev == 0)
2860 fvdef = fvnone;
2861 objdef = omethodtag;
2862 linebuffer_setlen (&token_name, len);
2863 memcpy (token_name.buffer, str, len);
2864 token_name.buffer[len] = '\0';
2865 return TRUE;
2867 return FALSE;
2868 case omethodcolon:
2869 if (parlev == 0)
2870 objdef = omethodparm;
2871 return FALSE;
2872 case omethodparm:
2873 if (parlev == 0)
2875 int oldlen = token_name.len;
2876 fvdef = fvnone;
2877 objdef = omethodtag;
2878 linebuffer_setlen (&token_name, oldlen + len);
2879 memcpy (token_name.buffer + oldlen, str, len);
2880 token_name.buffer[oldlen + len] = '\0';
2881 return TRUE;
2883 return FALSE;
2884 case oignore:
2885 if (toktype == st_C_objend)
2887 /* Memory leakage here: the string pointed by objtag is
2888 never released, because many tests would be needed to
2889 avoid breaking on incorrect input code. The amount of
2890 memory leaked here is the sum of the lengths of the
2891 class tags.
2892 free (objtag); */
2893 objdef = onone;
2895 return FALSE;
2898 /* A function, variable or enum constant? */
2899 switch (toktype)
2901 case st_C_extern:
2902 fvextern = TRUE;
2903 switch (fvdef)
2905 case finlist:
2906 case flistseen:
2907 case fignore:
2908 case vignore:
2909 break;
2910 default:
2911 fvdef = fvnone;
2913 return FALSE;
2914 case st_C_ignore:
2915 fvextern = FALSE;
2916 fvdef = vignore;
2917 return FALSE;
2918 case st_C_operator:
2919 fvdef = foperator;
2920 *is_func_or_var = TRUE;
2921 return TRUE;
2922 case st_none:
2923 if (constantypedefs
2924 && structdef == snone
2925 && structtype == st_C_enum && bracelev > structbracelev)
2926 return TRUE; /* enum constant */
2927 switch (fvdef)
2929 case fdefunkey:
2930 if (bracelev > 0)
2931 break;
2932 fvdef = fdefunname; /* GNU macro */
2933 *is_func_or_var = TRUE;
2934 return TRUE;
2935 case fvnone:
2936 switch (typdef)
2938 case ttypeseen:
2939 return FALSE;
2940 case tnone:
2941 if ((strneq (str, "asm", 3) && endtoken (str[3]))
2942 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
2944 fvdef = vignore;
2945 return FALSE;
2947 break;
2949 /* FALLTHRU */
2950 case fvnameseen:
2951 if (len >= 10 && strneq (str+len-10, "::operator", 10))
2953 if (*c_extp & C_AUTO) /* automatic detection of C++ */
2954 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2955 fvdef = foperator;
2956 *is_func_or_var = TRUE;
2957 return TRUE;
2959 if (bracelev > 0 && !instruct)
2960 break;
2961 fvdef = fvnameseen; /* function or variable */
2962 *is_func_or_var = TRUE;
2963 return TRUE;
2965 break;
2968 return FALSE;
2973 * C_entries often keeps pointers to tokens or lines which are older than
2974 * the line currently read. By keeping two line buffers, and switching
2975 * them at end of line, it is possible to use those pointers.
2977 static struct
2979 long linepos;
2980 linebuffer lb;
2981 } lbs[2];
2983 #define current_lb_is_new (newndx == curndx)
2984 #define switch_line_buffers() (curndx = 1 - curndx)
2986 #define curlb (lbs[curndx].lb)
2987 #define newlb (lbs[newndx].lb)
2988 #define curlinepos (lbs[curndx].linepos)
2989 #define newlinepos (lbs[newndx].linepos)
2991 #define plainc ((c_ext & C_EXT) == C_PLAIN)
2992 #define cplpl (c_ext & C_PLPL)
2993 #define cjava ((c_ext & C_JAVA) == C_JAVA)
2995 #define CNL_SAVE_DEFINEDEF() \
2996 do { \
2997 curlinepos = charno; \
2998 readline (&curlb, inf); \
2999 lp = curlb.buffer; \
3000 quotednl = FALSE; \
3001 newndx = curndx; \
3002 } while (0)
3004 #define CNL() \
3005 do { \
3006 CNL_SAVE_DEFINEDEF(); \
3007 if (savetoken.valid) \
3009 token = savetoken; \
3010 savetoken.valid = FALSE; \
3012 definedef = dnone; \
3013 } while (0)
3016 static void
3017 make_C_tag (int isfun)
3019 /* This function is never called when token.valid is FALSE, but
3020 we must protect against invalid input or internal errors. */
3021 if (token.valid)
3022 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3023 token.offset+token.length+1, token.lineno, token.linepos);
3024 else if (DEBUG)
3025 { /* this branch is optimized away if !DEBUG */
3026 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3027 token_name.len + 17, isfun, token.line,
3028 token.offset+token.length+1, token.lineno, token.linepos);
3029 error ("INVALID TOKEN");
3032 token.valid = FALSE;
3037 * C_entries ()
3038 * This routine finds functions, variables, typedefs,
3039 * #define's, enum constants and struct/union/enum definitions in
3040 * C syntax and adds them to the list.
3042 static void
3043 C_entries (int c_ext, FILE *inf)
3044 /* extension of C */
3045 /* input file */
3047 register char c; /* latest char read; '\0' for end of line */
3048 register char *lp; /* pointer one beyond the character `c' */
3049 int curndx, newndx; /* indices for current and new lb */
3050 register int tokoff; /* offset in line of start of current token */
3051 register int toklen; /* length of current token */
3052 const char *qualifier; /* string used to qualify names */
3053 int qlen; /* length of qualifier */
3054 int bracelev; /* current brace level */
3055 int bracketlev; /* current bracket level */
3056 int parlev; /* current parenthesis level */
3057 int attrparlev; /* __attribute__ parenthesis level */
3058 int templatelev; /* current template level */
3059 int typdefbracelev; /* bracelev where a typedef struct body begun */
3060 bool incomm, inquote, inchar, quotednl, midtoken;
3061 bool yacc_rules; /* in the rules part of a yacc file */
3062 struct tok savetoken = {0}; /* token saved during preprocessor handling */
3065 linebuffer_init (&lbs[0].lb);
3066 linebuffer_init (&lbs[1].lb);
3067 if (cstack.size == 0)
3069 cstack.size = (DEBUG) ? 1 : 4;
3070 cstack.nl = 0;
3071 cstack.cname = xnew (cstack.size, char *);
3072 cstack.bracelev = xnew (cstack.size, int);
3075 tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3076 curndx = newndx = 0;
3077 lp = curlb.buffer;
3078 *lp = 0;
3080 fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3081 structdef = snone; definedef = dnone; objdef = onone;
3082 yacc_rules = FALSE;
3083 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3084 token.valid = savetoken.valid = FALSE;
3085 bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3086 if (cjava)
3087 { qualifier = "."; qlen = 1; }
3088 else
3089 { qualifier = "::"; qlen = 2; }
3092 while (!feof (inf))
3094 c = *lp++;
3095 if (c == '\\')
3097 /* If we are at the end of the line, the next character is a
3098 '\0'; do not skip it, because it is what tells us
3099 to read the next line. */
3100 if (*lp == '\0')
3102 quotednl = TRUE;
3103 continue;
3105 lp++;
3106 c = ' ';
3108 else if (incomm)
3110 switch (c)
3112 case '*':
3113 if (*lp == '/')
3115 c = *lp++;
3116 incomm = FALSE;
3118 break;
3119 case '\0':
3120 /* Newlines inside comments do not end macro definitions in
3121 traditional cpp. */
3122 CNL_SAVE_DEFINEDEF ();
3123 break;
3125 continue;
3127 else if (inquote)
3129 switch (c)
3131 case '"':
3132 inquote = FALSE;
3133 break;
3134 case '\0':
3135 /* Newlines inside strings do not end macro definitions
3136 in traditional cpp, even though compilers don't
3137 usually accept them. */
3138 CNL_SAVE_DEFINEDEF ();
3139 break;
3141 continue;
3143 else if (inchar)
3145 switch (c)
3147 case '\0':
3148 /* Hmmm, something went wrong. */
3149 CNL ();
3150 /* FALLTHRU */
3151 case '\'':
3152 inchar = FALSE;
3153 break;
3155 continue;
3157 else switch (c)
3159 case '"':
3160 inquote = TRUE;
3161 if (bracketlev > 0)
3162 continue;
3163 if (inattribute)
3164 break;
3165 switch (fvdef)
3167 case fdefunkey:
3168 case fstartlist:
3169 case finlist:
3170 case fignore:
3171 case vignore:
3172 break;
3173 default:
3174 fvextern = FALSE;
3175 fvdef = fvnone;
3177 continue;
3178 case '\'':
3179 inchar = TRUE;
3180 if (bracketlev > 0)
3181 continue;
3182 if (inattribute)
3183 break;
3184 if (fvdef != finlist && fvdef != fignore && fvdef != vignore)
3186 fvextern = FALSE;
3187 fvdef = fvnone;
3189 continue;
3190 case '/':
3191 if (*lp == '*')
3193 incomm = TRUE;
3194 lp++;
3195 c = ' ';
3196 if (bracketlev > 0)
3197 continue;
3199 else if (/* cplpl && */ *lp == '/')
3201 c = '\0';
3203 break;
3204 case '%':
3205 if ((c_ext & YACC) && *lp == '%')
3207 /* Entering or exiting rules section in yacc file. */
3208 lp++;
3209 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3210 typdef = tnone; structdef = snone;
3211 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3212 bracelev = 0;
3213 yacc_rules = !yacc_rules;
3214 continue;
3216 else
3217 break;
3218 case '#':
3219 if (definedef == dnone)
3221 char *cp;
3222 bool cpptoken = TRUE;
3224 /* Look back on this line. If all blanks, or nonblanks
3225 followed by an end of comment, this is a preprocessor
3226 token. */
3227 for (cp = newlb.buffer; cp < lp-1; cp++)
3228 if (!iswhite (*cp))
3230 if (*cp == '*' && cp[1] == '/')
3232 cp++;
3233 cpptoken = TRUE;
3235 else
3236 cpptoken = FALSE;
3238 if (cpptoken)
3239 definedef = dsharpseen;
3240 } /* if (definedef == dnone) */
3241 continue;
3242 case '[':
3243 bracketlev++;
3244 continue;
3245 default:
3246 if (bracketlev > 0)
3248 if (c == ']')
3249 --bracketlev;
3250 else if (c == '\0')
3251 CNL_SAVE_DEFINEDEF ();
3252 continue;
3254 break;
3255 } /* switch (c) */
3258 /* Consider token only if some involved conditions are satisfied. */
3259 if (typdef != tignore
3260 && definedef != dignorerest
3261 && fvdef != finlist
3262 && templatelev == 0
3263 && (definedef != dnone
3264 || structdef != scolonseen)
3265 && !inattribute)
3267 if (midtoken)
3269 if (endtoken (c))
3271 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3272 /* This handles :: in the middle,
3273 but not at the beginning of an identifier.
3274 Also, space-separated :: is not recognized. */
3276 if (c_ext & C_AUTO) /* automatic detection of C++ */
3277 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3278 lp += 2;
3279 toklen += 2;
3280 c = lp[-1];
3281 goto still_in_token;
3283 else
3285 bool funorvar = FALSE;
3287 if (yacc_rules
3288 || consider_token (newlb.buffer + tokoff, toklen, c,
3289 &c_ext, bracelev, parlev,
3290 &funorvar))
3292 if (fvdef == foperator)
3294 char *oldlp = lp;
3295 lp = skip_spaces (lp-1);
3296 if (*lp != '\0')
3297 lp += 1;
3298 while (*lp != '\0'
3299 && !iswhite (*lp) && *lp != '(')
3300 lp += 1;
3301 c = *lp++;
3302 toklen += lp - oldlp;
3304 token.named = FALSE;
3305 if (!plainc
3306 && nestlev > 0 && definedef == dnone)
3307 /* in struct body */
3309 int len;
3310 write_classname (&token_name, qualifier);
3311 len = token_name.len;
3312 linebuffer_setlen (&token_name, len+qlen+toklen);
3313 sprintf (token_name.buffer + len, "%s%.*s",
3314 qualifier, toklen, newlb.buffer + tokoff);
3315 token.named = TRUE;
3317 else if (objdef == ocatseen)
3318 /* Objective C category */
3320 int len = strlen (objtag) + 2 + toklen;
3321 linebuffer_setlen (&token_name, len);
3322 sprintf (token_name.buffer, "%s(%.*s)",
3323 objtag, toklen, newlb.buffer + tokoff);
3324 token.named = TRUE;
3326 else if (objdef == omethodtag
3327 || objdef == omethodparm)
3328 /* Objective C method */
3330 token.named = TRUE;
3332 else if (fvdef == fdefunname)
3333 /* GNU DEFUN and similar macros */
3335 bool defun = (newlb.buffer[tokoff] == 'F');
3336 int off = tokoff;
3337 int len = toklen;
3339 /* Rewrite the tag so that emacs lisp DEFUNs
3340 can be found by their elisp name */
3341 if (defun)
3343 off += 1;
3344 len -= 1;
3346 linebuffer_setlen (&token_name, len);
3347 memcpy (token_name.buffer,
3348 newlb.buffer + off, len);
3349 token_name.buffer[len] = '\0';
3350 if (defun)
3351 while (--len >= 0)
3352 if (token_name.buffer[len] == '_')
3353 token_name.buffer[len] = '-';
3354 token.named = defun;
3356 else
3358 linebuffer_setlen (&token_name, toklen);
3359 memcpy (token_name.buffer,
3360 newlb.buffer + tokoff, toklen);
3361 token_name.buffer[toklen] = '\0';
3362 /* Name macros and members. */
3363 token.named = (structdef == stagseen
3364 || typdef == ttypeseen
3365 || typdef == tend
3366 || (funorvar
3367 && definedef == dignorerest)
3368 || (funorvar
3369 && definedef == dnone
3370 && structdef == snone
3371 && bracelev > 0));
3373 token.lineno = lineno;
3374 token.offset = tokoff;
3375 token.length = toklen;
3376 token.line = newlb.buffer;
3377 token.linepos = newlinepos;
3378 token.valid = TRUE;
3380 if (definedef == dnone
3381 && (fvdef == fvnameseen
3382 || fvdef == foperator
3383 || structdef == stagseen
3384 || typdef == tend
3385 || typdef == ttypeseen
3386 || objdef != onone))
3388 if (current_lb_is_new)
3389 switch_line_buffers ();
3391 else if (definedef != dnone
3392 || fvdef == fdefunname
3393 || instruct)
3394 make_C_tag (funorvar);
3396 else /* not yacc and consider_token failed */
3398 if (inattribute && fvdef == fignore)
3400 /* We have just met __attribute__ after a
3401 function parameter list: do not tag the
3402 function again. */
3403 fvdef = fvnone;
3406 midtoken = FALSE;
3408 } /* if (endtoken (c)) */
3409 else if (intoken (c))
3410 still_in_token:
3412 toklen++;
3413 continue;
3415 } /* if (midtoken) */
3416 else if (begtoken (c))
3418 switch (definedef)
3420 case dnone:
3421 switch (fvdef)
3423 case fstartlist:
3424 /* This prevents tagging fb in
3425 void (__attribute__((noreturn)) *fb) (void);
3426 Fixing this is not easy and not very important. */
3427 fvdef = finlist;
3428 continue;
3429 case flistseen:
3430 if (plainc || declarations)
3432 make_C_tag (TRUE); /* a function */
3433 fvdef = fignore;
3435 break;
3437 if (structdef == stagseen && !cjava)
3439 popclass_above (bracelev);
3440 structdef = snone;
3442 break;
3443 case dsharpseen:
3444 savetoken = token;
3445 break;
3447 if (!yacc_rules || lp == newlb.buffer + 1)
3449 tokoff = lp - 1 - newlb.buffer;
3450 toklen = 1;
3451 midtoken = TRUE;
3453 continue;
3454 } /* if (begtoken) */
3455 } /* if must look at token */
3458 /* Detect end of line, colon, comma, semicolon and various braces
3459 after having handled a token.*/
3460 switch (c)
3462 case ':':
3463 if (inattribute)
3464 break;
3465 if (yacc_rules && token.offset == 0 && token.valid)
3467 make_C_tag (FALSE); /* a yacc function */
3468 break;
3470 if (definedef != dnone)
3471 break;
3472 switch (objdef)
3474 case otagseen:
3475 objdef = oignore;
3476 make_C_tag (TRUE); /* an Objective C class */
3477 break;
3478 case omethodtag:
3479 case omethodparm:
3480 objdef = omethodcolon;
3481 linebuffer_setlen (&token_name, token_name.len + 1);
3482 strcat (token_name.buffer, ":");
3483 break;
3485 if (structdef == stagseen)
3487 structdef = scolonseen;
3488 break;
3490 /* Should be useless, but may be work as a safety net. */
3491 if (cplpl && fvdef == flistseen)
3493 make_C_tag (TRUE); /* a function */
3494 fvdef = fignore;
3495 break;
3497 break;
3498 case ';':
3499 if (definedef != dnone || inattribute)
3500 break;
3501 switch (typdef)
3503 case tend:
3504 case ttypeseen:
3505 make_C_tag (FALSE); /* a typedef */
3506 typdef = tnone;
3507 fvdef = fvnone;
3508 break;
3509 case tnone:
3510 case tinbody:
3511 case tignore:
3512 switch (fvdef)
3514 case fignore:
3515 if (typdef == tignore || cplpl)
3516 fvdef = fvnone;
3517 break;
3518 case fvnameseen:
3519 if ((globals && bracelev == 0 && (!fvextern || declarations))
3520 || (members && instruct))
3521 make_C_tag (FALSE); /* a variable */
3522 fvextern = FALSE;
3523 fvdef = fvnone;
3524 token.valid = FALSE;
3525 break;
3526 case flistseen:
3527 if ((declarations
3528 && (cplpl || !instruct)
3529 && (typdef == tnone || (typdef != tignore && instruct)))
3530 || (members
3531 && plainc && instruct))
3532 make_C_tag (TRUE); /* a function */
3533 /* FALLTHRU */
3534 default:
3535 fvextern = FALSE;
3536 fvdef = fvnone;
3537 if (declarations
3538 && cplpl && structdef == stagseen)
3539 make_C_tag (FALSE); /* forward declaration */
3540 else
3541 token.valid = FALSE;
3542 } /* switch (fvdef) */
3543 /* FALLTHRU */
3544 default:
3545 if (!instruct)
3546 typdef = tnone;
3548 if (structdef == stagseen)
3549 structdef = snone;
3550 break;
3551 case ',':
3552 if (definedef != dnone || inattribute)
3553 break;
3554 switch (objdef)
3556 case omethodtag:
3557 case omethodparm:
3558 make_C_tag (TRUE); /* an Objective C method */
3559 objdef = oinbody;
3560 break;
3562 switch (fvdef)
3564 case fdefunkey:
3565 case foperator:
3566 case fstartlist:
3567 case finlist:
3568 case fignore:
3569 case vignore:
3570 break;
3571 case fdefunname:
3572 fvdef = fignore;
3573 break;
3574 case fvnameseen:
3575 if (parlev == 0
3576 && ((globals
3577 && bracelev == 0
3578 && templatelev == 0
3579 && (!fvextern || declarations))
3580 || (members && instruct)))
3581 make_C_tag (FALSE); /* a variable */
3582 break;
3583 case flistseen:
3584 if ((declarations && typdef == tnone && !instruct)
3585 || (members && typdef != tignore && instruct))
3587 make_C_tag (TRUE); /* a function */
3588 fvdef = fvnameseen;
3590 else if (!declarations)
3591 fvdef = fvnone;
3592 token.valid = FALSE;
3593 break;
3594 default:
3595 fvdef = fvnone;
3597 if (structdef == stagseen)
3598 structdef = snone;
3599 break;
3600 case ']':
3601 if (definedef != dnone || inattribute)
3602 break;
3603 if (structdef == stagseen)
3604 structdef = snone;
3605 switch (typdef)
3607 case ttypeseen:
3608 case tend:
3609 typdef = tignore;
3610 make_C_tag (FALSE); /* a typedef */
3611 break;
3612 case tnone:
3613 case tinbody:
3614 switch (fvdef)
3616 case foperator:
3617 case finlist:
3618 case fignore:
3619 case vignore:
3620 break;
3621 case fvnameseen:
3622 if ((members && bracelev == 1)
3623 || (globals && bracelev == 0
3624 && (!fvextern || declarations)))
3625 make_C_tag (FALSE); /* a variable */
3626 /* FALLTHRU */
3627 default:
3628 fvdef = fvnone;
3630 break;
3632 break;
3633 case '(':
3634 if (inattribute)
3636 attrparlev++;
3637 break;
3639 if (definedef != dnone)
3640 break;
3641 if (objdef == otagseen && parlev == 0)
3642 objdef = oparenseen;
3643 switch (fvdef)
3645 case fvnameseen:
3646 if (typdef == ttypeseen
3647 && *lp != '*'
3648 && !instruct)
3650 /* This handles constructs like:
3651 typedef void OperatorFun (int fun); */
3652 make_C_tag (FALSE);
3653 typdef = tignore;
3654 fvdef = fignore;
3655 break;
3657 /* FALLTHRU */
3658 case foperator:
3659 fvdef = fstartlist;
3660 break;
3661 case flistseen:
3662 fvdef = finlist;
3663 break;
3665 parlev++;
3666 break;
3667 case ')':
3668 if (inattribute)
3670 if (--attrparlev == 0)
3671 inattribute = FALSE;
3672 break;
3674 if (definedef != dnone)
3675 break;
3676 if (objdef == ocatseen && parlev == 1)
3678 make_C_tag (TRUE); /* an Objective C category */
3679 objdef = oignore;
3681 if (--parlev == 0)
3683 switch (fvdef)
3685 case fstartlist:
3686 case finlist:
3687 fvdef = flistseen;
3688 break;
3690 if (!instruct
3691 && (typdef == tend
3692 || typdef == ttypeseen))
3694 typdef = tignore;
3695 make_C_tag (FALSE); /* a typedef */
3698 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
3699 parlev = 0;
3700 break;
3701 case '{':
3702 if (definedef != dnone)
3703 break;
3704 if (typdef == ttypeseen)
3706 /* Whenever typdef is set to tinbody (currently only
3707 here), typdefbracelev should be set to bracelev. */
3708 typdef = tinbody;
3709 typdefbracelev = bracelev;
3711 switch (fvdef)
3713 case flistseen:
3714 make_C_tag (TRUE); /* a function */
3715 /* FALLTHRU */
3716 case fignore:
3717 fvdef = fvnone;
3718 break;
3719 case fvnone:
3720 switch (objdef)
3722 case otagseen:
3723 make_C_tag (TRUE); /* an Objective C class */
3724 objdef = oignore;
3725 break;
3726 case omethodtag:
3727 case omethodparm:
3728 make_C_tag (TRUE); /* an Objective C method */
3729 objdef = oinbody;
3730 break;
3731 default:
3732 /* Neutralize `extern "C" {' grot. */
3733 if (bracelev == 0 && structdef == snone && nestlev == 0
3734 && typdef == tnone)
3735 bracelev = -1;
3737 break;
3739 switch (structdef)
3741 case skeyseen: /* unnamed struct */
3742 pushclass_above (bracelev, NULL, 0);
3743 structdef = snone;
3744 break;
3745 case stagseen: /* named struct or enum */
3746 case scolonseen: /* a class */
3747 pushclass_above (bracelev,token.line+token.offset, token.length);
3748 structdef = snone;
3749 make_C_tag (FALSE); /* a struct or enum */
3750 break;
3752 bracelev += 1;
3753 break;
3754 case '*':
3755 if (definedef != dnone)
3756 break;
3757 if (fvdef == fstartlist)
3759 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
3760 token.valid = FALSE;
3762 break;
3763 case '}':
3764 if (definedef != dnone)
3765 break;
3766 bracelev -= 1;
3767 if (!ignoreindent && lp == newlb.buffer + 1)
3769 if (bracelev != 0)
3770 token.valid = FALSE; /* unexpected value, token unreliable */
3771 bracelev = 0; /* reset brace level if first column */
3772 parlev = 0; /* also reset paren level, just in case... */
3774 else if (bracelev < 0)
3776 token.valid = FALSE; /* something gone amiss, token unreliable */
3777 bracelev = 0;
3779 if (bracelev == 0 && fvdef == vignore)
3780 fvdef = fvnone; /* end of function */
3781 popclass_above (bracelev);
3782 structdef = snone;
3783 /* Only if typdef == tinbody is typdefbracelev significant. */
3784 if (typdef == tinbody && bracelev <= typdefbracelev)
3786 assert (bracelev == typdefbracelev);
3787 typdef = tend;
3789 break;
3790 case '=':
3791 if (definedef != dnone)
3792 break;
3793 switch (fvdef)
3795 case foperator:
3796 case finlist:
3797 case fignore:
3798 case vignore:
3799 break;
3800 case fvnameseen:
3801 if ((members && bracelev == 1)
3802 || (globals && bracelev == 0 && (!fvextern || declarations)))
3803 make_C_tag (FALSE); /* a variable */
3804 /* FALLTHRU */
3805 default:
3806 fvdef = vignore;
3808 break;
3809 case '<':
3810 if (cplpl
3811 && (structdef == stagseen || fvdef == fvnameseen))
3813 templatelev++;
3814 break;
3816 goto resetfvdef;
3817 case '>':
3818 if (templatelev > 0)
3820 templatelev--;
3821 break;
3823 goto resetfvdef;
3824 case '+':
3825 case '-':
3826 if (objdef == oinbody && bracelev == 0)
3828 objdef = omethodsign;
3829 break;
3831 /* FALLTHRU */
3832 resetfvdef:
3833 case '#': case '~': case '&': case '%': case '/':
3834 case '|': case '^': case '!': case '.': case '?':
3835 if (definedef != dnone)
3836 break;
3837 /* These surely cannot follow a function tag in C. */
3838 switch (fvdef)
3840 case foperator:
3841 case finlist:
3842 case fignore:
3843 case vignore:
3844 break;
3845 default:
3846 fvdef = fvnone;
3848 break;
3849 case '\0':
3850 if (objdef == otagseen)
3852 make_C_tag (TRUE); /* an Objective C class */
3853 objdef = oignore;
3855 /* If a macro spans multiple lines don't reset its state. */
3856 if (quotednl)
3857 CNL_SAVE_DEFINEDEF ();
3858 else
3859 CNL ();
3860 break;
3861 } /* switch (c) */
3863 } /* while not eof */
3865 free (lbs[0].lb.buffer);
3866 free (lbs[1].lb.buffer);
3870 * Process either a C++ file or a C file depending on the setting
3871 * of a global flag.
3873 static void
3874 default_C_entries (FILE *inf)
3876 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
3879 /* Always do plain C. */
3880 static void
3881 plain_C_entries (FILE *inf)
3883 C_entries (0, inf);
3886 /* Always do C++. */
3887 static void
3888 Cplusplus_entries (FILE *inf)
3890 C_entries (C_PLPL, inf);
3893 /* Always do Java. */
3894 static void
3895 Cjava_entries (FILE *inf)
3897 C_entries (C_JAVA, inf);
3900 /* Always do C*. */
3901 static void
3902 Cstar_entries (FILE *inf)
3904 C_entries (C_STAR, inf);
3907 /* Always do Yacc. */
3908 static void
3909 Yacc_entries (FILE *inf)
3911 C_entries (YACC, inf);
3915 /* Useful macros. */
3916 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
3917 for (; /* loop initialization */ \
3918 !feof (file_pointer) /* loop test */ \
3919 && /* instructions at start of loop */ \
3920 (readline (&line_buffer, file_pointer), \
3921 char_pointer = line_buffer.buffer, \
3922 TRUE); \
3925 #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \
3926 ((assert ("" kw), TRUE) /* syntax error if not a literal string */ \
3927 && strneq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3928 && notinname ((cp)[sizeof (kw)-1]) /* end of kw */ \
3929 && ((cp) = skip_spaces ((cp)+sizeof (kw)-1))) /* skip spaces */
3931 /* Similar to LOOKING_AT but does not use notinname, does not skip */
3932 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
3933 ((assert ("" kw), TRUE) /* syntax error if not a literal string */ \
3934 && strncaseeq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \
3935 && ((cp) += sizeof (kw)-1)) /* skip spaces */
3938 * Read a file, but do no processing. This is used to do regexp
3939 * matching on files that have no language defined.
3941 static void
3942 just_read_file (FILE *inf)
3944 while (!feof (inf))
3945 readline (&lb, inf);
3949 /* Fortran parsing */
3951 static void F_takeprec (void);
3952 static void F_getit (FILE *);
3954 static void
3955 F_takeprec (void)
3957 dbp = skip_spaces (dbp);
3958 if (*dbp != '*')
3959 return;
3960 dbp++;
3961 dbp = skip_spaces (dbp);
3962 if (strneq (dbp, "(*)", 3))
3964 dbp += 3;
3965 return;
3967 if (!ISDIGIT (*dbp))
3969 --dbp; /* force failure */
3970 return;
3973 dbp++;
3974 while (ISDIGIT (*dbp));
3977 static void
3978 F_getit (FILE *inf)
3980 register char *cp;
3982 dbp = skip_spaces (dbp);
3983 if (*dbp == '\0')
3985 readline (&lb, inf);
3986 dbp = lb.buffer;
3987 if (dbp[5] != '&')
3988 return;
3989 dbp += 6;
3990 dbp = skip_spaces (dbp);
3992 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
3993 return;
3994 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
3995 continue;
3996 make_tag (dbp, cp-dbp, TRUE,
3997 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4001 static void
4002 Fortran_functions (FILE *inf)
4004 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4006 if (*dbp == '%')
4007 dbp++; /* Ratfor escape to fortran */
4008 dbp = skip_spaces (dbp);
4009 if (*dbp == '\0')
4010 continue;
4012 if (LOOKING_AT_NOCASE (dbp, "recursive"))
4013 dbp = skip_spaces (dbp);
4015 if (LOOKING_AT_NOCASE (dbp, "pure"))
4016 dbp = skip_spaces (dbp);
4018 if (LOOKING_AT_NOCASE (dbp, "elemental"))
4019 dbp = skip_spaces (dbp);
4021 switch (lowcase (*dbp))
4023 case 'i':
4024 if (nocase_tail ("integer"))
4025 F_takeprec ();
4026 break;
4027 case 'r':
4028 if (nocase_tail ("real"))
4029 F_takeprec ();
4030 break;
4031 case 'l':
4032 if (nocase_tail ("logical"))
4033 F_takeprec ();
4034 break;
4035 case 'c':
4036 if (nocase_tail ("complex") || nocase_tail ("character"))
4037 F_takeprec ();
4038 break;
4039 case 'd':
4040 if (nocase_tail ("double"))
4042 dbp = skip_spaces (dbp);
4043 if (*dbp == '\0')
4044 continue;
4045 if (nocase_tail ("precision"))
4046 break;
4047 continue;
4049 break;
4051 dbp = skip_spaces (dbp);
4052 if (*dbp == '\0')
4053 continue;
4054 switch (lowcase (*dbp))
4056 case 'f':
4057 if (nocase_tail ("function"))
4058 F_getit (inf);
4059 continue;
4060 case 's':
4061 if (nocase_tail ("subroutine"))
4062 F_getit (inf);
4063 continue;
4064 case 'e':
4065 if (nocase_tail ("entry"))
4066 F_getit (inf);
4067 continue;
4068 case 'b':
4069 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4071 dbp = skip_spaces (dbp);
4072 if (*dbp == '\0') /* assume un-named */
4073 make_tag ("blockdata", 9, TRUE,
4074 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4075 else
4076 F_getit (inf); /* look for name */
4078 continue;
4085 * Ada parsing
4086 * Original code by
4087 * Philippe Waroquiers (1998)
4090 /* Once we are positioned after an "interesting" keyword, let's get
4091 the real tag value necessary. */
4092 static void
4093 Ada_getit (FILE *inf, const char *name_qualifier)
4095 register char *cp;
4096 char *name;
4097 char c;
4099 while (!feof (inf))
4101 dbp = skip_spaces (dbp);
4102 if (*dbp == '\0'
4103 || (dbp[0] == '-' && dbp[1] == '-'))
4105 readline (&lb, inf);
4106 dbp = lb.buffer;
4108 switch (lowcase (*dbp))
4110 case 'b':
4111 if (nocase_tail ("body"))
4113 /* Skipping body of procedure body or package body or ....
4114 resetting qualifier to body instead of spec. */
4115 name_qualifier = "/b";
4116 continue;
4118 break;
4119 case 't':
4120 /* Skipping type of task type or protected type ... */
4121 if (nocase_tail ("type"))
4122 continue;
4123 break;
4125 if (*dbp == '"')
4127 dbp += 1;
4128 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4129 continue;
4131 else
4133 dbp = skip_spaces (dbp);
4134 for (cp = dbp;
4135 (*cp != '\0'
4136 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4137 cp++)
4138 continue;
4139 if (cp == dbp)
4140 return;
4142 c = *cp;
4143 *cp = '\0';
4144 name = concat (dbp, name_qualifier, "");
4145 *cp = c;
4146 make_tag (name, strlen (name), TRUE,
4147 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4148 free (name);
4149 if (c == '"')
4150 dbp = cp + 1;
4151 return;
4155 static void
4156 Ada_funcs (FILE *inf)
4158 bool inquote = FALSE;
4159 bool skip_till_semicolumn = FALSE;
4161 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4163 while (*dbp != '\0')
4165 /* Skip a string i.e. "abcd". */
4166 if (inquote || (*dbp == '"'))
4168 dbp = etags_strchr (dbp + !inquote, '"');
4169 if (dbp != NULL)
4171 inquote = FALSE;
4172 dbp += 1;
4173 continue; /* advance char */
4175 else
4177 inquote = TRUE;
4178 break; /* advance line */
4182 /* Skip comments. */
4183 if (dbp[0] == '-' && dbp[1] == '-')
4184 break; /* advance line */
4186 /* Skip character enclosed in single quote i.e. 'a'
4187 and skip single quote starting an attribute i.e. 'Image. */
4188 if (*dbp == '\'')
4190 dbp++ ;
4191 if (*dbp != '\0')
4192 dbp++;
4193 continue;
4196 if (skip_till_semicolumn)
4198 if (*dbp == ';')
4199 skip_till_semicolumn = FALSE;
4200 dbp++;
4201 continue; /* advance char */
4204 /* Search for beginning of a token. */
4205 if (!begtoken (*dbp))
4207 dbp++;
4208 continue; /* advance char */
4211 /* We are at the beginning of a token. */
4212 switch (lowcase (*dbp))
4214 case 'f':
4215 if (!packages_only && nocase_tail ("function"))
4216 Ada_getit (inf, "/f");
4217 else
4218 break; /* from switch */
4219 continue; /* advance char */
4220 case 'p':
4221 if (!packages_only && nocase_tail ("procedure"))
4222 Ada_getit (inf, "/p");
4223 else if (nocase_tail ("package"))
4224 Ada_getit (inf, "/s");
4225 else if (nocase_tail ("protected")) /* protected type */
4226 Ada_getit (inf, "/t");
4227 else
4228 break; /* from switch */
4229 continue; /* advance char */
4231 case 'u':
4232 if (typedefs && !packages_only && nocase_tail ("use"))
4234 /* when tagging types, avoid tagging use type Pack.Typename;
4235 for this, we will skip everything till a ; */
4236 skip_till_semicolumn = TRUE;
4237 continue; /* advance char */
4240 case 't':
4241 if (!packages_only && nocase_tail ("task"))
4242 Ada_getit (inf, "/k");
4243 else if (typedefs && !packages_only && nocase_tail ("type"))
4245 Ada_getit (inf, "/t");
4246 while (*dbp != '\0')
4247 dbp += 1;
4249 else
4250 break; /* from switch */
4251 continue; /* advance char */
4254 /* Look for the end of the token. */
4255 while (!endtoken (*dbp))
4256 dbp++;
4258 } /* advance char */
4259 } /* advance line */
4264 * Unix and microcontroller assembly tag handling
4265 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4266 * Idea by Bob Weiner, Motorola Inc. (1994)
4268 static void
4269 Asm_labels (FILE *inf)
4271 register char *cp;
4273 LOOP_ON_INPUT_LINES (inf, lb, cp)
4275 /* If first char is alphabetic or one of [_.$], test for colon
4276 following identifier. */
4277 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4279 /* Read past label. */
4280 cp++;
4281 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4282 cp++;
4283 if (*cp == ':' || iswhite (*cp))
4284 /* Found end of label, so copy it and add it to the table. */
4285 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4286 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4293 * Perl support
4294 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4295 * Perl variable names: /^(my|local).../
4296 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4297 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4298 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4300 static void
4301 Perl_functions (FILE *inf)
4303 char *package = savestr ("main"); /* current package name */
4304 register char *cp;
4306 LOOP_ON_INPUT_LINES (inf, lb, cp)
4308 cp = skip_spaces (cp);
4310 if (LOOKING_AT (cp, "package"))
4312 free (package);
4313 get_tag (cp, &package);
4315 else if (LOOKING_AT (cp, "sub"))
4317 char *pos;
4318 char *sp = cp;
4320 while (!notinname (*cp))
4321 cp++;
4322 if (cp == sp)
4323 continue; /* nothing found */
4324 if ((pos = etags_strchr (sp, ':')) != NULL
4325 && pos < cp && pos[1] == ':')
4326 /* The name is already qualified. */
4327 make_tag (sp, cp - sp, TRUE,
4328 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4329 else
4330 /* Qualify it. */
4332 char savechar, *name;
4334 savechar = *cp;
4335 *cp = '\0';
4336 name = concat (package, "::", sp);
4337 *cp = savechar;
4338 make_tag (name, strlen (name), TRUE,
4339 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4340 free (name);
4343 else if (globals) /* only if we are tagging global vars */
4345 /* Skip a qualifier, if any. */
4346 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4347 /* After "my" or "local", but before any following paren or space. */
4348 char *varstart = cp;
4350 if (qual /* should this be removed? If yes, how? */
4351 && (*cp == '$' || *cp == '@' || *cp == '%'))
4353 varstart += 1;
4355 cp++;
4356 while (ISALNUM (*cp) || *cp == '_');
4358 else if (qual)
4360 /* Should be examining a variable list at this point;
4361 could insist on seeing an open parenthesis. */
4362 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4363 cp++;
4365 else
4366 continue;
4368 make_tag (varstart, cp - varstart, FALSE,
4369 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4372 free (package);
4377 * Python support
4378 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4379 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4380 * More ideas by seb bacon <seb@jamkit.com> (2002)
4382 static void
4383 Python_functions (FILE *inf)
4385 register char *cp;
4387 LOOP_ON_INPUT_LINES (inf, lb, cp)
4389 cp = skip_spaces (cp);
4390 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4392 char *name = cp;
4393 while (!notinname (*cp) && *cp != ':')
4394 cp++;
4395 make_tag (name, cp - name, TRUE,
4396 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4403 * PHP support
4404 * Look for:
4405 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4406 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4407 * - /^[ \t]*define\(\"[^\"]+/
4408 * Only with --members:
4409 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4410 * Idea by Diez B. Roggisch (2001)
4412 static void
4413 PHP_functions (FILE *inf)
4415 register char *cp, *name;
4416 bool search_identifier = FALSE;
4418 LOOP_ON_INPUT_LINES (inf, lb, cp)
4420 cp = skip_spaces (cp);
4421 name = cp;
4422 if (search_identifier
4423 && *cp != '\0')
4425 while (!notinname (*cp))
4426 cp++;
4427 make_tag (name, cp - name, TRUE,
4428 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4429 search_identifier = FALSE;
4431 else if (LOOKING_AT (cp, "function"))
4433 if (*cp == '&')
4434 cp = skip_spaces (cp+1);
4435 if (*cp != '\0')
4437 name = cp;
4438 while (!notinname (*cp))
4439 cp++;
4440 make_tag (name, cp - name, TRUE,
4441 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4443 else
4444 search_identifier = TRUE;
4446 else if (LOOKING_AT (cp, "class"))
4448 if (*cp != '\0')
4450 name = cp;
4451 while (*cp != '\0' && !iswhite (*cp))
4452 cp++;
4453 make_tag (name, cp - name, FALSE,
4454 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4456 else
4457 search_identifier = TRUE;
4459 else if (strneq (cp, "define", 6)
4460 && (cp = skip_spaces (cp+6))
4461 && *cp++ == '('
4462 && (*cp == '"' || *cp == '\''))
4464 char quote = *cp++;
4465 name = cp;
4466 while (*cp != quote && *cp != '\0')
4467 cp++;
4468 make_tag (name, cp - name, FALSE,
4469 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4471 else if (members
4472 && LOOKING_AT (cp, "var")
4473 && *cp == '$')
4475 name = cp;
4476 while (!notinname (*cp))
4477 cp++;
4478 make_tag (name, cp - name, FALSE,
4479 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4486 * Cobol tag functions
4487 * We could look for anything that could be a paragraph name.
4488 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4489 * Idea by Corny de Souza (1993)
4491 static void
4492 Cobol_paragraphs (FILE *inf)
4494 register char *bp, *ep;
4496 LOOP_ON_INPUT_LINES (inf, lb, bp)
4498 if (lb.len < 9)
4499 continue;
4500 bp += 8;
4502 /* If eoln, compiler option or comment ignore whole line. */
4503 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4504 continue;
4506 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4507 continue;
4508 if (*ep++ == '.')
4509 make_tag (bp, ep - bp, TRUE,
4510 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4516 * Makefile support
4517 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4519 static void
4520 Makefile_targets (FILE *inf)
4522 register char *bp;
4524 LOOP_ON_INPUT_LINES (inf, lb, bp)
4526 if (*bp == '\t' || *bp == '#')
4527 continue;
4528 while (*bp != '\0' && *bp != '=' && *bp != ':')
4529 bp++;
4530 if (*bp == ':' || (globals && *bp == '='))
4532 /* We should detect if there is more than one tag, but we do not.
4533 We just skip initial and final spaces. */
4534 char * namestart = skip_spaces (lb.buffer);
4535 while (--bp > namestart)
4536 if (!notinname (*bp))
4537 break;
4538 make_tag (namestart, bp - namestart + 1, TRUE,
4539 lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4546 * Pascal parsing
4547 * Original code by Mosur K. Mohan (1989)
4549 * Locates tags for procedures & functions. Doesn't do any type- or
4550 * var-definitions. It does look for the keyword "extern" or
4551 * "forward" immediately following the procedure statement; if found,
4552 * the tag is skipped.
4554 static void
4555 Pascal_functions (FILE *inf)
4557 linebuffer tline; /* mostly copied from C_entries */
4558 long save_lcno;
4559 int save_lineno, namelen, taglen;
4560 char c, *name;
4562 bool /* each of these flags is TRUE if: */
4563 incomment, /* point is inside a comment */
4564 inquote, /* point is inside '..' string */
4565 get_tagname, /* point is after PROCEDURE/FUNCTION
4566 keyword, so next item = potential tag */
4567 found_tag, /* point is after a potential tag */
4568 inparms, /* point is within parameter-list */
4569 verify_tag; /* point has passed the parm-list, so the
4570 next token will determine whether this
4571 is a FORWARD/EXTERN to be ignored, or
4572 whether it is a real tag */
4574 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
4575 name = NULL; /* keep compiler quiet */
4576 dbp = lb.buffer;
4577 *dbp = '\0';
4578 linebuffer_init (&tline);
4580 incomment = inquote = FALSE;
4581 found_tag = FALSE; /* have a proc name; check if extern */
4582 get_tagname = FALSE; /* found "procedure" keyword */
4583 inparms = FALSE; /* found '(' after "proc" */
4584 verify_tag = FALSE; /* check if "extern" is ahead */
4587 while (!feof (inf)) /* long main loop to get next char */
4589 c = *dbp++;
4590 if (c == '\0') /* if end of line */
4592 readline (&lb, inf);
4593 dbp = lb.buffer;
4594 if (*dbp == '\0')
4595 continue;
4596 if (!((found_tag && verify_tag)
4597 || get_tagname))
4598 c = *dbp++; /* only if don't need *dbp pointing
4599 to the beginning of the name of
4600 the procedure or function */
4602 if (incomment)
4604 if (c == '}') /* within { } comments */
4605 incomment = FALSE;
4606 else if (c == '*' && *dbp == ')') /* within (* *) comments */
4608 dbp++;
4609 incomment = FALSE;
4611 continue;
4613 else if (inquote)
4615 if (c == '\'')
4616 inquote = FALSE;
4617 continue;
4619 else
4620 switch (c)
4622 case '\'':
4623 inquote = TRUE; /* found first quote */
4624 continue;
4625 case '{': /* found open { comment */
4626 incomment = TRUE;
4627 continue;
4628 case '(':
4629 if (*dbp == '*') /* found open (* comment */
4631 incomment = TRUE;
4632 dbp++;
4634 else if (found_tag) /* found '(' after tag, i.e., parm-list */
4635 inparms = TRUE;
4636 continue;
4637 case ')': /* end of parms list */
4638 if (inparms)
4639 inparms = FALSE;
4640 continue;
4641 case ';':
4642 if (found_tag && !inparms) /* end of proc or fn stmt */
4644 verify_tag = TRUE;
4645 break;
4647 continue;
4649 if (found_tag && verify_tag && (*dbp != ' '))
4651 /* Check if this is an "extern" declaration. */
4652 if (*dbp == '\0')
4653 continue;
4654 if (lowcase (*dbp) == 'e')
4656 if (nocase_tail ("extern")) /* superfluous, really! */
4658 found_tag = FALSE;
4659 verify_tag = FALSE;
4662 else if (lowcase (*dbp) == 'f')
4664 if (nocase_tail ("forward")) /* check for forward reference */
4666 found_tag = FALSE;
4667 verify_tag = FALSE;
4670 if (found_tag && verify_tag) /* not external proc, so make tag */
4672 found_tag = FALSE;
4673 verify_tag = FALSE;
4674 make_tag (name, namelen, TRUE,
4675 tline.buffer, taglen, save_lineno, save_lcno);
4676 continue;
4679 if (get_tagname) /* grab name of proc or fn */
4681 char *cp;
4683 if (*dbp == '\0')
4684 continue;
4686 /* Find block name. */
4687 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
4688 continue;
4690 /* Save all values for later tagging. */
4691 linebuffer_setlen (&tline, lb.len);
4692 strcpy (tline.buffer, lb.buffer);
4693 save_lineno = lineno;
4694 save_lcno = linecharno;
4695 name = tline.buffer + (dbp - lb.buffer);
4696 namelen = cp - dbp;
4697 taglen = cp - lb.buffer + 1;
4699 dbp = cp; /* set dbp to e-o-token */
4700 get_tagname = FALSE;
4701 found_tag = TRUE;
4702 continue;
4704 /* And proceed to check for "extern". */
4706 else if (!incomment && !inquote && !found_tag)
4708 /* Check for proc/fn keywords. */
4709 switch (lowcase (c))
4711 case 'p':
4712 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
4713 get_tagname = TRUE;
4714 continue;
4715 case 'f':
4716 if (nocase_tail ("unction"))
4717 get_tagname = TRUE;
4718 continue;
4721 } /* while not eof */
4723 free (tline.buffer);
4728 * Lisp tag functions
4729 * look for (def or (DEF, quote or QUOTE
4732 static void L_getit (void);
4734 static void
4735 L_getit (void)
4737 if (*dbp == '\'') /* Skip prefix quote */
4738 dbp++;
4739 else if (*dbp == '(')
4741 dbp++;
4742 /* Try to skip "(quote " */
4743 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
4744 /* Ok, then skip "(" before name in (defstruct (foo)) */
4745 dbp = skip_spaces (dbp);
4747 get_tag (dbp, NULL);
4750 static void
4751 Lisp_functions (FILE *inf)
4753 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4755 if (dbp[0] != '(')
4756 continue;
4758 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
4760 dbp = skip_non_spaces (dbp);
4761 dbp = skip_spaces (dbp);
4762 L_getit ();
4764 else
4766 /* Check for (foo::defmumble name-defined ... */
4768 dbp++;
4769 while (!notinname (*dbp) && *dbp != ':');
4770 if (*dbp == ':')
4773 dbp++;
4774 while (*dbp == ':');
4776 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
4778 dbp = skip_non_spaces (dbp);
4779 dbp = skip_spaces (dbp);
4780 L_getit ();
4789 * Lua script language parsing
4790 * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
4792 * "function" and "local function" are tags if they start at column 1.
4794 static void
4795 Lua_functions (FILE *inf)
4797 register char *bp;
4799 LOOP_ON_INPUT_LINES (inf, lb, bp)
4801 if (bp[0] != 'f' && bp[0] != 'l')
4802 continue;
4804 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
4806 if (LOOKING_AT (bp, "function"))
4807 get_tag (bp, NULL);
4813 * PostScript tags
4814 * Just look for lines where the first character is '/'
4815 * Also look at "defineps" for PSWrap
4816 * Ideas by:
4817 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
4818 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
4820 static void
4821 PS_functions (FILE *inf)
4823 register char *bp, *ep;
4825 LOOP_ON_INPUT_LINES (inf, lb, bp)
4827 if (bp[0] == '/')
4829 for (ep = bp+1;
4830 *ep != '\0' && *ep != ' ' && *ep != '{';
4831 ep++)
4832 continue;
4833 make_tag (bp, ep - bp, TRUE,
4834 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4836 else if (LOOKING_AT (bp, "defineps"))
4837 get_tag (bp, NULL);
4843 * Forth tags
4844 * Ignore anything after \ followed by space or in ( )
4845 * Look for words defined by :
4846 * Look for constant, code, create, defer, value, and variable
4847 * OBP extensions: Look for buffer:, field,
4848 * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
4850 static void
4851 Forth_words (FILE *inf)
4853 register char *bp;
4855 LOOP_ON_INPUT_LINES (inf, lb, bp)
4856 while ((bp = skip_spaces (bp))[0] != '\0')
4857 if (bp[0] == '\\' && iswhite (bp[1]))
4858 break; /* read next line */
4859 else if (bp[0] == '(' && iswhite (bp[1]))
4860 do /* skip to ) or eol */
4861 bp++;
4862 while (*bp != ')' && *bp != '\0');
4863 else if ((bp[0] == ':' && iswhite (bp[1]) && bp++)
4864 || LOOKING_AT_NOCASE (bp, "constant")
4865 || LOOKING_AT_NOCASE (bp, "code")
4866 || LOOKING_AT_NOCASE (bp, "create")
4867 || LOOKING_AT_NOCASE (bp, "defer")
4868 || LOOKING_AT_NOCASE (bp, "value")
4869 || LOOKING_AT_NOCASE (bp, "variable")
4870 || LOOKING_AT_NOCASE (bp, "buffer:")
4871 || LOOKING_AT_NOCASE (bp, "field"))
4872 get_tag (skip_spaces (bp), NULL); /* Yay! A definition! */
4873 else
4874 bp = skip_non_spaces (bp);
4879 * Scheme tag functions
4880 * look for (def... xyzzy
4881 * (def... (xyzzy
4882 * (def ... ((...(xyzzy ....
4883 * (set! xyzzy
4884 * Original code by Ken Haase (1985?)
4886 static void
4887 Scheme_functions (FILE *inf)
4889 register char *bp;
4891 LOOP_ON_INPUT_LINES (inf, lb, bp)
4893 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
4895 bp = skip_non_spaces (bp+4);
4896 /* Skip over open parens and white space. Don't continue past
4897 '\0'. */
4898 while (*bp && notinname (*bp))
4899 bp++;
4900 get_tag (bp, NULL);
4902 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
4903 get_tag (bp, NULL);
4908 /* Find tags in TeX and LaTeX input files. */
4910 /* TEX_toktab is a table of TeX control sequences that define tags.
4911 * Each entry records one such control sequence.
4913 * Original code from who knows whom.
4914 * Ideas by:
4915 * Stefan Monnier (2002)
4918 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
4920 /* Default set of control sequences to put into TEX_toktab.
4921 The value of environment var TEXTAGS is prepended to this. */
4922 static const char *TEX_defenv = "\
4923 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
4924 :part:appendix:entry:index:def\
4925 :newcommand:renewcommand:newenvironment:renewenvironment";
4927 static void TEX_mode (FILE *);
4928 static void TEX_decode_env (const char *, const char *);
4930 static char TEX_esc = '\\';
4931 static char TEX_opgrp = '{';
4932 static char TEX_clgrp = '}';
4935 * TeX/LaTeX scanning loop.
4937 static void
4938 TeX_commands (FILE *inf)
4940 char *cp;
4941 linebuffer *key;
4943 /* Select either \ or ! as escape character. */
4944 TEX_mode (inf);
4946 /* Initialize token table once from environment. */
4947 if (TEX_toktab == NULL)
4948 TEX_decode_env ("TEXTAGS", TEX_defenv);
4950 LOOP_ON_INPUT_LINES (inf, lb, cp)
4952 /* Look at each TEX keyword in line. */
4953 for (;;)
4955 /* Look for a TEX escape. */
4956 while (*cp++ != TEX_esc)
4957 if (cp[-1] == '\0' || cp[-1] == '%')
4958 goto tex_next_line;
4960 for (key = TEX_toktab; key->buffer != NULL; key++)
4961 if (strneq (cp, key->buffer, key->len))
4963 register char *p;
4964 int namelen, linelen;
4965 bool opgrp = FALSE;
4967 cp = skip_spaces (cp + key->len);
4968 if (*cp == TEX_opgrp)
4970 opgrp = TRUE;
4971 cp++;
4973 for (p = cp;
4974 (!iswhite (*p) && *p != '#' &&
4975 *p != TEX_opgrp && *p != TEX_clgrp);
4976 p++)
4977 continue;
4978 namelen = p - cp;
4979 linelen = lb.len;
4980 if (!opgrp || *p == TEX_clgrp)
4982 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
4983 p++;
4984 linelen = p - lb.buffer + 1;
4986 make_tag (cp, namelen, TRUE,
4987 lb.buffer, linelen, lineno, linecharno);
4988 goto tex_next_line; /* We only tag a line once */
4991 tex_next_line:
4996 #define TEX_LESC '\\'
4997 #define TEX_SESC '!'
4999 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5000 chars accordingly. */
5001 static void
5002 TEX_mode (FILE *inf)
5004 int c;
5006 while ((c = getc (inf)) != EOF)
5008 /* Skip to next line if we hit the TeX comment char. */
5009 if (c == '%')
5010 while (c != '\n' && c != EOF)
5011 c = getc (inf);
5012 else if (c == TEX_LESC || c == TEX_SESC )
5013 break;
5016 if (c == TEX_LESC)
5018 TEX_esc = TEX_LESC;
5019 TEX_opgrp = '{';
5020 TEX_clgrp = '}';
5022 else
5024 TEX_esc = TEX_SESC;
5025 TEX_opgrp = '<';
5026 TEX_clgrp = '>';
5028 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5029 No attempt is made to correct the situation. */
5030 rewind (inf);
5033 /* Read environment and prepend it to the default string.
5034 Build token table. */
5035 static void
5036 TEX_decode_env (const char *evarname, const char *defenv)
5038 register const char *env, *p;
5039 int i, len;
5041 /* Append default string to environment. */
5042 env = getenv (evarname);
5043 if (!env)
5044 env = defenv;
5045 else
5046 env = concat (env, defenv, "");
5048 /* Allocate a token table */
5049 for (len = 1, p = env; p;)
5050 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5051 len++;
5052 TEX_toktab = xnew (len, linebuffer);
5054 /* Unpack environment string into token table. Be careful about */
5055 /* zero-length strings (leading ':', "::" and trailing ':') */
5056 for (i = 0; *env != '\0';)
5058 p = etags_strchr (env, ':');
5059 if (!p) /* End of environment string. */
5060 p = env + strlen (env);
5061 if (p - env > 0)
5062 { /* Only non-zero strings. */
5063 TEX_toktab[i].buffer = savenstr (env, p - env);
5064 TEX_toktab[i].len = p - env;
5065 i++;
5067 if (*p)
5068 env = p + 1;
5069 else
5071 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5072 TEX_toktab[i].len = 0;
5073 break;
5079 /* Texinfo support. Dave Love, Mar. 2000. */
5080 static void
5081 Texinfo_nodes (FILE *inf)
5083 char *cp, *start;
5084 LOOP_ON_INPUT_LINES (inf, lb, cp)
5085 if (LOOKING_AT (cp, "@node"))
5087 start = cp;
5088 while (*cp != '\0' && *cp != ',')
5089 cp++;
5090 make_tag (start, cp - start, TRUE,
5091 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5097 * HTML support.
5098 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5099 * Contents of <a name=xxx> are tags with name xxx.
5101 * Francesco Potortì, 2002.
5103 static void
5104 HTML_labels (FILE *inf)
5106 bool getnext = FALSE; /* next text outside of HTML tags is a tag */
5107 bool skiptag = FALSE; /* skip to the end of the current HTML tag */
5108 bool intag = FALSE; /* inside an html tag, looking for ID= */
5109 bool inanchor = FALSE; /* when INTAG, is an anchor, look for NAME= */
5110 char *end;
5113 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5115 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5116 for (;;) /* loop on the same line */
5118 if (skiptag) /* skip HTML tag */
5120 while (*dbp != '\0' && *dbp != '>')
5121 dbp++;
5122 if (*dbp == '>')
5124 dbp += 1;
5125 skiptag = FALSE;
5126 continue; /* look on the same line */
5128 break; /* go to next line */
5131 else if (intag) /* look for "name=" or "id=" */
5133 while (*dbp != '\0' && *dbp != '>'
5134 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5135 dbp++;
5136 if (*dbp == '\0')
5137 break; /* go to next line */
5138 if (*dbp == '>')
5140 dbp += 1;
5141 intag = FALSE;
5142 continue; /* look on the same line */
5144 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5145 || LOOKING_AT_NOCASE (dbp, "id="))
5147 bool quoted = (dbp[0] == '"');
5149 if (quoted)
5150 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5151 continue;
5152 else
5153 for (end = dbp; *end != '\0' && intoken (*end); end++)
5154 continue;
5155 linebuffer_setlen (&token_name, end - dbp);
5156 memcpy (token_name.buffer, dbp, end - dbp);
5157 token_name.buffer[end - dbp] = '\0';
5159 dbp = end;
5160 intag = FALSE; /* we found what we looked for */
5161 skiptag = TRUE; /* skip to the end of the tag */
5162 getnext = TRUE; /* then grab the text */
5163 continue; /* look on the same line */
5165 dbp += 1;
5168 else if (getnext) /* grab next tokens and tag them */
5170 dbp = skip_spaces (dbp);
5171 if (*dbp == '\0')
5172 break; /* go to next line */
5173 if (*dbp == '<')
5175 intag = TRUE;
5176 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5177 continue; /* look on the same line */
5180 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5181 continue;
5182 make_tag (token_name.buffer, token_name.len, TRUE,
5183 dbp, end - dbp, lineno, linecharno);
5184 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5185 getnext = FALSE;
5186 break; /* go to next line */
5189 else /* look for an interesting HTML tag */
5191 while (*dbp != '\0' && *dbp != '<')
5192 dbp++;
5193 if (*dbp == '\0')
5194 break; /* go to next line */
5195 intag = TRUE;
5196 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5198 inanchor = TRUE;
5199 continue; /* look on the same line */
5201 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5202 || LOOKING_AT_NOCASE (dbp, "<h1>")
5203 || LOOKING_AT_NOCASE (dbp, "<h2>")
5204 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5206 intag = FALSE;
5207 getnext = TRUE;
5208 continue; /* look on the same line */
5210 dbp += 1;
5217 * Prolog support
5219 * Assumes that the predicate or rule starts at column 0.
5220 * Only the first clause of a predicate or rule is added.
5221 * Original code by Sunichirou Sugou (1989)
5222 * Rewritten by Anders Lindgren (1996)
5224 static size_t prolog_pr (char *, char *);
5225 static void prolog_skip_comment (linebuffer *, FILE *);
5226 static size_t prolog_atom (char *, size_t);
5228 static void
5229 Prolog_functions (FILE *inf)
5231 char *cp, *last;
5232 size_t len;
5233 size_t allocated;
5235 allocated = 0;
5236 len = 0;
5237 last = NULL;
5239 LOOP_ON_INPUT_LINES (inf, lb, cp)
5241 if (cp[0] == '\0') /* Empty line */
5242 continue;
5243 else if (iswhite (cp[0])) /* Not a predicate */
5244 continue;
5245 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5246 prolog_skip_comment (&lb, inf);
5247 else if ((len = prolog_pr (cp, last)) > 0)
5249 /* Predicate or rule. Store the function name so that we
5250 only generate a tag for the first clause. */
5251 if (last == NULL)
5252 last = xnew (len + 1, char);
5253 else if (len + 1 > allocated)
5254 xrnew (last, len + 1, char);
5255 allocated = len + 1;
5256 memcpy (last, cp, len);
5257 last[len] = '\0';
5260 free (last);
5264 static void
5265 prolog_skip_comment (linebuffer *plb, FILE *inf)
5267 char *cp;
5271 for (cp = plb->buffer; *cp != '\0'; cp++)
5272 if (cp[0] == '*' && cp[1] == '/')
5273 return;
5274 readline (plb, inf);
5276 while (!feof (inf));
5280 * A predicate or rule definition is added if it matches:
5281 * <beginning of line><Prolog Atom><whitespace>(
5282 * or <beginning of line><Prolog Atom><whitespace>:-
5284 * It is added to the tags database if it doesn't match the
5285 * name of the previous clause header.
5287 * Return the size of the name of the predicate or rule, or 0 if no
5288 * header was found.
5290 static size_t
5291 prolog_pr (char *s, char *last)
5293 /* Name of last clause. */
5295 size_t pos;
5296 size_t len;
5298 pos = prolog_atom (s, 0);
5299 if (! pos)
5300 return 0;
5302 len = pos;
5303 pos = skip_spaces (s + pos) - s;
5305 if ((s[pos] == '.'
5306 || (s[pos] == '(' && (pos += 1))
5307 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5308 && (last == NULL /* save only the first clause */
5309 || len != strlen (last)
5310 || !strneq (s, last, len)))
5312 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5313 return len;
5315 else
5316 return 0;
5320 * Consume a Prolog atom.
5321 * Return the number of bytes consumed, or 0 if there was an error.
5323 * A prolog atom, in this context, could be one of:
5324 * - An alphanumeric sequence, starting with a lower case letter.
5325 * - A quoted arbitrary string. Single quotes can escape themselves.
5326 * Backslash quotes everything.
5328 static size_t
5329 prolog_atom (char *s, size_t pos)
5331 size_t origpos;
5333 origpos = pos;
5335 if (ISLOWER (s[pos]) || (s[pos] == '_'))
5337 /* The atom is unquoted. */
5338 pos++;
5339 while (ISALNUM (s[pos]) || (s[pos] == '_'))
5341 pos++;
5343 return pos - origpos;
5345 else if (s[pos] == '\'')
5347 pos++;
5349 for (;;)
5351 if (s[pos] == '\'')
5353 pos++;
5354 if (s[pos] != '\'')
5355 break;
5356 pos++; /* A double quote */
5358 else if (s[pos] == '\0')
5359 /* Multiline quoted atoms are ignored. */
5360 return 0;
5361 else if (s[pos] == '\\')
5363 if (s[pos+1] == '\0')
5364 return 0;
5365 pos += 2;
5367 else
5368 pos++;
5370 return pos - origpos;
5372 else
5373 return 0;
5378 * Support for Erlang
5380 * Generates tags for functions, defines, and records.
5381 * Assumes that Erlang functions start at column 0.
5382 * Original code by Anders Lindgren (1996)
5384 static int erlang_func (char *, char *);
5385 static void erlang_attribute (char *);
5386 static int erlang_atom (char *);
5388 static void
5389 Erlang_functions (FILE *inf)
5391 char *cp, *last;
5392 int len;
5393 int allocated;
5395 allocated = 0;
5396 len = 0;
5397 last = NULL;
5399 LOOP_ON_INPUT_LINES (inf, lb, cp)
5401 if (cp[0] == '\0') /* Empty line */
5402 continue;
5403 else if (iswhite (cp[0])) /* Not function nor attribute */
5404 continue;
5405 else if (cp[0] == '%') /* comment */
5406 continue;
5407 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5408 continue;
5409 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5411 erlang_attribute (cp);
5412 if (last != NULL)
5414 free (last);
5415 last = NULL;
5418 else if ((len = erlang_func (cp, last)) > 0)
5421 * Function. Store the function name so that we only
5422 * generates a tag for the first clause.
5424 if (last == NULL)
5425 last = xnew (len + 1, char);
5426 else if (len + 1 > allocated)
5427 xrnew (last, len + 1, char);
5428 allocated = len + 1;
5429 memcpy (last, cp, len);
5430 last[len] = '\0';
5433 free (last);
5438 * A function definition is added if it matches:
5439 * <beginning of line><Erlang Atom><whitespace>(
5441 * It is added to the tags database if it doesn't match the
5442 * name of the previous clause header.
5444 * Return the size of the name of the function, or 0 if no function
5445 * was found.
5447 static int
5448 erlang_func (char *s, char *last)
5450 /* Name of last clause. */
5452 int pos;
5453 int len;
5455 pos = erlang_atom (s);
5456 if (pos < 1)
5457 return 0;
5459 len = pos;
5460 pos = skip_spaces (s + pos) - s;
5462 /* Save only the first clause. */
5463 if (s[pos++] == '('
5464 && (last == NULL
5465 || len != (int)strlen (last)
5466 || !strneq (s, last, len)))
5468 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5469 return len;
5472 return 0;
5477 * Handle attributes. Currently, tags are generated for defines
5478 * and records.
5480 * They are on the form:
5481 * -define(foo, bar).
5482 * -define(Foo(M, N), M+N).
5483 * -record(graph, {vtab = notable, cyclic = true}).
5485 static void
5486 erlang_attribute (char *s)
5488 char *cp = s;
5490 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5491 && *cp++ == '(')
5493 int len = erlang_atom (skip_spaces (cp));
5494 if (len > 0)
5495 make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5497 return;
5502 * Consume an Erlang atom (or variable).
5503 * Return the number of bytes consumed, or -1 if there was an error.
5505 static int
5506 erlang_atom (char *s)
5508 int pos = 0;
5510 if (ISALPHA (s[pos]) || s[pos] == '_')
5512 /* The atom is unquoted. */
5514 pos++;
5515 while (ISALNUM (s[pos]) || s[pos] == '_');
5517 else if (s[pos] == '\'')
5519 for (pos++; s[pos] != '\''; pos++)
5520 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5521 || (s[pos] == '\\' && s[++pos] == '\0'))
5522 return 0;
5523 pos++;
5526 return pos;
5530 static char *scan_separators (char *);
5531 static void add_regex (char *, language *);
5532 static char *substitute (char *, char *, struct re_registers *);
5535 * Take a string like "/blah/" and turn it into "blah", verifying
5536 * that the first and last characters are the same, and handling
5537 * quoted separator characters. Actually, stops on the occurrence of
5538 * an unquoted separator. Also process \t, \n, etc. and turn into
5539 * appropriate characters. Works in place. Null terminates name string.
5540 * Returns pointer to terminating separator, or NULL for
5541 * unterminated regexps.
5543 static char *
5544 scan_separators (char *name)
5546 char sep = name[0];
5547 char *copyto = name;
5548 bool quoted = FALSE;
5550 for (++name; *name != '\0'; ++name)
5552 if (quoted)
5554 switch (*name)
5556 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
5557 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
5558 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
5559 case 'e': *copyto++ = 033; break; /* ESC (delete) */
5560 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
5561 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
5562 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
5563 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
5564 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
5565 default:
5566 if (*name == sep)
5567 *copyto++ = sep;
5568 else
5570 /* Something else is quoted, so preserve the quote. */
5571 *copyto++ = '\\';
5572 *copyto++ = *name;
5574 break;
5576 quoted = FALSE;
5578 else if (*name == '\\')
5579 quoted = TRUE;
5580 else if (*name == sep)
5581 break;
5582 else
5583 *copyto++ = *name;
5585 if (*name != sep)
5586 name = NULL; /* signal unterminated regexp */
5588 /* Terminate copied string. */
5589 *copyto = '\0';
5590 return name;
5593 /* Look at the argument of --regex or --no-regex and do the right
5594 thing. Same for each line of a regexp file. */
5595 static void
5596 analyse_regex (char *regex_arg)
5598 if (regex_arg == NULL)
5600 free_regexps (); /* --no-regex: remove existing regexps */
5601 return;
5604 /* A real --regexp option or a line in a regexp file. */
5605 switch (regex_arg[0])
5607 /* Comments in regexp file or null arg to --regex. */
5608 case '\0':
5609 case ' ':
5610 case '\t':
5611 break;
5613 /* Read a regex file. This is recursive and may result in a
5614 loop, which will stop when the file descriptors are exhausted. */
5615 case '@':
5617 FILE *regexfp;
5618 linebuffer regexbuf;
5619 char *regexfile = regex_arg + 1;
5621 /* regexfile is a file containing regexps, one per line. */
5622 regexfp = fopen (regexfile, "r");
5623 if (regexfp == NULL)
5625 pfatal (regexfile);
5626 return;
5628 linebuffer_init (&regexbuf);
5629 while (readline_internal (&regexbuf, regexfp) > 0)
5630 analyse_regex (regexbuf.buffer);
5631 free (regexbuf.buffer);
5632 fclose (regexfp);
5634 break;
5636 /* Regexp to be used for a specific language only. */
5637 case '{':
5639 language *lang;
5640 char *lang_name = regex_arg + 1;
5641 char *cp;
5643 for (cp = lang_name; *cp != '}'; cp++)
5644 if (*cp == '\0')
5646 error ("unterminated language name in regex: %s", regex_arg);
5647 return;
5649 *cp++ = '\0';
5650 lang = get_language_from_langname (lang_name);
5651 if (lang == NULL)
5652 return;
5653 add_regex (cp, lang);
5655 break;
5657 /* Regexp to be used for any language. */
5658 default:
5659 add_regex (regex_arg, NULL);
5660 break;
5664 /* Separate the regexp pattern, compile it,
5665 and care for optional name and modifiers. */
5666 static void
5667 add_regex (char *regexp_pattern, language *lang)
5669 static struct re_pattern_buffer zeropattern;
5670 char sep, *pat, *name, *modifiers;
5671 char empty = '\0';
5672 const char *err;
5673 struct re_pattern_buffer *patbuf;
5674 regexp *rp;
5675 bool
5676 force_explicit_name = TRUE, /* do not use implicit tag names */
5677 ignore_case = FALSE, /* case is significant */
5678 multi_line = FALSE, /* matches are done one line at a time */
5679 single_line = FALSE; /* dot does not match newline */
5682 if (strlen (regexp_pattern) < 3)
5684 error ("null regexp");
5685 return;
5687 sep = regexp_pattern[0];
5688 name = scan_separators (regexp_pattern);
5689 if (name == NULL)
5691 error ("%s: unterminated regexp", regexp_pattern);
5692 return;
5694 if (name[1] == sep)
5696 error ("null name for regexp \"%s\"", regexp_pattern);
5697 return;
5699 modifiers = scan_separators (name);
5700 if (modifiers == NULL) /* no terminating separator --> no name */
5702 modifiers = name;
5703 name = &empty;
5705 else
5706 modifiers += 1; /* skip separator */
5708 /* Parse regex modifiers. */
5709 for (; modifiers[0] != '\0'; modifiers++)
5710 switch (modifiers[0])
5712 case 'N':
5713 if (modifiers == name)
5714 error ("forcing explicit tag name but no name, ignoring");
5715 force_explicit_name = TRUE;
5716 break;
5717 case 'i':
5718 ignore_case = TRUE;
5719 break;
5720 case 's':
5721 single_line = TRUE;
5722 /* FALLTHRU */
5723 case 'm':
5724 multi_line = TRUE;
5725 need_filebuf = TRUE;
5726 break;
5727 default:
5728 error ("invalid regexp modifier `%c', ignoring", modifiers[0]);
5729 break;
5732 patbuf = xnew (1, struct re_pattern_buffer);
5733 *patbuf = zeropattern;
5734 if (ignore_case)
5736 static char lc_trans[CHARS];
5737 int i;
5738 for (i = 0; i < CHARS; i++)
5739 lc_trans[i] = lowcase (i);
5740 patbuf->translate = lc_trans; /* translation table to fold case */
5743 if (multi_line)
5744 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
5745 else
5746 pat = regexp_pattern;
5748 if (single_line)
5749 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
5750 else
5751 re_set_syntax (RE_SYNTAX_EMACS);
5753 err = re_compile_pattern (pat, strlen (pat), patbuf);
5754 if (multi_line)
5755 free (pat);
5756 if (err != NULL)
5758 error ("%s while compiling pattern", err);
5759 return;
5762 rp = p_head;
5763 p_head = xnew (1, regexp);
5764 p_head->pattern = savestr (regexp_pattern);
5765 p_head->p_next = rp;
5766 p_head->lang = lang;
5767 p_head->pat = patbuf;
5768 p_head->name = savestr (name);
5769 p_head->error_signaled = FALSE;
5770 p_head->force_explicit_name = force_explicit_name;
5771 p_head->ignore_case = ignore_case;
5772 p_head->multi_line = multi_line;
5776 * Do the substitutions indicated by the regular expression and
5777 * arguments.
5779 static char *
5780 substitute (char *in, char *out, struct re_registers *regs)
5782 char *result, *t;
5783 int size, dig, diglen;
5785 result = NULL;
5786 size = strlen (out);
5788 /* Pass 1: figure out how much to allocate by finding all \N strings. */
5789 if (out[size - 1] == '\\')
5790 fatal ("pattern error in \"%s\"", out);
5791 for (t = etags_strchr (out, '\\');
5792 t != NULL;
5793 t = etags_strchr (t + 2, '\\'))
5794 if (ISDIGIT (t[1]))
5796 dig = t[1] - '0';
5797 diglen = regs->end[dig] - regs->start[dig];
5798 size += diglen - 2;
5800 else
5801 size -= 1;
5803 /* Allocate space and do the substitutions. */
5804 assert (size >= 0);
5805 result = xnew (size + 1, char);
5807 for (t = result; *out != '\0'; out++)
5808 if (*out == '\\' && ISDIGIT (*++out))
5810 dig = *out - '0';
5811 diglen = regs->end[dig] - regs->start[dig];
5812 memcpy (t, in + regs->start[dig], diglen);
5813 t += diglen;
5815 else
5816 *t++ = *out;
5817 *t = '\0';
5819 assert (t <= result + size);
5820 assert (t - result == (int)strlen (result));
5822 return result;
5825 /* Deallocate all regexps. */
5826 static void
5827 free_regexps (void)
5829 regexp *rp;
5830 while (p_head != NULL)
5832 rp = p_head->p_next;
5833 free (p_head->pattern);
5834 free (p_head->name);
5835 free (p_head);
5836 p_head = rp;
5838 return;
5842 * Reads the whole file as a single string from `filebuf' and looks for
5843 * multi-line regular expressions, creating tags on matches.
5844 * readline already dealt with normal regexps.
5846 * Idea by Ben Wing <ben@666.com> (2002).
5848 static void
5849 regex_tag_multiline (void)
5851 char *buffer = filebuf.buffer;
5852 regexp *rp;
5853 char *name;
5855 for (rp = p_head; rp != NULL; rp = rp->p_next)
5857 int match = 0;
5859 if (!rp->multi_line)
5860 continue; /* skip normal regexps */
5862 /* Generic initializations before parsing file from memory. */
5863 lineno = 1; /* reset global line number */
5864 charno = 0; /* reset global char number */
5865 linecharno = 0; /* reset global char number of line start */
5867 /* Only use generic regexps or those for the current language. */
5868 if (rp->lang != NULL && rp->lang != curfdp->lang)
5869 continue;
5871 while (match >= 0 && match < filebuf.len)
5873 match = re_search (rp->pat, buffer, filebuf.len, charno,
5874 filebuf.len - match, &rp->regs);
5875 switch (match)
5877 case -2:
5878 /* Some error. */
5879 if (!rp->error_signaled)
5881 error ("regexp stack overflow while matching \"%s\"",
5882 rp->pattern);
5883 rp->error_signaled = TRUE;
5885 break;
5886 case -1:
5887 /* No match. */
5888 break;
5889 default:
5890 if (match == rp->regs.end[0])
5892 if (!rp->error_signaled)
5894 error ("regexp matches the empty string: \"%s\"",
5895 rp->pattern);
5896 rp->error_signaled = TRUE;
5898 match = -3; /* exit from while loop */
5899 break;
5902 /* Match occurred. Construct a tag. */
5903 while (charno < rp->regs.end[0])
5904 if (buffer[charno++] == '\n')
5905 lineno++, linecharno = charno;
5906 name = rp->name;
5907 if (name[0] == '\0')
5908 name = NULL;
5909 else /* make a named tag */
5910 name = substitute (buffer, rp->name, &rp->regs);
5911 if (rp->force_explicit_name)
5912 /* Force explicit tag name, if a name is there. */
5913 pfnote (name, TRUE, buffer + linecharno,
5914 charno - linecharno + 1, lineno, linecharno);
5915 else
5916 make_tag (name, strlen (name), TRUE, buffer + linecharno,
5917 charno - linecharno + 1, lineno, linecharno);
5918 break;
5925 static bool
5926 nocase_tail (const char *cp)
5928 register int len = 0;
5930 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
5931 cp++, len++;
5932 if (*cp == '\0' && !intoken (dbp[len]))
5934 dbp += len;
5935 return TRUE;
5937 return FALSE;
5940 static void
5941 get_tag (register char *bp, char **namepp)
5943 register char *cp = bp;
5945 if (*bp != '\0')
5947 /* Go till you get to white space or a syntactic break */
5948 for (cp = bp + 1; !notinname (*cp); cp++)
5949 continue;
5950 make_tag (bp, cp - bp, TRUE,
5951 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5954 if (namepp != NULL)
5955 *namepp = savenstr (bp, cp - bp);
5959 * Read a line of text from `stream' into `lbp', excluding the
5960 * newline or CR-NL, if any. Return the number of characters read from
5961 * `stream', which is the length of the line including the newline.
5963 * On DOS or Windows we do not count the CR character, if any before the
5964 * NL, in the returned length; this mirrors the behavior of Emacs on those
5965 * platforms (for text files, it translates CR-NL to NL as it reads in the
5966 * file).
5968 * If multi-line regular expressions are requested, each line read is
5969 * appended to `filebuf'.
5971 static long
5972 readline_internal (linebuffer *lbp, register FILE *stream)
5974 char *buffer = lbp->buffer;
5975 register char *p = lbp->buffer;
5976 register char *pend;
5977 int chars_deleted;
5979 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
5981 for (;;)
5983 register int c = getc (stream);
5984 if (p == pend)
5986 /* We're at the end of linebuffer: expand it. */
5987 lbp->size *= 2;
5988 xrnew (buffer, lbp->size, char);
5989 p += buffer - lbp->buffer;
5990 pend = buffer + lbp->size;
5991 lbp->buffer = buffer;
5993 if (c == EOF)
5995 *p = '\0';
5996 chars_deleted = 0;
5997 break;
5999 if (c == '\n')
6001 if (p > buffer && p[-1] == '\r')
6003 p -= 1;
6004 #ifdef DOS_NT
6005 /* Assume CRLF->LF translation will be performed by Emacs
6006 when loading this file, so CRs won't appear in the buffer.
6007 It would be cleaner to compensate within Emacs;
6008 however, Emacs does not know how many CRs were deleted
6009 before any given point in the file. */
6010 chars_deleted = 1;
6011 #else
6012 chars_deleted = 2;
6013 #endif
6015 else
6017 chars_deleted = 1;
6019 *p = '\0';
6020 break;
6022 *p++ = c;
6024 lbp->len = p - buffer;
6026 if (need_filebuf /* we need filebuf for multi-line regexps */
6027 && chars_deleted > 0) /* not at EOF */
6029 while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */
6031 /* Expand filebuf. */
6032 filebuf.size *= 2;
6033 xrnew (filebuf.buffer, filebuf.size, char);
6035 memcpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len);
6036 filebuf.len += lbp->len;
6037 filebuf.buffer[filebuf.len++] = '\n';
6038 filebuf.buffer[filebuf.len] = '\0';
6041 return lbp->len + chars_deleted;
6045 * Like readline_internal, above, but in addition try to match the
6046 * input line against relevant regular expressions and manage #line
6047 * directives.
6049 static void
6050 readline (linebuffer *lbp, FILE *stream)
6052 long result;
6054 linecharno = charno; /* update global char number of line start */
6055 result = readline_internal (lbp, stream); /* read line */
6056 lineno += 1; /* increment global line number */
6057 charno += result; /* increment global char number */
6059 /* Honor #line directives. */
6060 if (!no_line_directive)
6062 static bool discard_until_line_directive;
6064 /* Check whether this is a #line directive. */
6065 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6067 unsigned int lno;
6068 int start = 0;
6070 if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6071 && start > 0) /* double quote character found */
6073 char *endp = lbp->buffer + start;
6075 while ((endp = etags_strchr (endp, '"')) != NULL
6076 && endp[-1] == '\\')
6077 endp++;
6078 if (endp != NULL)
6079 /* Ok, this is a real #line directive. Let's deal with it. */
6081 char *taggedabsname; /* absolute name of original file */
6082 char *taggedfname; /* name of original file as given */
6083 char *name; /* temp var */
6085 discard_until_line_directive = FALSE; /* found it */
6086 name = lbp->buffer + start;
6087 *endp = '\0';
6088 canonicalize_filename (name);
6089 taggedabsname = absolute_filename (name, tagfiledir);
6090 if (filename_is_absolute (name)
6091 || filename_is_absolute (curfdp->infname))
6092 taggedfname = savestr (taggedabsname);
6093 else
6094 taggedfname = relative_filename (taggedabsname,tagfiledir);
6096 if (streq (curfdp->taggedfname, taggedfname))
6097 /* The #line directive is only a line number change. We
6098 deal with this afterwards. */
6099 free (taggedfname);
6100 else
6101 /* The tags following this #line directive should be
6102 attributed to taggedfname. In order to do this, set
6103 curfdp accordingly. */
6105 fdesc *fdp; /* file description pointer */
6107 /* Go look for a file description already set up for the
6108 file indicated in the #line directive. If there is
6109 one, use it from now until the next #line
6110 directive. */
6111 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6112 if (streq (fdp->infname, curfdp->infname)
6113 && streq (fdp->taggedfname, taggedfname))
6114 /* If we remove the second test above (after the &&)
6115 then all entries pertaining to the same file are
6116 coalesced in the tags file. If we use it, then
6117 entries pertaining to the same file but generated
6118 from different files (via #line directives) will
6119 go into separate sections in the tags file. These
6120 alternatives look equivalent. The first one
6121 destroys some apparently useless information. */
6123 curfdp = fdp;
6124 free (taggedfname);
6125 break;
6127 /* Else, if we already tagged the real file, skip all
6128 input lines until the next #line directive. */
6129 if (fdp == NULL) /* not found */
6130 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6131 if (streq (fdp->infabsname, taggedabsname))
6133 discard_until_line_directive = TRUE;
6134 free (taggedfname);
6135 break;
6137 /* Else create a new file description and use that from
6138 now on, until the next #line directive. */
6139 if (fdp == NULL) /* not found */
6141 fdp = fdhead;
6142 fdhead = xnew (1, fdesc);
6143 *fdhead = *curfdp; /* copy curr. file description */
6144 fdhead->next = fdp;
6145 fdhead->infname = savestr (curfdp->infname);
6146 fdhead->infabsname = savestr (curfdp->infabsname);
6147 fdhead->infabsdir = savestr (curfdp->infabsdir);
6148 fdhead->taggedfname = taggedfname;
6149 fdhead->usecharno = FALSE;
6150 fdhead->prop = NULL;
6151 fdhead->written = FALSE;
6152 curfdp = fdhead;
6155 free (taggedabsname);
6156 lineno = lno - 1;
6157 readline (lbp, stream);
6158 return;
6159 } /* if a real #line directive */
6160 } /* if #line is followed by a number */
6161 } /* if line begins with "#line " */
6163 /* If we are here, no #line directive was found. */
6164 if (discard_until_line_directive)
6166 if (result > 0)
6168 /* Do a tail recursion on ourselves, thus discarding the contents
6169 of the line buffer. */
6170 readline (lbp, stream);
6171 return;
6173 /* End of file. */
6174 discard_until_line_directive = FALSE;
6175 return;
6177 } /* if #line directives should be considered */
6180 int match;
6181 regexp *rp;
6182 char *name;
6184 /* Match against relevant regexps. */
6185 if (lbp->len > 0)
6186 for (rp = p_head; rp != NULL; rp = rp->p_next)
6188 /* Only use generic regexps or those for the current language.
6189 Also do not use multiline regexps, which is the job of
6190 regex_tag_multiline. */
6191 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6192 || rp->multi_line)
6193 continue;
6195 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6196 switch (match)
6198 case -2:
6199 /* Some error. */
6200 if (!rp->error_signaled)
6202 error ("regexp stack overflow while matching \"%s\"",
6203 rp->pattern);
6204 rp->error_signaled = TRUE;
6206 break;
6207 case -1:
6208 /* No match. */
6209 break;
6210 case 0:
6211 /* Empty string matched. */
6212 if (!rp->error_signaled)
6214 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6215 rp->error_signaled = TRUE;
6217 break;
6218 default:
6219 /* Match occurred. Construct a tag. */
6220 name = rp->name;
6221 if (name[0] == '\0')
6222 name = NULL;
6223 else /* make a named tag */
6224 name = substitute (lbp->buffer, rp->name, &rp->regs);
6225 if (rp->force_explicit_name)
6226 /* Force explicit tag name, if a name is there. */
6227 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6228 else
6229 make_tag (name, strlen (name), TRUE,
6230 lbp->buffer, match, lineno, linecharno);
6231 break;
6239 * Return a pointer to a space of size strlen(cp)+1 allocated
6240 * with xnew where the string CP has been copied.
6242 static char *
6243 savestr (const char *cp)
6245 return savenstr (cp, strlen (cp));
6249 * Return a pointer to a space of size LEN+1 allocated with xnew where
6250 * the string CP has been copied for at most the first LEN characters.
6252 static char *
6253 savenstr (const char *cp, int len)
6255 register char *dp;
6257 dp = xnew (len + 1, char);
6258 memcpy (dp, cp, len);
6259 dp[len] = '\0';
6260 return dp;
6264 * Return the ptr in sp at which the character c last
6265 * appears; NULL if not found
6267 * Identical to POSIX strrchr, included for portability.
6269 static char *
6270 etags_strrchr (register const char *sp, register int c)
6272 register const char *r;
6274 r = NULL;
6277 if (*sp == c)
6278 r = sp;
6279 } while (*sp++);
6280 return (char *)r;
6284 * Return the ptr in sp at which the character c first
6285 * appears; NULL if not found
6287 * Identical to POSIX strchr, included for portability.
6289 static char *
6290 etags_strchr (register const char *sp, register int c)
6294 if (*sp == c)
6295 return (char *)sp;
6296 } while (*sp++);
6297 return NULL;
6300 /* Skip spaces (end of string is not space), return new pointer. */
6301 static char *
6302 skip_spaces (char *cp)
6304 while (iswhite (*cp))
6305 cp++;
6306 return cp;
6309 /* Skip non spaces, except end of string, return new pointer. */
6310 static char *
6311 skip_non_spaces (char *cp)
6313 while (*cp != '\0' && !iswhite (*cp))
6314 cp++;
6315 return cp;
6318 /* Print error message and exit. */
6319 void
6320 fatal (const char *s1, const char *s2)
6322 error (s1, s2);
6323 exit (EXIT_FAILURE);
6326 static void
6327 pfatal (const char *s1)
6329 perror (s1);
6330 exit (EXIT_FAILURE);
6333 static void
6334 suggest_asking_for_help (void)
6336 fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6337 progname, NO_LONG_OPTIONS ? "-h" : "--help");
6338 exit (EXIT_FAILURE);
6341 /* Output a diagnostic with printf-style FORMAT and args. */
6342 static void
6343 error (const char *format, ...)
6345 va_list ap;
6346 va_start (ap, format);
6347 fprintf (stderr, "%s: ", progname);
6348 vfprintf (stderr, format, ap);
6349 fprintf (stderr, "\n");
6350 va_end (ap);
6353 /* Return a newly-allocated string whose contents
6354 concatenate those of s1, s2, s3. */
6355 static char *
6356 concat (const char *s1, const char *s2, const char *s3)
6358 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6359 char *result = xnew (len1 + len2 + len3 + 1, char);
6361 strcpy (result, s1);
6362 strcpy (result + len1, s2);
6363 strcpy (result + len1 + len2, s3);
6364 result[len1 + len2 + len3] = '\0';
6366 return result;
6370 /* Does the same work as the system V getcwd, but does not need to
6371 guess the buffer size in advance. */
6372 static char *
6373 etags_getcwd (void)
6375 #ifdef HAVE_GETCWD
6376 int bufsize = 200;
6377 char *path = xnew (bufsize, char);
6379 while (getcwd (path, bufsize) == NULL)
6381 if (errno != ERANGE)
6382 pfatal ("getcwd");
6383 bufsize *= 2;
6384 free (path);
6385 path = xnew (bufsize, char);
6388 canonicalize_filename (path);
6389 return path;
6391 #else /* not HAVE_GETCWD */
6392 #if MSDOS
6394 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
6396 getwd (path);
6398 for (p = path; *p != '\0'; p++)
6399 if (*p == '\\')
6400 *p = '/';
6401 else
6402 *p = lowcase (*p);
6404 return strdup (path);
6405 #else /* not MSDOS */
6406 linebuffer path;
6407 FILE *pipe;
6409 linebuffer_init (&path);
6410 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6411 if (pipe == NULL || readline_internal (&path, pipe) == 0)
6412 pfatal ("pwd");
6413 pclose (pipe);
6415 return path.buffer;
6416 #endif /* not MSDOS */
6417 #endif /* not HAVE_GETCWD */
6420 /* Return a newly allocated string containing the file name of FILE
6421 relative to the absolute directory DIR (which should end with a slash). */
6422 static char *
6423 relative_filename (char *file, char *dir)
6425 char *fp, *dp, *afn, *res;
6426 int i;
6428 /* Find the common root of file and dir (with a trailing slash). */
6429 afn = absolute_filename (file, cwd);
6430 fp = afn;
6431 dp = dir;
6432 while (*fp++ == *dp++)
6433 continue;
6434 fp--, dp--; /* back to the first differing char */
6435 #ifdef DOS_NT
6436 if (fp == afn && afn[0] != '/') /* cannot build a relative name */
6437 return afn;
6438 #endif
6439 do /* look at the equal chars until '/' */
6440 fp--, dp--;
6441 while (*fp != '/');
6443 /* Build a sequence of "../" strings for the resulting relative file name. */
6444 i = 0;
6445 while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6446 i += 1;
6447 res = xnew (3*i + strlen (fp + 1) + 1, char);
6448 res[0] = '\0';
6449 while (i-- > 0)
6450 strcat (res, "../");
6452 /* Add the file name relative to the common root of file and dir. */
6453 strcat (res, fp + 1);
6454 free (afn);
6456 return res;
6459 /* Return a newly allocated string containing the absolute file name
6460 of FILE given DIR (which should end with a slash). */
6461 static char *
6462 absolute_filename (char *file, char *dir)
6464 char *slashp, *cp, *res;
6466 if (filename_is_absolute (file))
6467 res = savestr (file);
6468 #ifdef DOS_NT
6469 /* We don't support non-absolute file names with a drive
6470 letter, like `d:NAME' (it's too much hassle). */
6471 else if (file[1] == ':')
6472 fatal ("%s: relative file names with drive letters not supported", file);
6473 #endif
6474 else
6475 res = concat (dir, file, "");
6477 /* Delete the "/dirname/.." and "/." substrings. */
6478 slashp = etags_strchr (res, '/');
6479 while (slashp != NULL && slashp[0] != '\0')
6481 if (slashp[1] == '.')
6483 if (slashp[2] == '.'
6484 && (slashp[3] == '/' || slashp[3] == '\0'))
6486 cp = slashp;
6488 cp--;
6489 while (cp >= res && !filename_is_absolute (cp));
6490 if (cp < res)
6491 cp = slashp; /* the absolute name begins with "/.." */
6492 #ifdef DOS_NT
6493 /* Under MSDOS and NT we get `d:/NAME' as absolute
6494 file name, so the luser could say `d:/../NAME'.
6495 We silently treat this as `d:/NAME'. */
6496 else if (cp[0] != '/')
6497 cp = slashp;
6498 #endif
6499 memmove (cp, slashp + 3, strlen (slashp + 2));
6500 slashp = cp;
6501 continue;
6503 else if (slashp[2] == '/' || slashp[2] == '\0')
6505 memmove (slashp, slashp + 2, strlen (slashp + 1));
6506 continue;
6510 slashp = etags_strchr (slashp + 1, '/');
6513 if (res[0] == '\0') /* just a safety net: should never happen */
6515 free (res);
6516 return savestr ("/");
6518 else
6519 return res;
6522 /* Return a newly allocated string containing the absolute
6523 file name of dir where FILE resides given DIR (which should
6524 end with a slash). */
6525 static char *
6526 absolute_dirname (char *file, char *dir)
6528 char *slashp, *res;
6529 char save;
6531 slashp = etags_strrchr (file, '/');
6532 if (slashp == NULL)
6533 return savestr (dir);
6534 save = slashp[1];
6535 slashp[1] = '\0';
6536 res = absolute_filename (file, dir);
6537 slashp[1] = save;
6539 return res;
6542 /* Whether the argument string is an absolute file name. The argument
6543 string must have been canonicalized with canonicalize_filename. */
6544 static bool
6545 filename_is_absolute (char *fn)
6547 return (fn[0] == '/'
6548 #ifdef DOS_NT
6549 || (ISALPHA (fn[0]) && fn[1] == ':' && fn[2] == '/')
6550 #endif
6554 /* Downcase DOS drive letter and collapse separators into single slashes.
6555 Works in place. */
6556 static void
6557 canonicalize_filename (register char *fn)
6559 register char* cp;
6560 char sep = '/';
6562 #ifdef DOS_NT
6563 /* Canonicalize drive letter case. */
6564 # define ISUPPER(c) isupper (CHAR (c))
6565 if (fn[0] != '\0' && fn[1] == ':' && ISUPPER (fn[0]))
6566 fn[0] = lowcase (fn[0]);
6568 sep = '\\';
6569 #endif
6571 /* Collapse multiple separators into a single slash. */
6572 for (cp = fn; *cp != '\0'; cp++, fn++)
6573 if (*cp == sep)
6575 *fn = '/';
6576 while (cp[1] == sep)
6577 cp++;
6579 else
6580 *fn = *cp;
6581 *fn = '\0';
6585 /* Initialize a linebuffer for use. */
6586 static void
6587 linebuffer_init (linebuffer *lbp)
6589 lbp->size = (DEBUG) ? 3 : 200;
6590 lbp->buffer = xnew (lbp->size, char);
6591 lbp->buffer[0] = '\0';
6592 lbp->len = 0;
6595 /* Set the minimum size of a string contained in a linebuffer. */
6596 static void
6597 linebuffer_setlen (linebuffer *lbp, int toksize)
6599 while (lbp->size <= toksize)
6601 lbp->size *= 2;
6602 xrnew (lbp->buffer, lbp->size, char);
6604 lbp->len = toksize;
6607 /* Like malloc but get fatal error if memory is exhausted. */
6608 static void *
6609 xmalloc (size_t size)
6611 void *result = malloc (size);
6612 if (result == NULL)
6613 fatal ("virtual memory exhausted", (char *)NULL);
6614 return result;
6617 static void *
6618 xrealloc (char *ptr, size_t size)
6620 void *result = realloc (ptr, size);
6621 if (result == NULL)
6622 fatal ("virtual memory exhausted", (char *)NULL);
6623 return result;
6627 * Local Variables:
6628 * indent-tabs-mode: t
6629 * tab-width: 8
6630 * fill-column: 79
6631 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
6632 * c-file-style: "gnu"
6633 * End:
6636 /* etags.c ends here */