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
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
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, 1988, 1989, 1993, 1994, 1995, 1998, 1999,
32 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
33 Free Software Foundation, Inc.
35 This file is not considered part of GNU Emacs.
37 This program is free software: you can redistribute it and/or modify
38 it under the terms of the GNU General Public License as published by
39 the Free Software Foundation, either version 3 of the License, or
40 (at your option) any later version.
42 This program is distributed in the hope that it will be useful,
43 but WITHOUT ANY WARRANTY; without even the implied warranty of
44 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 GNU General Public License for more details.
47 You should have received a copy of the GNU General Public License
48 along with this program. If not, see <http://www.gnu.org/licenses/>. */
51 /* NB To comply with the above BSD license, copyright information is
52 reproduced in etc/ETAGS.README. That file should be updated when the
55 To the best of our knowledge, this code was originally based on the
56 ctags.c distributed with BSD4.2, which was copyrighted by the
57 University of California, as described above. */
62 * 1983 Ctags originally by Ken Arnold.
63 * 1984 Fortran added by Jim Kleckner.
64 * 1984 Ed Pelegri-Llopart added C typedefs.
65 * 1985 Emacs TAGS format by Richard Stallman.
66 * 1989 Sam Kendall added C++.
67 * 1992 Joseph B. Wells improved C and C++ parsing.
68 * 1993 Francesco Potortì reorganized C and C++.
69 * 1994 Line-by-line regexp tags by Tom Tromey.
70 * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba).
71 * 2002 #line directives by Francesco Potortì.
73 * Francesco Potortì <pot@gnu.org> has maintained and improved it since 1993.
77 * If you want to add support for a new language, start by looking at the LUA
78 * language, which is the simplest. Alternatively, consider distributing etags
79 * together with a configuration file containing regexp definitions for etags.
82 char pot_etags_version[] = "@(#) pot revision number is 17.38.1.4";
92 # define NDEBUG /* disable assert */
97 /* On some systems, Emacs defines static as nothing for the sake
98 of unexec. We don't want that here since we don't use unexec. */
100 # ifndef PTR /* for XEmacs */
103 # ifndef __P /* for XEmacs */
104 # define __P(args) args
106 #else /* no config.h */
107 # if defined(__STDC__) && (__STDC__ || defined(__SUNPRO_C))
108 # define __P(args) args /* use prototypes */
109 # define PTR void * /* for generic pointers */
110 # else /* not standard C */
111 # define __P(args) () /* no prototypes */
112 # define const /* remove const for old compilers' sake */
113 # define PTR long * /* don't use void* */
115 #endif /* !HAVE_CONFIG_H */
118 # define _GNU_SOURCE 1 /* enables some compiler checks on GNU */
126 #else /* no standard C headers */
127 extern char *getenv __P((const char *));
128 extern char *strcpy __P((char *, const char *));
129 extern char *strncpy __P((char *, const char *, unsigned long));
130 extern char *strcat __P((char *, const char *));
131 extern char *strncat __P((char *, const char *, unsigned long));
132 extern int strcmp __P((const char *, const char *));
133 extern int strncmp __P((const char *, const char *, unsigned long));
134 extern int system __P((const char *));
135 extern unsigned long strlen __P((const char *));
136 extern void *malloc __P((unsigned long));
137 extern void *realloc __P((void *, unsigned long));
138 extern void exit __P((int));
139 extern void free __P((void *));
140 extern void *memmove __P((void *, const void *, unsigned long));
141 # define EXIT_SUCCESS 0
142 # define EXIT_FAILURE 1
143 #endif /* STDC_HEADERS */
149 extern char *getcwd (char *buf, size_t size);
151 #endif /* HAVE_UNISTD_H */
159 #include <sys/types.h>
160 #include <sys/stat.h>
164 # undef assert /* some systems have a buggy assert.h */
165 # define assert(x) ((void) 0)
168 #if !defined (S_ISREG) && defined (S_IFREG)
169 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
172 #ifndef HAVE_GETOPT_LONG
173 # define NO_LONG_OPTIONS TRUE
174 # define getopt_long(argc,argv,optstr,lopts,lind) getopt (argc, argv, optstr)
176 extern int optind, opterr;
178 # define NO_LONG_OPTIONS FALSE
180 #endif /* HAVE_GETOPT_LONG */
184 /* Define CTAGS to make the program "ctags" compatible with the usual one.
185 Leave it undefined to make the program "etags", which makes emacs-style
186 tag tables and tags typedefs, #defines and struct/union/enum by default. */
194 #define streq(s,t) (assert((s)!=NULL || (t)!=NULL), !strcmp (s, t))
195 #define strcaseeq(s,t) (assert((s)!=NULL && (t)!=NULL), !etags_strcasecmp (s, t))
196 #define strneq(s,t,n) (assert((s)!=NULL || (t)!=NULL), !strncmp (s, t, n))
197 #define strncaseeq(s,t,n) (assert((s)!=NULL && (t)!=NULL), !etags_strncasecmp (s, t, n))
199 #define CHARS 256 /* 2^sizeof(char) */
200 #define CHAR(x) ((unsigned int)(x) & (CHARS - 1))
201 #define iswhite(c) (_wht[CHAR(c)]) /* c is white (see white) */
202 #define notinname(c) (_nin[CHAR(c)]) /* c is not in a name (see nonam) */
203 #define begtoken(c) (_btk[CHAR(c)]) /* c can start token (see begtk) */
204 #define intoken(c) (_itk[CHAR(c)]) /* c can be in token (see midtk) */
205 #define endtoken(c) (_etk[CHAR(c)]) /* c ends tokens (see endtk) */
207 #define ISALNUM(c) isalnum (CHAR(c))
208 #define ISALPHA(c) isalpha (CHAR(c))
209 #define ISDIGIT(c) isdigit (CHAR(c))
210 #define ISLOWER(c) islower (CHAR(c))
212 #define lowcase(c) tolower (CHAR(c))
213 #define upcase(c) toupper (CHAR(c))
217 * xnew, xrnew -- allocate, reallocate storage
219 * SYNOPSIS: Type *xnew (int n, Type);
220 * void xrnew (OldPointer, int n, Type);
223 # include "chkmalloc.h"
224 # define xnew(n,Type) ((Type *) trace_malloc (__FILE__, __LINE__, \
225 (n) * sizeof (Type)))
226 # define xrnew(op,n,Type) ((op) = (Type *) trace_realloc (__FILE__, __LINE__, \
227 (char *) (op), (n) * sizeof (Type)))
229 # define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
230 # define xrnew(op,n,Type) ((op) = (Type *) xrealloc ( \
231 (char *) (op), (n) * sizeof (Type)))
236 #define xstrncpy(d_,s_,l_) \
240 strncat((dst_),(s_),(l_)-1); \
243 typedef void Lang_function __P((FILE *));
247 char *suffix; /* file name suffix for this compressor */
248 char *command; /* takes one arg and decompresses to stdout */
253 char *name; /* language name */
254 char *help; /* detailed help for the language */
255 Lang_function *function; /* parse function */
256 char **suffixes; /* name suffixes of this language's files */
257 char **filenames; /* names of this language's files */
258 char **interpreters; /* interpreters for this language */
259 bool metasource; /* source used to generate other sources */
264 struct fdesc *next; /* for the linked list */
265 char *infname; /* uncompressed input file name */
266 char *infabsname; /* absolute uncompressed input file name */
267 char *infabsdir; /* absolute dir of input file */
268 char *taggedfname; /* file name to write in tagfile */
269 language *lang; /* language of file */
270 char *prop; /* file properties to write in tagfile */
271 bool usecharno; /* etags tags shall contain char number */
272 bool written; /* entry written in the tags file */
275 typedef struct node_st
276 { /* sorting structure */
277 struct node_st *left, *right; /* left and right sons */
278 fdesc *fdp; /* description of file to whom tag belongs */
279 char *name; /* tag name */
280 char *regex; /* search regexp */
281 bool valid; /* write this tag on the tag file */
282 bool is_func; /* function tag: use regexp in CTAGS mode */
283 bool been_warned; /* warning already given for duplicated tag */
284 int lno; /* line number tag is on */
285 long cno; /* character number line starts on */
289 * A `linebuffer' is a structure which holds a line of text.
290 * `readline_internal' reads a line from a stream into a linebuffer
291 * and works regardless of the length of the line.
292 * SIZE is the size of BUFFER, LEN is the length of the string in
293 * BUFFER after readline reads it.
302 /* Used to support mixing of --lang and file names. */
306 at_language, /* a language specification */
307 at_regexp, /* a regular expression */
308 at_filename, /* a file name */
309 at_stdin, /* read from stdin here */
310 at_end /* stop parsing the list */
311 } arg_type; /* argument type */
312 language *lang; /* language associated with the argument */
313 char *what; /* the argument itself */
316 /* Structure defining a regular expression. */
317 typedef struct regexp
319 struct regexp *p_next; /* pointer to next in list */
320 language *lang; /* if set, use only for this language */
321 char *pattern; /* the regexp pattern */
322 char *name; /* tag name */
323 struct re_pattern_buffer *pat; /* the compiled pattern */
324 struct re_registers regs; /* re registers */
325 bool error_signaled; /* already signaled for this regexp */
326 bool force_explicit_name; /* do not allow implict tag name */
327 bool ignore_case; /* ignore case when matching */
328 bool multi_line; /* do a multi-line match on the whole file */
332 /* Many compilers barf on this:
333 Lang_function Ada_funcs;
334 so let's write it this way */
335 static void Ada_funcs __P((FILE *));
336 static void Asm_labels __P((FILE *));
337 static void C_entries __P((int c_ext, FILE *));
338 static void default_C_entries __P((FILE *));
339 static void plain_C_entries __P((FILE *));
340 static void Cjava_entries __P((FILE *));
341 static void Cobol_paragraphs __P((FILE *));
342 static void Cplusplus_entries __P((FILE *));
343 static void Cstar_entries __P((FILE *));
344 static void Erlang_functions __P((FILE *));
345 static void Forth_words __P((FILE *));
346 static void Fortran_functions __P((FILE *));
347 static void HTML_labels __P((FILE *));
348 static void Lisp_functions __P((FILE *));
349 static void Lua_functions __P((FILE *));
350 static void Makefile_targets __P((FILE *));
351 static void Pascal_functions __P((FILE *));
352 static void Perl_functions __P((FILE *));
353 static void PHP_functions __P((FILE *));
354 static void PS_functions __P((FILE *));
355 static void Prolog_functions __P((FILE *));
356 static void Python_functions __P((FILE *));
357 static void Scheme_functions __P((FILE *));
358 static void TeX_commands __P((FILE *));
359 static void Texinfo_nodes __P((FILE *));
360 static void Yacc_entries __P((FILE *));
361 static void just_read_file __P((FILE *));
363 static void print_language_names __P((void));
364 static void print_version __P((void));
365 static void print_help __P((argument *));
366 int main __P((int, char **));
368 static compressor *get_compressor_from_suffix __P((char *, char **));
369 static language *get_language_from_langname __P((const char *));
370 static language *get_language_from_interpreter __P((char *));
371 static language *get_language_from_filename __P((char *, bool));
372 static void readline __P((linebuffer *, FILE *));
373 static long readline_internal __P((linebuffer *, FILE *));
374 static bool nocase_tail __P((char *));
375 static void get_tag __P((char *, char **));
377 static void analyse_regex __P((char *));
378 static void free_regexps __P((void));
379 static void regex_tag_multiline __P((void));
380 static void error __P((const char *, const char *));
381 static void suggest_asking_for_help __P((void));
382 void fatal __P((char *, char *));
383 static void pfatal __P((char *));
384 static void add_node __P((node *, node **));
386 static void init __P((void));
387 static void process_file_name __P((char *, language *));
388 static void process_file __P((FILE *, char *, language *));
389 static void find_entries __P((FILE *));
390 static void free_tree __P((node *));
391 static void free_fdesc __P((fdesc *));
392 static void pfnote __P((char *, bool, char *, int, int, long));
393 static void make_tag __P((char *, int, bool, char *, int, int, long));
394 static void invalidate_nodes __P((fdesc *, node **));
395 static void put_entries __P((node *));
397 static char *concat __P((char *, char *, char *));
398 static char *skip_spaces __P((char *));
399 static char *skip_non_spaces __P((char *));
400 static char *savenstr __P((char *, int));
401 static char *savestr __P((char *));
402 static char *etags_getcwd __P((void));
403 static char *relative_filename __P((char *, char *));
404 static char *absolute_filename __P((char *, char *));
405 static char *absolute_dirname __P((char *, char *));
406 static bool filename_is_absolute __P((char *f));
407 static void canonicalize_filename __P((char *));
408 static void linebuffer_init __P((linebuffer *));
409 static void linebuffer_setlen __P((linebuffer *, int));
410 static PTR xmalloc __P((unsigned int));
411 static PTR xrealloc __P((char *, unsigned int));
416 #define etags_strrchr strrchr
419 * Return the ptr in sp at which the character c last
420 * appears; NULL if not found
422 * Identical to POSIX strrchr, included for portability.
425 etags_strrchr (sp, c)
426 register const char *sp;
429 register const char *r;
442 #define etags_strchr strchr
445 * Return the ptr in sp at which the character c first
446 * appears; NULL if not found
448 * Identical to POSIX strchr, included for portability.
452 register const char *sp;
465 #define etags_strcasecmp strcasecmp
468 * Compare two strings, ignoring case for alphabetic characters.
470 * Same as BSD's strcasecmp, included for portability.
473 etags_strcasecmp (s1, s2)
474 register const char *s1;
475 register const char *s2;
478 && (ISALPHA (*s1) && ISALPHA (*s2)
479 ? lowcase (*s1) == lowcase (*s2)
483 return (ISALPHA (*s1) && ISALPHA (*s2)
484 ? lowcase (*s1) - lowcase (*s2)
490 #define etags_strncasecmp strncasecmp
493 * Compare two strings, ignoring case for alphabetic characters.
494 * Stop after a given number of characters
496 * Same as BSD's strncasecmp, included for portability.
499 etags_strncasecmp (s1, s2, n)
500 register const char *s1;
501 register const char *s2;
504 while (*s1 != '\0' && n-- > 0
505 && (ISALPHA (*s1) && ISALPHA (*s2)
506 ? lowcase (*s1) == lowcase (*s2)
513 return (ISALPHA (*s1) && ISALPHA (*s2)
514 ? lowcase (*s1) - lowcase (*s2)
520 static char searchar = '/'; /* use /.../ searches */
522 static char *tagfile; /* output file */
523 static char *progname; /* name this program was invoked with */
524 static char *cwd; /* current working directory */
525 static char *tagfiledir; /* directory of tagfile */
526 static FILE *tagf; /* ioptr for tags file */
528 static fdesc *fdhead; /* head of file description list */
529 static fdesc *curfdp; /* current file description */
530 static int lineno; /* line number of current line */
531 static long charno; /* current character number */
532 static long linecharno; /* charno of start of current line */
533 static char *dbp; /* pointer to start of current tag */
535 static const int invalidcharno = -1;
537 static node *nodehead; /* the head of the binary tree of tags */
538 static node *last_node; /* the last node created */
540 static linebuffer lb; /* the current line */
541 static linebuffer filebuf; /* a buffer containing the whole file */
542 static linebuffer token_name; /* a buffer containing a tag name */
544 /* boolean "functions" (see init) */
545 static bool _wht[CHARS], _nin[CHARS], _itk[CHARS], _btk[CHARS], _etk[CHARS];
548 *white = " \f\t\n\r\v",
550 *nonam = " \f\t\n\r()=,;", /* look at make_tag before modifying! */
551 /* token ending chars */
552 *endtk = " \t\n\r\"'#()[]{}=-+%*/&|^~!<>;,.:?",
553 /* token starting chars */
554 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
555 /* valid in-token chars */
556 *midtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
558 static bool append_to_tagfile; /* -a: append to tags */
559 /* The next five default to TRUE in C and derived languages. */
560 static bool typedefs; /* -t: create tags for C and Ada typedefs */
561 static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */
562 /* 0 struct/enum/union decls, and C++ */
563 /* member functions. */
564 static bool constantypedefs; /* -d: create tags for C #define, enum */
565 /* constants and variables. */
566 /* -D: opposite of -d. Default under ctags. */
567 static bool globals; /* create tags for global variables */
568 static bool members; /* create tags for C member variables */
569 static bool declarations; /* --declarations: tag them and extern in C&Co*/
570 static bool no_line_directive; /* ignore #line directives (undocumented) */
571 static bool no_duplicates; /* no duplicate tags for ctags (undocumented) */
572 static bool update; /* -u: update tags */
573 static bool vgrind_style; /* -v: create vgrind style index output */
574 static bool no_warnings; /* -w: suppress warnings (undocumented) */
575 static bool cxref_style; /* -x: create cxref style output */
576 static bool cplusplus; /* .[hc] means C++, not C (undocumented) */
577 static bool ignoreindent; /* -I: ignore indentation in C */
578 static bool packages_only; /* --packages-only: in Ada, only tag packages*/
580 /* STDIN is defined in LynxOS system headers */
585 #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */
586 static bool parsing_stdin; /* --parse-stdin used */
588 static regexp *p_head; /* list of all regexps */
589 static bool need_filebuf; /* some regexes are multi-line */
591 #if NO_LONG_OPTIONS == FALSE
592 static struct option longopts[] =
594 { "append", no_argument, NULL, 'a' },
595 { "packages-only", no_argument, &packages_only, TRUE },
596 { "c++", no_argument, NULL, 'C' },
597 { "declarations", no_argument, &declarations, TRUE },
598 { "no-line-directive", no_argument, &no_line_directive, TRUE },
599 { "no-duplicates", no_argument, &no_duplicates, TRUE },
600 { "help", no_argument, NULL, 'h' },
601 { "help", no_argument, NULL, 'H' },
602 { "ignore-indentation", no_argument, NULL, 'I' },
603 { "language", required_argument, NULL, 'l' },
604 { "members", no_argument, &members, TRUE },
605 { "no-members", no_argument, &members, FALSE },
606 { "output", required_argument, NULL, 'o' },
607 { "regex", required_argument, NULL, 'r' },
608 { "no-regex", no_argument, NULL, 'R' },
609 { "ignore-case-regex", required_argument, NULL, 'c' },
610 { "parse-stdin", required_argument, NULL, STDIN },
611 { "version", no_argument, NULL, 'V' },
613 #if CTAGS /* Ctags options */
614 { "backward-search", no_argument, NULL, 'B' },
615 { "cxref", no_argument, NULL, 'x' },
616 { "defines", no_argument, NULL, 'd' },
617 { "globals", no_argument, &globals, TRUE },
618 { "typedefs", no_argument, NULL, 't' },
619 { "typedefs-and-c++", no_argument, NULL, 'T' },
620 { "update", no_argument, NULL, 'u' },
621 { "vgrind", no_argument, NULL, 'v' },
622 { "no-warn", no_argument, NULL, 'w' },
624 #else /* Etags options */
625 { "no-defines", no_argument, NULL, 'D' },
626 { "no-globals", no_argument, &globals, FALSE },
627 { "include", required_argument, NULL, 'i' },
634 static compressor compressors[] =
636 { "z", "gzip -d -c"},
637 { "Z", "gzip -d -c"},
638 { "gz", "gzip -d -c"},
639 { "GZ", "gzip -d -c"},
640 { "bz2", "bzip2 -d -c" },
649 static char *Ada_suffixes [] =
650 { "ads", "adb", "ada", NULL };
651 static char Ada_help [] =
652 "In Ada code, functions, procedures, packages, tasks and types are\n\
653 tags. Use the `--packages-only' option to create tags for\n\
655 Ada tag names have suffixes indicating the type of entity:\n\
656 Entity type: Qualifier:\n\
657 ------------ ----------\n\
664 Thus, `M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\
665 body of the package `bidule', while `M-x find-tag <RET> bidule <RET>'\n\
666 will just search for any tag `bidule'.";
669 static char *Asm_suffixes [] =
670 { "a", /* Unix assembler */
671 "asm", /* Microcontroller assembly */
672 "def", /* BSO/Tasking definition includes */
673 "inc", /* Microcontroller include files */
674 "ins", /* Microcontroller include files */
675 "s", "sa", /* Unix assembler */
676 "S", /* cpp-processed Unix assembler */
677 "src", /* BSO/Tasking C compiler output */
680 static char Asm_help [] =
681 "In assembler code, labels appearing at the beginning of a line,\n\
682 followed by a colon, are tags.";
685 /* Note that .c and .h can be considered C++, if the --c++ flag was
686 given, or if the `class' or `template' keywords are met inside the file.
687 That is why default_C_entries is called for these. */
688 static char *default_C_suffixes [] =
690 #if CTAGS /* C help for Ctags */
691 static char default_C_help [] =
692 "In C code, any C function is a tag. Use -t to tag typedefs.\n\
693 Use -T to tag definitions of `struct', `union' and `enum'.\n\
694 Use -d to tag `#define' macro definitions and `enum' constants.\n\
695 Use --globals to tag global variables.\n\
696 You can tag function declarations and external variables by\n\
697 using `--declarations', and struct members by using `--members'.";
698 #else /* C help for Etags */
699 static char default_C_help [] =
700 "In C code, any C function or typedef is a tag, and so are\n\
701 definitions of `struct', `union' and `enum'. `#define' macro\n\
702 definitions and `enum' constants are tags unless you specify\n\
703 `--no-defines'. Global variables are tags unless you specify\n\
704 `--no-globals' and so are struct members unless you specify\n\
705 `--no-members'. Use of `--no-globals', `--no-defines' and\n\
706 `--no-members' can make the tags table file much smaller.\n\
707 You can tag function declarations and external variables by\n\
708 using `--declarations'.";
709 #endif /* C help for Ctags and Etags */
711 static char *Cplusplus_suffixes [] =
712 { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx",
713 "M", /* Objective C++ */
714 "pdb", /* Postscript with C syntax */
716 static char Cplusplus_help [] =
717 "In C++ code, all the tag constructs of C code are tagged. (Use\n\
718 --help --lang=c --lang=c++ for full help.)\n\
719 In addition to C tags, member functions are also recognized. Member\n\
720 variables are recognized unless you use the `--no-members' option.\n\
721 Tags for variables and functions in classes are named `CLASS::VARIABLE'\n\
722 and `CLASS::FUNCTION'. `operator' definitions have tag names like\n\
725 static char *Cjava_suffixes [] =
727 static char Cjava_help [] =
728 "In Java code, all the tags constructs of C and C++ code are\n\
729 tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)";
732 static char *Cobol_suffixes [] =
733 { "COB", "cob", NULL };
734 static char Cobol_help [] =
735 "In Cobol code, tags are paragraph names; that is, any word\n\
736 starting in column 8 and followed by a period.";
738 static char *Cstar_suffixes [] =
739 { "cs", "hs", NULL };
741 static char *Erlang_suffixes [] =
742 { "erl", "hrl", NULL };
743 static char Erlang_help [] =
744 "In Erlang code, the tags are the functions, records and macros\n\
745 defined in the file.";
747 char *Forth_suffixes [] =
748 { "fth", "tok", NULL };
749 static char Forth_help [] =
750 "In Forth code, tags are words defined by `:',\n\
751 constant, code, create, defer, value, variable, buffer:, field.";
753 static char *Fortran_suffixes [] =
754 { "F", "f", "f90", "for", NULL };
755 static char Fortran_help [] =
756 "In Fortran code, functions, subroutines and block data are tags.";
758 static char *HTML_suffixes [] =
759 { "htm", "html", "shtml", NULL };
760 static char HTML_help [] =
761 "In HTML input files, the tags are the `title' and the `h1', `h2',\n\
762 `h3' headers. Also, tags are `name=' in anchors and all\n\
763 occurrences of `id='.";
765 static char *Lisp_suffixes [] =
766 { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL };
767 static char Lisp_help [] =
768 "In Lisp code, any function defined with `defun', any variable\n\
769 defined with `defvar' or `defconst', and in general the first\n\
770 argument of any expression that starts with `(def' in column zero\n\
773 static char *Lua_suffixes [] =
774 { "lua", "LUA", NULL };
775 static char Lua_help [] =
776 "In Lua scripts, all functions are tags.";
778 static char *Makefile_filenames [] =
779 { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL};
780 static char Makefile_help [] =
781 "In makefiles, targets are tags; additionally, variables are tags\n\
782 unless you specify `--no-globals'.";
784 static char *Objc_suffixes [] =
785 { "lm", /* Objective lex file */
786 "m", /* Objective C file */
788 static char Objc_help [] =
789 "In Objective C code, tags include Objective C definitions for classes,\n\
790 class categories, methods and protocols. Tags for variables and\n\
791 functions in classes are named `CLASS::VARIABLE' and `CLASS::FUNCTION'.\n\
792 (Use --help --lang=c --lang=objc --lang=java for full help.)";
794 static char *Pascal_suffixes [] =
795 { "p", "pas", NULL };
796 static char Pascal_help [] =
797 "In Pascal code, the tags are the functions and procedures defined\n\
799 /* " // this is for working around an Emacs highlighting bug... */
801 static char *Perl_suffixes [] =
802 { "pl", "pm", NULL };
803 static char *Perl_interpreters [] =
804 { "perl", "@PERL@", NULL };
805 static char Perl_help [] =
806 "In Perl code, the tags are the packages, subroutines and variables\n\
807 defined by the `package', `sub', `my' and `local' keywords. Use\n\
808 `--globals' if you want to tag global variables. Tags for\n\
809 subroutines are named `PACKAGE::SUB'. The name for subroutines\n\
810 defined in the default package is `main::SUB'.";
812 static char *PHP_suffixes [] =
813 { "php", "php3", "php4", NULL };
814 static char PHP_help [] =
815 "In PHP code, tags are functions, classes and defines. Unless you use\n\
816 the `--no-members' option, vars are tags too.";
818 static char *plain_C_suffixes [] =
819 { "pc", /* Pro*C file */
822 static char *PS_suffixes [] =
823 { "ps", "psw", NULL }; /* .psw is for PSWrap */
824 static char PS_help [] =
825 "In PostScript code, the tags are the functions.";
827 static char *Prolog_suffixes [] =
829 static char Prolog_help [] =
830 "In Prolog code, tags are predicates and rules at the beginning of\n\
833 static char *Python_suffixes [] =
835 static char Python_help [] =
836 "In Python code, `def' or `class' at the beginning of a line\n\
839 /* Can't do the `SCM' or `scm' prefix with a version number. */
840 static char *Scheme_suffixes [] =
841 { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL };
842 static char Scheme_help [] =
843 "In Scheme code, tags include anything defined with `def' or with a\n\
844 construct whose name starts with `def'. They also include\n\
845 variables set with `set!' at top level in the file.";
847 static char *TeX_suffixes [] =
848 { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL };
849 static char TeX_help [] =
850 "In LaTeX text, the argument of any of the commands `\\chapter',\n\
851 `\\section', `\\subsection', `\\subsubsection', `\\eqno', `\\label',\n\
852 `\\ref', `\\cite', `\\bibitem', `\\part', `\\appendix', `\\entry',\n\
853 `\\index', `\\def', `\\newcommand', `\\renewcommand',\n\
854 `\\newenvironment' or `\\renewenvironment' is a tag.\n\
856 Other commands can be specified by setting the environment variable\n\
857 `TEXTAGS' to a colon-separated list like, for example,\n\
858 TEXTAGS=\"mycommand:myothercommand\".";
861 static char *Texinfo_suffixes [] =
862 { "texi", "texinfo", "txi", NULL };
863 static char Texinfo_help [] =
864 "for texinfo files, lines starting with @node are tagged.";
866 static char *Yacc_suffixes [] =
867 { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */
868 static char Yacc_help [] =
869 "In Bison or Yacc input files, each rule defines as a tag the\n\
870 nonterminal it constructs. The portions of the file that contain\n\
871 C code are parsed as C code (use --help --lang=c --lang=yacc\n\
874 static char auto_help [] =
875 "`auto' is not a real language, it indicates to use\n\
876 a default language for files base on file name suffix and file contents.";
878 static char none_help [] =
879 "`none' is not a real language, it indicates to only do\n\
880 regexp processing on files.";
882 static char no_lang_help [] =
883 "No detailed help available for this language.";
887 * Table of languages.
889 * It is ok for a given function to be listed under more than one
890 * name. I just didn't.
893 static language lang_names [] =
895 { "ada", Ada_help, Ada_funcs, Ada_suffixes },
896 { "asm", Asm_help, Asm_labels, Asm_suffixes },
897 { "c", default_C_help, default_C_entries, default_C_suffixes },
898 { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes },
899 { "c*", no_lang_help, Cstar_entries, Cstar_suffixes },
900 { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes },
901 { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes },
902 { "forth", Forth_help, Forth_words, Forth_suffixes },
903 { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes },
904 { "html", HTML_help, HTML_labels, HTML_suffixes },
905 { "java", Cjava_help, Cjava_entries, Cjava_suffixes },
906 { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes },
907 { "lua", Lua_help, Lua_functions, Lua_suffixes },
908 { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames},
909 { "objc", Objc_help, plain_C_entries, Objc_suffixes },
910 { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes },
911 { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters},
912 { "php", PHP_help, PHP_functions, PHP_suffixes },
913 { "postscript",PS_help, PS_functions, PS_suffixes },
914 { "proc", no_lang_help, plain_C_entries, plain_C_suffixes },
915 { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes },
916 { "python", Python_help, Python_functions, Python_suffixes },
917 { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes },
918 { "tex", TeX_help, TeX_commands, TeX_suffixes },
919 { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes },
920 { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,TRUE},
921 { "auto", auto_help }, /* default guessing scheme */
922 { "none", none_help, just_read_file }, /* regexp matching only */
923 { NULL } /* end of list */
928 print_language_names ()
933 puts ("\nThese are the currently supported languages, along with the\n\
934 default file names and dot suffixes:");
935 for (lang = lang_names; lang->name != NULL; lang++)
937 printf (" %-*s", 10, lang->name);
938 if (lang->filenames != NULL)
939 for (name = lang->filenames; *name != NULL; name++)
940 printf (" %s", *name);
941 if (lang->suffixes != NULL)
942 for (ext = lang->suffixes; *ext != NULL; ext++)
943 printf (" .%s", *ext);
946 puts ("where `auto' means use default language for files based on file\n\
947 name suffix, and `none' means only do regexp processing on files.\n\
948 If no language is specified and no matching suffix is found,\n\
949 the first line of the file is read for a sharp-bang (#!) sequence\n\
950 followed by the name of an interpreter. If no such sequence is found,\n\
951 Fortran is tried first; if no tags are found, C is tried next.\n\
952 When parsing any C file, a \"class\" or \"template\" keyword\n\
954 puts ("Compressed files are supported using gzip and bzip2.\n\
956 For detailed help on a given language use, for example,\n\
957 etags --help --lang=ada.");
961 # define EMACS_NAME "standalone"
964 # define VERSION "17.38.1.4"
967 # define E_VERSION EMACS_VERSION
969 # define E_VERSION VERSION
974 /* Makes it easier to update automatically. */
975 char emacs_copyright[] = "Copyright (C) 2008 Free Software Foundation, Inc.";
977 printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, E_VERSION);
978 puts (pot_etags_version);
979 puts (emacs_copyright);
980 puts ("This program is distributed under the terms in ETAGS.README");
985 #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP
986 # define PRINT_UNDOCUMENTED_OPTIONS_HELP FALSE
990 print_help (argbuffer)
993 bool help_for_lang = FALSE;
995 for (; argbuffer->arg_type != at_end; argbuffer++)
996 if (argbuffer->arg_type == at_language)
1000 puts (argbuffer->lang->help);
1001 help_for_lang = TRUE;
1005 exit (EXIT_SUCCESS);
1007 printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\
1009 These are the options accepted by %s.\n", progname, progname);
1010 if (NO_LONG_OPTIONS)
1011 puts ("WARNING: long option names do not work with this executable,\n\
1012 as it is not linked with GNU getopt.");
1014 puts ("You may use unambiguous abbreviations for the long option names.");
1015 puts (" A - as file name means read names from stdin (one per line).\n\
1016 Absolute names are stored in the output file as they are.\n\
1017 Relative ones are stored relative to the output file's directory.\n");
1019 puts ("-a, --append\n\
1020 Append tag entries to existing tags file.");
1022 puts ("--packages-only\n\
1023 For Ada files, only generate tags for packages.");
1026 puts ("-B, --backward-search\n\
1027 Write the search commands for the tag entries using '?', the\n\
1028 backward-search command instead of '/', the forward-search command.");
1030 /* This option is mostly obsolete, because etags can now automatically
1031 detect C++. Retained for backward compatibility and for debugging and
1032 experimentation. In principle, we could want to tag as C++ even
1033 before any "class" or "template" keyword.
1035 Treat files whose name suffix defaults to C language as C++ files.");
1038 puts ("--declarations\n\
1039 In C and derived languages, create tags for function declarations,");
1041 puts ("\tand create tags for extern variables if --globals is used.");
1044 ("\tand create tags for extern variables unless --no-globals is used.");
1047 puts ("-d, --defines\n\
1048 Create tag entries for C #define constants and enum constants, too.");
1050 puts ("-D, --no-defines\n\
1051 Don't create tag entries for C #define constants and enum constants.\n\
1052 This makes the tags file smaller.");
1055 puts ("-i FILE, --include=FILE\n\
1056 Include a note in tag file indicating that, when searching for\n\
1057 a tag, one should also consult the tags file FILE after\n\
1058 checking the current file.");
1060 puts ("-l LANG, --language=LANG\n\
1061 Force the following files to be considered as written in the\n\
1062 named language up to the next --language=LANG option.");
1066 Create tag entries for global variables in some languages.");
1068 puts ("--no-globals\n\
1069 Do not create tag entries for global variables in some\n\
1070 languages. This makes the tags file smaller.");
1072 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1073 puts ("--no-line-directive\n\
1074 Ignore #line preprocessor directives in C and derived languages.");
1078 Create tag entries for members of structures in some languages.");
1080 puts ("--no-members\n\
1081 Do not create tag entries for members of structures\n\
1082 in some languages.");
1084 puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\
1085 Make a tag for each line matching a regular expression pattern\n\
1086 in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\
1087 files only. REGEXFILE is a file containing one REGEXP per line.\n\
1088 REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\
1089 optional. The TAGREGEXP pattern is anchored (as if preceded by ^).");
1090 puts (" If TAGNAME/ is present, the tags created are named.\n\
1091 For example Tcl named tags can be created with:\n\
1092 --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\
1093 MODS are optional one-letter modifiers: `i' means to ignore case,\n\
1094 `m' means to allow multi-line matches, `s' implies `m' and\n\
1095 causes dot to match any character, including newline.");
1097 puts ("-R, --no-regex\n\
1098 Don't create tags from regexps for the following files.");
1100 puts ("-I, --ignore-indentation\n\
1101 In C and C++ do not assume that a closing brace in the first\n\
1102 column is the final brace of a function or structure definition.");
1104 puts ("-o FILE, --output=FILE\n\
1105 Write the tags to FILE.");
1107 puts ("--parse-stdin=NAME\n\
1108 Read from standard input and record tags as belonging to file NAME.");
1112 puts ("-t, --typedefs\n\
1113 Generate tag entries for C and Ada typedefs.");
1114 puts ("-T, --typedefs-and-c++\n\
1115 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
1116 and C++ member functions.");
1120 puts ("-u, --update\n\
1121 Update the tag entries for the given files, leaving tag\n\
1122 entries for other files in place. Currently, this is\n\
1123 implemented by deleting the existing entries for the given\n\
1124 files and then rewriting the new entries at the end of the\n\
1125 tags file. It is often faster to simply rebuild the entire\n\
1126 tag file than to use this.");
1130 puts ("-v, --vgrind\n\
1131 Print on the standard output an index of items intended for\n\
1132 human consumption, similar to the output of vgrind. The index\n\
1133 is sorted, and gives the page number of each item.");
1135 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1136 puts ("-w, --no-duplicates\n\
1137 Do not create duplicate tag entries, for compatibility with\n\
1138 traditional ctags.");
1140 if (PRINT_UNDOCUMENTED_OPTIONS_HELP)
1141 puts ("-w, --no-warn\n\
1142 Suppress warning messages about duplicate tag entries.");
1144 puts ("-x, --cxref\n\
1145 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
1146 The output uses line numbers instead of page numbers, but\n\
1147 beyond that the differences are cosmetic; try both to see\n\
1151 puts ("-V, --version\n\
1152 Print the version of the program.\n\
1154 Print this help message.\n\
1155 Followed by one or more `--language' options prints detailed\n\
1156 help about tag generation for the specified languages.");
1158 print_language_names ();
1161 puts ("Report bugs to bug-gnu-emacs@gnu.org");
1163 exit (EXIT_SUCCESS);
1173 unsigned int nincluded_files;
1174 char **included_files;
1175 argument *argbuffer;
1176 int current_arg, file_count;
1177 linebuffer filename_lb;
1178 bool help_asked = FALSE;
1184 nincluded_files = 0;
1185 included_files = xnew (argc, char *);
1189 /* Allocate enough no matter what happens. Overkill, but each one
1191 argbuffer = xnew (argc, argument);
1194 * Always find typedefs and structure tags.
1195 * Also default to find macro constants, enum constants, struct
1196 * members and global variables. Do it for both etags and ctags.
1198 typedefs = typedefs_or_cplusplus = constantypedefs = TRUE;
1199 globals = members = TRUE;
1201 /* When the optstring begins with a '-' getopt_long does not rearrange the
1202 non-options arguments to be at the end, but leaves them alone. */
1203 optstring = concat (NO_LONG_OPTIONS ? "" : "-",
1204 "ac:Cf:Il:o:r:RSVhH",
1205 (CTAGS) ? "BxdtTuvw" : "Di:");
1207 while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF)
1211 /* If getopt returns 0, then it has already processed a
1212 long-named option. We should do nothing. */
1216 /* This means that a file name has been seen. Record it. */
1217 argbuffer[current_arg].arg_type = at_filename;
1218 argbuffer[current_arg].what = optarg;
1224 /* Parse standard input. Idea by Vivek <vivek@etla.org>. */
1225 argbuffer[current_arg].arg_type = at_stdin;
1226 argbuffer[current_arg].what = optarg;
1230 fatal ("cannot parse standard input more than once", (char *)NULL);
1231 parsing_stdin = TRUE;
1234 /* Common options. */
1235 case 'a': append_to_tagfile = TRUE; break;
1236 case 'C': cplusplus = TRUE; break;
1237 case 'f': /* for compatibility with old makefiles */
1241 error ("-o option may only be given once.", (char *)NULL);
1242 suggest_asking_for_help ();
1248 case 'S': /* for backward compatibility */
1249 ignoreindent = TRUE;
1253 language *lang = get_language_from_langname (optarg);
1256 argbuffer[current_arg].lang = lang;
1257 argbuffer[current_arg].arg_type = at_language;
1263 /* Backward compatibility: support obsolete --ignore-case-regexp. */
1264 optarg = concat (optarg, "i", ""); /* memory leak here */
1267 argbuffer[current_arg].arg_type = at_regexp;
1268 argbuffer[current_arg].what = optarg;
1272 argbuffer[current_arg].arg_type = at_regexp;
1273 argbuffer[current_arg].what = NULL;
1285 case 'D': constantypedefs = FALSE; break;
1286 case 'i': included_files[nincluded_files++] = optarg; break;
1288 /* Ctags options. */
1289 case 'B': searchar = '?'; break;
1290 case 'd': constantypedefs = TRUE; break;
1291 case 't': typedefs = TRUE; break;
1292 case 'T': typedefs = typedefs_or_cplusplus = TRUE; break;
1293 case 'u': update = TRUE; break;
1294 case 'v': vgrind_style = TRUE; /*FALLTHRU*/
1295 case 'x': cxref_style = TRUE; break;
1296 case 'w': no_warnings = TRUE; break;
1298 suggest_asking_for_help ();
1302 /* No more options. Store the rest of arguments. */
1303 for (; optind < argc; optind++)
1305 argbuffer[current_arg].arg_type = at_filename;
1306 argbuffer[current_arg].what = argv[optind];
1311 argbuffer[current_arg].arg_type = at_end;
1314 print_help (argbuffer);
1317 if (nincluded_files == 0 && file_count == 0)
1319 error ("no input files specified.", (char *)NULL);
1320 suggest_asking_for_help ();
1324 if (tagfile == NULL)
1325 tagfile = savestr (CTAGS ? "tags" : "TAGS");
1326 cwd = etags_getcwd (); /* the current working directory */
1327 if (cwd[strlen (cwd) - 1] != '/')
1330 cwd = concat (oldcwd, "/", "");
1334 /* Compute base directory for relative file names. */
1335 if (streq (tagfile, "-")
1336 || strneq (tagfile, "/dev/", 5))
1337 tagfiledir = cwd; /* relative file names are relative to cwd */
1340 canonicalize_filename (tagfile);
1341 tagfiledir = absolute_dirname (tagfile, cwd);
1344 init (); /* set up boolean "functions" */
1346 linebuffer_init (&lb);
1347 linebuffer_init (&filename_lb);
1348 linebuffer_init (&filebuf);
1349 linebuffer_init (&token_name);
1353 if (streq (tagfile, "-"))
1358 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1364 * Loop through files finding functions.
1366 for (i = 0; i < current_arg; i++)
1368 static language *lang; /* non-NULL if language is forced */
1371 switch (argbuffer[i].arg_type)
1374 lang = argbuffer[i].lang;
1377 analyse_regex (argbuffer[i].what);
1380 this_file = argbuffer[i].what;
1381 /* Input file named "-" means read file names from stdin
1382 (one per line) and use them. */
1383 if (streq (this_file, "-"))
1386 fatal ("cannot parse standard input AND read file names from it",
1388 while (readline_internal (&filename_lb, stdin) > 0)
1389 process_file_name (filename_lb.buffer, lang);
1392 process_file_name (this_file, lang);
1395 this_file = argbuffer[i].what;
1396 process_file (stdin, this_file, lang);
1408 free (filebuf.buffer);
1409 free (token_name.buffer);
1411 if (!CTAGS || cxref_style)
1413 /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */
1414 put_entries (nodehead);
1415 free_tree (nodehead);
1421 /* Output file entries that have no tags. */
1422 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1424 fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname);
1426 while (nincluded_files-- > 0)
1427 fprintf (tagf, "\f\n%s,include\n", *included_files++);
1429 if (fclose (tagf) == EOF)
1433 exit (EXIT_SUCCESS);
1436 /* From here on, we are in (CTAGS && !cxref_style) */
1442 for (i = 0; i < current_arg; ++i)
1444 switch (argbuffer[i].arg_type)
1453 continue; /* the for loop */
1455 len = snprintf (cmd, sizeof(cmd),
1456 "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
1457 tagfile, argbuffer[i].what, tagfile);
1458 if (len >= 0 && (size_t)len < sizeof(cmd))
1459 fatal ("failed to build shell command line", (char *)NULL);
1460 if (system (cmd) != EXIT_SUCCESS)
1461 fatal ("failed to execute shell command", (char *)NULL);
1463 append_to_tagfile = TRUE;
1466 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
1469 put_entries (nodehead); /* write all the tags (CTAGS) */
1470 free_tree (nodehead);
1472 if (fclose (tagf) == EOF)
1476 if (append_to_tagfile || update)
1478 char cmd[2*BUFSIZ+20];
1479 /* Maybe these should be used:
1480 setenv ("LC_COLLATE", "C", 1);
1481 setenv ("LC_ALL", "C", 1); */
1482 int len = snprintf (cmd, sizeof(cmd),
1483 "sort -u -o %.*s %.*s",
1486 if (len >= 0 && (size_t)len < sizeof(cmd))
1487 fatal("failed to build sort shell command line",
1489 exit (system (cmd));
1491 return EXIT_SUCCESS;
1496 * Return a compressor given the file name. If EXTPTR is non-zero,
1497 * return a pointer into FILE where the compressor-specific
1498 * extension begins. If no compressor is found, NULL is returned
1499 * and EXTPTR is not significant.
1500 * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998)
1503 get_compressor_from_suffix (file, extptr)
1508 char *slash, *suffix;
1510 /* File has been processed by canonicalize_filename,
1511 so we don't need to consider backslashes on DOS_NT. */
1512 slash = etags_strrchr (file, '/');
1513 suffix = etags_strrchr (file, '.');
1514 if (suffix == NULL || suffix < slash)
1519 /* Let those poor souls who live with DOS 8+3 file name limits get
1520 some solace by treating foo.cgz as if it were foo.c.gz, etc.
1521 Only the first do loop is run if not MSDOS */
1524 for (compr = compressors; compr->suffix != NULL; compr++)
1525 if (streq (compr->suffix, suffix))
1528 break; /* do it only once: not really a loop */
1531 } while (*suffix != '\0');
1538 * Return a language given the name.
1541 get_language_from_langname (name)
1547 error ("empty language name", (char *)NULL);
1550 for (lang = lang_names; lang->name != NULL; lang++)
1551 if (streq (name, lang->name))
1553 error ("unknown language \"%s\"", name);
1561 * Return a language given the interpreter name.
1564 get_language_from_interpreter (interpreter)
1570 if (interpreter == NULL)
1572 for (lang = lang_names; lang->name != NULL; lang++)
1573 if (lang->interpreters != NULL)
1574 for (iname = lang->interpreters; *iname != NULL; iname++)
1575 if (streq (*iname, interpreter))
1584 * Return a language given the file name.
1587 get_language_from_filename (file, case_sensitive)
1589 bool case_sensitive;
1592 char **name, **ext, *suffix;
1594 /* Try whole file name first. */
1595 for (lang = lang_names; lang->name != NULL; lang++)
1596 if (lang->filenames != NULL)
1597 for (name = lang->filenames; *name != NULL; name++)
1598 if ((case_sensitive)
1599 ? streq (*name, file)
1600 : strcaseeq (*name, file))
1603 /* If not found, try suffix after last dot. */
1604 suffix = etags_strrchr (file, '.');
1608 for (lang = lang_names; lang->name != NULL; lang++)
1609 if (lang->suffixes != NULL) {
1610 for (ext = lang->suffixes; *ext != NULL; ext++)
1611 if (case_sensitive) {
1612 if (streq (*ext, suffix))
1614 } else if (strcaseeq (*ext, suffix))
1622 * This routine is called on each file argument.
1625 process_file_name (file, lang)
1629 struct stat stat_buf;
1632 compressor *compr = NULL;
1633 char *compressed_name = NULL,
1634 *uncompressed_name = NULL;
1639 canonicalize_filename (file);
1640 if (streq (file, tagfile) && !streq (tagfile, "-"))
1642 error ("skipping inclusion of %s in self.", file);
1645 if ( get_compressor_from_suffix (file, &ext) == NULL)
1647 real_name = uncompressed_name = savestr (file);
1651 real_name = compressed_name = savestr (file);
1652 uncompressed_name = savenstr (file, ext - file);
1655 /* If the canonicalized uncompressed name
1656 has already been dealt with, skip it silently. */
1657 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
1659 assert (fdp->infname != NULL);
1660 if (streq (uncompressed_name, fdp->infname))
1664 compr = compressors;
1666 /* First try to open ... */
1667 if (real_name == compressed_name)
1669 char *cmd = concat (compr->command, " ", real_name);
1670 inf = (FILE *) popen (cmd, "r");
1674 inf = fopen (real_name, "r");
1675 if ( inf != NULL ) {
1676 /* Open was successfull, check it is a regular file */
1677 if (stat (real_name, &stat_buf) == 0 &&
1678 !S_ISREG (stat_buf.st_mode))
1680 error ("skipping %s: it is not a regular file.",
1686 /* Not else from previous if because inner check may reset inf
1687 to NULL, at which case we will want to try the next?
1688 compressed filename... */
1689 if ( inf == NULL ) {
1690 /* Reset real_name and try with a different name. */
1691 free(compressed_name);
1693 if (compressed_name != NULL)
1694 /* try with the given suffix */
1696 compressed_name = NULL;
1697 real_name = uncompressed_name;
1699 else if ( compr && compr->suffix != NULL )
1700 /* try all possible suffixes */
1702 compressed_name = concat (file, ".", compr->suffix);
1703 real_name = compressed_name;
1707 } while( inf == NULL && real_name != NULL);
1714 process_file (inf, uncompressed_name, lang);
1716 if (real_name == compressed_name)
1717 retval = pclose (inf);
1719 retval = fclose (inf);
1724 free (compressed_name);
1725 free (uncompressed_name);
1732 process_file (fh, fn, lang)
1737 static const fdesc emptyfdesc;
1740 /* Create a new input file description entry. */
1741 fdp = xnew (1, fdesc);
1744 fdp->infname = savestr (fn);
1746 fdp->infabsname = absolute_filename (fn, cwd);
1747 fdp->infabsdir = absolute_dirname (fn, cwd);
1748 if (filename_is_absolute (fn))
1750 /* An absolute file name. Canonicalize it. */
1751 fdp->taggedfname = absolute_filename (fn, NULL);
1755 /* A file name relative to cwd. Make it relative
1756 to the directory of the tags file. */
1757 fdp->taggedfname = relative_filename (fn, tagfiledir);
1759 fdp->usecharno = TRUE; /* use char position when making tags */
1761 fdp->written = FALSE; /* not written on tags file yet */
1764 curfdp = fdhead; /* the current file description */
1768 /* If not Ctags, and if this is not metasource and if it contained no #line
1769 directives, we can write the tags and free all nodes pointing to
1772 && curfdp->usecharno /* no #line directives in this file */
1773 && !curfdp->lang->metasource)
1777 /* Look for the head of the sublist relative to this file. See add_node
1778 for the structure of the node tree. */
1780 for (np = nodehead; np != NULL; prev = np, np = np->left)
1781 if (np->fdp == curfdp)
1784 /* If we generated tags for this file, write and delete them. */
1787 /* This is the head of the last sublist, if any. The following
1788 instructions depend on this being true. */
1789 assert (np->left == NULL);
1791 assert (fdhead == curfdp);
1792 assert (last_node->fdp == curfdp);
1793 put_entries (np); /* write tags for file curfdp->taggedfname */
1794 free_tree (np); /* remove the written nodes */
1796 nodehead = NULL; /* no nodes left */
1798 prev->left = NULL; /* delete the pointer to the sublist */
1804 * This routine sets up the boolean pseudo-functions which work
1805 * by setting boolean flags dependent upon the corresponding character.
1806 * Every char which is NOT in that string is not a white char. Therefore,
1807 * all of the array "_wht" is set to FALSE, and then the elements
1808 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1809 * of a char is TRUE if it is the string "white", else FALSE.
1817 for (i = 0; i < CHARS; i++)
1818 iswhite(i) = notinname(i) = begtoken(i) = intoken(i) = endtoken(i) = FALSE;
1819 for (sp = white; *sp != '\0'; sp++) iswhite (*sp) = TRUE;
1820 for (sp = nonam; *sp != '\0'; sp++) notinname (*sp) = TRUE;
1821 notinname('\0') = notinname('\n');
1822 for (sp = begtk; *sp != '\0'; sp++) begtoken (*sp) = TRUE;
1823 begtoken('\0') = begtoken('\n');
1824 for (sp = midtk; *sp != '\0'; sp++) intoken (*sp) = TRUE;
1825 intoken('\0') = intoken('\n');
1826 for (sp = endtk; *sp != '\0'; sp++) endtoken (*sp) = TRUE;
1827 endtoken('\0') = endtoken('\n');
1831 * This routine opens the specified file and calls the function
1832 * which finds the function and type definitions.
1839 language *lang = curfdp->lang;
1840 Lang_function *parser = NULL;
1842 /* If user specified a language, use it. */
1843 if (lang != NULL && lang->function != NULL)
1845 parser = lang->function;
1848 /* Else try to guess the language given the file name. */
1851 lang = get_language_from_filename (curfdp->infname, TRUE);
1852 if (lang != NULL && lang->function != NULL)
1854 curfdp->lang = lang;
1855 parser = lang->function;
1859 /* Else look for sharp-bang as the first two characters. */
1861 && readline_internal (&lb, inf) > 0
1863 && lb.buffer[0] == '#'
1864 && lb.buffer[1] == '!')
1868 /* Set lp to point at the first char after the last slash in the
1869 line or, if no slashes, at the first nonblank. Then set cp to
1870 the first successive blank and terminate the string. */
1871 lp = etags_strrchr (lb.buffer+2, '/');
1875 lp = skip_spaces (lb.buffer + 2);
1876 cp = skip_non_spaces (lp);
1879 if (strlen (lp) > 0)
1881 lang = get_language_from_interpreter (lp);
1882 if (lang != NULL && lang->function != NULL)
1884 curfdp->lang = lang;
1885 parser = lang->function;
1890 /* We rewind here, even if inf may be a pipe. We fail if the
1891 length of the first line is longer than the pipe block size,
1892 which is unlikely. */
1895 /* Else try to guess the language given the case insensitive file name. */
1898 lang = get_language_from_filename (curfdp->infname, FALSE);
1899 if (lang != NULL && lang->function != NULL)
1901 curfdp->lang = lang;
1902 parser = lang->function;
1906 /* Else try Fortran or C. */
1909 node *old_last_node = last_node;
1911 curfdp->lang = get_language_from_langname ("fortran");
1914 if (old_last_node == last_node)
1915 /* No Fortran entries found. Try C. */
1917 /* We do not tag if rewind fails.
1918 Only the file name will be recorded in the tags file. */
1920 curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c");
1926 if (!no_line_directive
1927 && curfdp->lang != NULL && curfdp->lang->metasource)
1928 /* It may be that this is a bingo.y file, and we already parsed a bingo.c
1929 file, or anyway we parsed a file that is automatically generated from
1930 this one. If this is the case, the bingo.c file contained #line
1931 directives that generated tags pointing to this file. Let's delete
1932 them all before parsing this file, which is the real source. */
1934 fdesc **fdpp = &fdhead;
1935 while (*fdpp != NULL)
1937 && streq ((*fdpp)->taggedfname, curfdp->taggedfname))
1938 /* We found one of those! We must delete both the file description
1939 and all tags referring to it. */
1941 fdesc *badfdp = *fdpp;
1943 /* Delete the tags referring to badfdp->taggedfname
1944 that were obtained from badfdp->infname. */
1945 invalidate_nodes (badfdp, &nodehead);
1947 *fdpp = badfdp->next; /* remove the bad description from the list */
1948 free_fdesc (badfdp);
1951 fdpp = &(*fdpp)->next; /* advance the list pointer */
1954 assert (parser != NULL);
1956 /* Generic initialisations before reading from file. */
1957 linebuffer_setlen (&filebuf, 0); /* reset the file buffer */
1959 /* Generic initialisations before parsing file with readline. */
1960 lineno = 0; /* reset global line number */
1961 charno = 0; /* reset global char number */
1962 linecharno = 0; /* reset global char number of line start */
1966 regex_tag_multiline ();
1971 * Check whether an implicitly named tag should be created,
1972 * then call `pfnote'.
1973 * NAME is a string that is internally copied by this function.
1975 * TAGS format specification
1976 * Idea by Sam Kendall <kendall@mv.mv.com> (1997)
1977 * The following is explained in some more detail in etc/ETAGS.EBNF.
1979 * make_tag creates tags with "implicit tag names" (unnamed tags)
1980 * if the following are all true, assuming NONAM=" \f\t\n\r()=,;":
1981 * 1. NAME does not contain any of the characters in NONAM;
1982 * 2. LINESTART contains name as either a rightmost, or rightmost but
1983 * one character, substring;
1984 * 3. the character, if any, immediately before NAME in LINESTART must
1985 * be a character in NONAM;
1986 * 4. the character, if any, immediately after NAME in LINESTART must
1987 * also be a character in NONAM.
1989 * The implementation uses the notinname() macro, which recognises the
1990 * characters stored in the string `nonam'.
1991 * etags.el needs to use the same characters that are in NONAM.
1994 make_tag (name, namelen, is_func, linestart, linelen, lno, cno)
1995 char *name; /* tag name, or NULL if unnamed */
1996 int namelen; /* tag length */
1997 bool is_func; /* tag is a function */
1998 char *linestart; /* start of the line where tag is */
1999 int linelen; /* length of the line where tag is */
2000 int lno; /* line number */
2001 long cno; /* character number */
2003 bool named = (name != NULL && namelen > 0);
2005 if (!CTAGS && named) /* maybe set named to false */
2006 /* Let's try to make an implicit tag name, that is, create an unnamed tag
2007 such that etags.el can guess a name from it. */
2010 register char *cp = name;
2012 for (i = 0; i < namelen; i++)
2013 if (notinname (*cp++))
2015 if (i == namelen) /* rule #1 */
2017 cp = linestart + linelen - namelen;
2018 if (notinname (linestart[linelen-1]))
2019 cp -= 1; /* rule #4 */
2020 if (cp >= linestart /* rule #2 */
2022 || notinname (cp[-1])) /* rule #3 */
2023 && strneq (name, cp, namelen)) /* rule #2 */
2024 named = FALSE; /* use implicit tag name */
2029 name = savenstr (name, namelen);
2032 pfnote (name, is_func, linestart, linelen, lno, cno);
2037 pfnote (name, is_func, linestart, linelen, lno, cno)
2038 char *name; /* tag name, or NULL if unnamed */
2039 bool is_func; /* tag is a function */
2040 char *linestart; /* start of the line where tag is */
2041 int linelen; /* length of the line where tag is */
2042 int lno; /* line number */
2043 long cno; /* character number */
2047 assert (name == NULL || name[0] != '\0');
2048 if (CTAGS && name == NULL)
2051 np = xnew (1, node);
2053 /* If ctags mode, change name "main" to M<thisfilename>. */
2054 if (CTAGS && !cxref_style && streq (name, "main"))
2056 register char *fp = etags_strrchr (curfdp->taggedfname, '/');
2057 np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, "");
2058 fp = etags_strrchr (np->name, '.');
2059 if (fp != NULL && fp[1] != '\0' && fp[2] == '\0')
2065 np->been_warned = FALSE;
2067 np->is_func = is_func;
2069 if (np->fdp->usecharno)
2070 /* Our char numbers are 0-base, because of C language tradition?
2071 ctags compatibility? old versions compatibility? I don't know.
2072 Anyway, since emacs's are 1-base we expect etags.el to take care
2073 of the difference. If we wanted to have 1-based numbers, we would
2074 uncomment the +1 below. */
2075 np->cno = cno /* + 1 */ ;
2077 np->cno = invalidcharno;
2078 np->left = np->right = NULL;
2079 if (CTAGS && !cxref_style)
2081 if (strlen (linestart) < 50)
2082 np->regex = concat (linestart, "$", "");
2084 np->regex = savenstr (linestart, 50);
2087 np->regex = savenstr (linestart, linelen);
2089 add_node (np, &nodehead);
2094 * recurse on left children, iterate on right children.
2102 register node *node_right = np->right;
2103 free_tree (np->left);
2113 * delete a file description
2117 register fdesc *fdp;
2119 free (fdp->infname);
2120 free (fdp->infabsname);
2121 free (fdp->infabsdir);
2122 free (fdp->taggedfname);
2129 * Adds a node to the tree of nodes. In etags mode, sort by file
2130 * name. In ctags mode, sort by tag name. Make no attempt at
2133 * add_node is the only function allowed to add nodes, so it can
2137 add_node (np, cur_node_p)
2138 node *np, **cur_node_p;
2141 register node *cur_node = *cur_node_p;
2143 if (cur_node == NULL)
2153 /* For each file name, tags are in a linked sublist on the right
2154 pointer. The first tags of different files are a linked list
2155 on the left pointer. last_node points to the end of the last
2157 if (last_node != NULL && last_node->fdp == np->fdp)
2159 /* Let's use the same sublist as the last added node. */
2160 assert (last_node->right == NULL);
2161 last_node->right = np;
2164 else if (cur_node->fdp == np->fdp)
2166 /* Scanning the list we found the head of a sublist which is
2167 good for us. Let's scan this sublist. */
2168 add_node (np, &cur_node->right);
2171 /* The head of this sublist is not good for us. Let's try the
2173 add_node (np, &cur_node->left);
2174 } /* if ETAGS mode */
2179 dif = strcmp (np->name, cur_node->name);
2182 * If this tag name matches an existing one, then
2183 * do not add the node, but maybe print a warning.
2185 if (no_duplicates && !dif)
2187 if (np->fdp == cur_node->fdp)
2191 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
2192 np->fdp->infname, lineno, np->name);
2193 fprintf (stderr, "Second entry ignored\n");
2196 else if (!cur_node->been_warned && !no_warnings)
2200 "Duplicate entry in files %s and %s: %s (Warning only)\n",
2201 np->fdp->infname, cur_node->fdp->infname, np->name);
2202 cur_node->been_warned = TRUE;
2207 /* Actually add the node */
2208 add_node (np, dif < 0 ? &cur_node->left : &cur_node->right);
2209 } /* if CTAGS mode */
2213 * invalidate_nodes ()
2214 * Scan the node tree and invalidate all nodes pointing to the
2215 * given file description (CTAGS case) or free them (ETAGS case).
2218 invalidate_nodes (badfdp, npp)
2229 if (np->left != NULL)
2230 invalidate_nodes (badfdp, &np->left);
2231 if (np->fdp == badfdp)
2233 if (np->right != NULL)
2234 invalidate_nodes (badfdp, &np->right);
2238 assert (np->fdp != NULL);
2239 if (np->fdp == badfdp)
2241 *npp = np->left; /* detach the sublist from the list */
2242 np->left = NULL; /* isolate it */
2243 free_tree (np); /* free it */
2244 invalidate_nodes (badfdp, npp);
2247 invalidate_nodes (badfdp, &np->left);
2252 static int total_size_of_entries __P((node *));
2253 static int number_len __P((long));
2255 /* Length of a non-negative number's decimal representation. */
2261 while ((num /= 10) > 0)
2267 * Return total number of characters that put_entries will output for
2268 * the nodes in the linked list at the right of the specified node.
2269 * This count is irrelevant with etags.el since emacs 19.34 at least,
2270 * but is still supplied for backward compatibility.
2273 total_size_of_entries (np)
2276 register int total = 0;
2278 for (; np != NULL; np = np->right)
2281 total += strlen (np->regex) + 1; /* pat\177 */
2282 if (np->name != NULL)
2283 total += strlen (np->name) + 1; /* name\001 */
2284 total += number_len ((long) np->lno) + 1; /* lno, */
2285 if (np->cno != invalidcharno) /* cno */
2286 total += number_len (np->cno);
2287 total += 1; /* newline */
2298 static fdesc *fdp = NULL;
2303 /* Output subentries that precede this one */
2305 put_entries (np->left);
2307 /* Output this entry */
2316 fprintf (tagf, "\f\n%s,%d\n",
2317 fdp->taggedfname, total_size_of_entries (np));
2318 fdp->written = TRUE;
2320 fputs (np->regex, tagf);
2321 fputc ('\177', tagf);
2322 if (np->name != NULL)
2324 fputs (np->name, tagf);
2325 fputc ('\001', tagf);
2327 fprintf (tagf, "%d,", np->lno);
2328 if (np->cno != invalidcharno)
2329 fprintf (tagf, "%ld", np->cno);
2335 if (np->name == NULL)
2336 error ("internal error: NULL name in ctags mode.", (char *)NULL);
2341 fprintf (stdout, "%s %s %d\n",
2342 np->name, np->fdp->taggedfname, (np->lno + 63) / 64);
2344 fprintf (stdout, "%-16s %3d %-16s %s\n",
2345 np->name, np->lno, np->fdp->taggedfname, np->regex);
2349 fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname);
2352 { /* function or #define macro with args */
2353 putc (searchar, tagf);
2356 for (sp = np->regex; *sp; sp++)
2358 if (*sp == '\\' || *sp == searchar)
2362 putc (searchar, tagf);
2365 { /* anything else; text pattern inadequate */
2366 fprintf (tagf, "%d", np->lno);
2371 } /* if this node contains a valid tag */
2373 /* Output subentries that follow this one */
2374 put_entries (np->right);
2376 put_entries (np->left);
2381 #define C_EXT 0x00fff /* C extensions */
2382 #define C_PLAIN 0x00000 /* C */
2383 #define C_PLPL 0x00001 /* C++ */
2384 #define C_STAR 0x00003 /* C* */
2385 #define C_JAVA 0x00005 /* JAVA */
2386 #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */
2387 #define YACC 0x10000 /* yacc file */
2390 * The C symbol tables.
2395 st_C_objprot, st_C_objimpl, st_C_objend,
2397 st_C_ignore, st_C_attribute,
2400 st_C_class, st_C_template,
2401 st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef
2404 static unsigned int hash __P((const char *, unsigned int));
2405 static struct C_stab_entry * in_word_set __P((const char *, unsigned int));
2406 static enum sym_type C_symtype __P((char *, int, int));
2408 /* Feed stuff between (but not including) %[ and %] lines to:
2414 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
2418 while, 0, st_C_ignore
2419 switch, 0, st_C_ignore
2420 return, 0, st_C_ignore
2421 __attribute__, 0, st_C_attribute
2422 GTY, 0, st_C_attribute
2423 @interface, 0, st_C_objprot
2424 @protocol, 0, st_C_objprot
2425 @implementation, 0, st_C_objimpl
2426 @end, 0, st_C_objend
2427 import, (C_JAVA & ~C_PLPL), st_C_ignore
2428 package, (C_JAVA & ~C_PLPL), st_C_ignore
2429 friend, C_PLPL, st_C_ignore
2430 extends, (C_JAVA & ~C_PLPL), st_C_javastruct
2431 implements, (C_JAVA & ~C_PLPL), st_C_javastruct
2432 interface, (C_JAVA & ~C_PLPL), st_C_struct
2433 class, 0, st_C_class
2434 namespace, C_PLPL, st_C_struct
2435 domain, C_STAR, st_C_struct
2436 union, 0, st_C_struct
2437 struct, 0, st_C_struct
2438 extern, 0, st_C_extern
2440 typedef, 0, st_C_typedef
2441 define, 0, st_C_define
2442 undef, 0, st_C_define
2443 operator, C_PLPL, st_C_operator
2444 template, 0, st_C_template
2445 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
2446 DEFUN, 0, st_C_gnumacro
2447 SYSCALL, 0, st_C_gnumacro
2448 ENTRY, 0, st_C_gnumacro
2449 PSEUDO, 0, st_C_gnumacro
2450 # These are defined inside C functions, so currently they are not met.
2451 # EXFUN used in glibc, DEFVAR_* in emacs.
2452 #EXFUN, 0, st_C_gnumacro
2453 #DEFVAR_, 0, st_C_gnumacro
2455 and replace lines between %< and %> with its output, then:
2456 - remove the #if characterset check
2457 - make in_word_set static and not inline. */
2459 /* C code produced by gperf version 3.0.1 */
2460 /* Command-line: gperf -m 5 */
2461 /* Computed positions: -k'2-3' */
2463 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
2464 /* maximum key range = 33, duplicates = 0 */
2475 register const char *str;
2476 register unsigned int len;
2478 static unsigned char asso_values[] =
2480 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2481 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2482 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2483 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2484 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2485 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2486 35, 35, 35, 35, 35, 35, 35, 35, 35, 3,
2487 26, 35, 35, 35, 35, 35, 35, 35, 27, 35,
2488 35, 35, 35, 24, 0, 35, 35, 35, 35, 0,
2489 35, 35, 35, 35, 35, 1, 35, 16, 35, 6,
2490 23, 0, 0, 35, 22, 0, 35, 35, 5, 0,
2491 0, 15, 1, 35, 6, 35, 8, 19, 35, 16,
2492 4, 5, 35, 35, 35, 35, 35, 35, 35, 35,
2493 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2494 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2495 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2496 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2497 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2498 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2499 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2500 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2501 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2502 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2503 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2504 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
2505 35, 35, 35, 35, 35, 35
2507 register int hval = len;
2512 hval += asso_values[(unsigned char)str[2]];
2515 hval += asso_values[(unsigned char)str[1]];
2521 static struct C_stab_entry *
2522 in_word_set (str, len)
2523 register const char *str;
2524 register unsigned int len;
2528 TOTAL_KEYWORDS = 33,
2529 MIN_WORD_LENGTH = 2,
2530 MAX_WORD_LENGTH = 15,
2535 static struct C_stab_entry wordlist[] =
2538 {"if", 0, st_C_ignore},
2539 {"GTY", 0, st_C_attribute},
2540 {"@end", 0, st_C_objend},
2541 {"union", 0, st_C_struct},
2542 {"define", 0, st_C_define},
2543 {"import", (C_JAVA & ~C_PLPL), st_C_ignore},
2544 {"template", 0, st_C_template},
2545 {"operator", C_PLPL, st_C_operator},
2546 {"@interface", 0, st_C_objprot},
2547 {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct},
2548 {"friend", C_PLPL, st_C_ignore},
2549 {"typedef", 0, st_C_typedef},
2550 {"return", 0, st_C_ignore},
2551 {"@implementation",0, st_C_objimpl},
2552 {"@protocol", 0, st_C_objprot},
2553 {"interface", (C_JAVA & ~C_PLPL), st_C_struct},
2554 {"extern", 0, st_C_extern},
2555 {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct},
2556 {"struct", 0, st_C_struct},
2557 {"domain", C_STAR, st_C_struct},
2558 {"switch", 0, st_C_ignore},
2559 {"enum", 0, st_C_enum},
2560 {"for", 0, st_C_ignore},
2561 {"namespace", C_PLPL, st_C_struct},
2562 {"class", 0, st_C_class},
2563 {"while", 0, st_C_ignore},
2564 {"undef", 0, st_C_define},
2565 {"package", (C_JAVA & ~C_PLPL), st_C_ignore},
2566 {"__attribute__", 0, st_C_attribute},
2567 {"SYSCALL", 0, st_C_gnumacro},
2568 {"ENTRY", 0, st_C_gnumacro},
2569 {"PSEUDO", 0, st_C_gnumacro},
2570 {"DEFUN", 0, st_C_gnumacro}
2573 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
2575 register int key = hash (str, len);
2577 if (key <= MAX_HASH_VALUE && key >= 0)
2579 register const char *s = wordlist[key].name;
2581 if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0')
2582 return &wordlist[key];
2589 static enum sym_type
2590 C_symtype (str, len, c_ext)
2595 register struct C_stab_entry *se = in_word_set (str, len);
2597 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
2604 * Ignoring __attribute__ ((list))
2606 static bool inattribute; /* looking at an __attribute__ construct */
2609 * C functions and variables are recognized using a simple
2610 * finite automaton. fvdef is its state variable.
2614 fvnone, /* nothing seen */
2615 fdefunkey, /* Emacs DEFUN keyword seen */
2616 fdefunname, /* Emacs DEFUN name seen */
2617 foperator, /* func: operator keyword seen (cplpl) */
2618 fvnameseen, /* function or variable name seen */
2619 fstartlist, /* func: just after open parenthesis */
2620 finlist, /* func: in parameter list */
2621 flistseen, /* func: after parameter list */
2622 fignore, /* func: before open brace */
2623 vignore /* var-like: ignore until ';' */
2626 static bool fvextern; /* func or var: extern keyword seen; */
2629 * typedefs are recognized using a simple finite automaton.
2630 * typdef is its state variable.
2634 tnone, /* nothing seen */
2635 tkeyseen, /* typedef keyword seen */
2636 ttypeseen, /* defined type seen */
2637 tinbody, /* inside typedef body */
2638 tend, /* just before typedef tag */
2639 tignore /* junk after typedef tag */
2643 * struct-like structures (enum, struct and union) are recognized
2644 * using another simple finite automaton. `structdef' is its state
2649 snone, /* nothing seen yet,
2650 or in struct body if bracelev > 0 */
2651 skeyseen, /* struct-like keyword seen */
2652 stagseen, /* struct-like tag seen */
2653 scolonseen /* colon seen after struct-like tag */
2657 * When objdef is different from onone, objtag is the name of the class.
2659 static char *objtag = "<uninited>";
2662 * Yet another little state machine to deal with preprocessor lines.
2666 dnone, /* nothing seen */
2667 dsharpseen, /* '#' seen as first char on line */
2668 ddefineseen, /* '#' and 'define' seen */
2669 dignorerest /* ignore rest of line */
2673 * State machine for Objective C protocols and implementations.
2674 * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995)
2678 onone, /* nothing seen */
2679 oprotocol, /* @interface or @protocol seen */
2680 oimplementation, /* @implementations seen */
2681 otagseen, /* class name seen */
2682 oparenseen, /* parenthesis before category seen */
2683 ocatseen, /* category name seen */
2684 oinbody, /* in @implementation body */
2685 omethodsign, /* in @implementation body, after +/- */
2686 omethodtag, /* after method name */
2687 omethodcolon, /* after method colon */
2688 omethodparm, /* after method parameter */
2689 oignore /* wait for @end */
2694 * Use this structure to keep info about the token read, and how it
2695 * should be tagged. Used by the make_C_tag function to build a tag.
2699 char *line; /* string containing the token */
2700 int offset; /* where the token starts in LINE */
2701 int length; /* token length */
2703 The previous members can be used to pass strings around for generic
2704 purposes. The following ones specifically refer to creating tags. In this
2705 case the token contained here is the pattern that will be used to create a
2708 bool valid; /* do not create a tag; the token should be
2709 invalidated whenever a state machine is
2710 reset prematurely */
2711 bool named; /* create a named tag */
2712 int lineno; /* source line number of tag */
2713 long linepos; /* source char number of tag */
2714 } token; /* latest token read */
2717 * Variables and functions for dealing with nested structures.
2718 * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001)
2720 static void pushclass_above __P((int, char *, int));
2721 static void popclass_above __P((int));
2722 static void write_classname __P((linebuffer *, char *qualifier));
2725 char **cname; /* nested class names */
2726 int *bracelev; /* nested class brace level */
2727 int nl; /* class nesting level (elements used) */
2728 int size; /* length of the array */
2729 } cstack; /* stack for nested declaration tags */
2730 /* Current struct nesting depth (namespace, class, struct, union, enum). */
2731 #define nestlev (cstack.nl)
2732 /* After struct keyword or in struct body, not inside a nested function. */
2733 #define instruct (structdef == snone && nestlev > 0 \
2734 && bracelev == cstack.bracelev[nestlev-1] + 1)
2737 pushclass_above (bracelev, str, len)
2744 popclass_above (bracelev);
2746 if (nl >= cstack.size)
2748 int size = cstack.size *= 2;
2749 xrnew (cstack.cname, size, char *);
2750 xrnew (cstack.bracelev, size, int);
2752 assert (nl == 0 || cstack.bracelev[nl-1] < bracelev);
2753 cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len);
2754 cstack.bracelev[nl] = bracelev;
2759 popclass_above (bracelev)
2764 for (nl = cstack.nl - 1;
2765 nl >= 0 && cstack.bracelev[nl] >= bracelev;
2768 free (cstack.cname[nl]);
2774 write_classname (cn, qualifier)
2779 int qlen = strlen (qualifier);
2781 if (cstack.nl == 0 || cstack.cname[0] == NULL)
2785 cn->buffer[0] = '\0';
2789 len = strlen (cstack.cname[0]);
2790 linebuffer_setlen (cn, len+1);
2791 xstrncpy (cn->buffer, cstack.cname[0],len+1);
2793 for (i = 1; i < cstack.nl; i++)
2798 s = cstack.cname[i];
2803 linebuffer_setlen (cn, len);
2804 strncat (cn->buffer, qualifier, qlen);
2805 strncat (cn->buffer, s, slen);
2810 static bool consider_token __P((char *, int, int, int *, int, int, bool *));
2811 static void make_C_tag __P((bool));
2815 * checks to see if the current token is at the start of a
2816 * function or variable, or corresponds to a typedef, or
2817 * is a struct/union/enum tag, or #define, or an enum constant.
2819 * *IS_FUNC gets TRUE if the token is a function or #define macro
2820 * with args. C_EXTP points to which language we are looking at.
2831 consider_token (str, len, c, c_extp, bracelev, parlev, is_func_or_var)
2832 register char *str; /* IN: token pointer */
2833 register int len; /* IN: token length */
2834 register int c; /* IN: first char after the token */
2835 int *c_extp; /* IN, OUT: C extensions mask */
2836 int bracelev; /* IN: brace level */
2837 int parlev; /* IN: parenthesis level */
2838 bool *is_func_or_var; /* OUT: function or variable found */
2840 /* When structdef is stagseen, scolonseen, or snone with bracelev > 0,
2841 structtype is the type of the preceding struct-like keyword, and
2842 structbracelev is the brace level where it has been seen. */
2843 static enum sym_type structtype;
2844 static int structbracelev;
2845 static enum sym_type toktype;
2848 toktype = C_symtype (str, len, *c_extp);
2851 * Skip __attribute__
2853 if (toktype == st_C_attribute)
2860 * Advance the definedef state machine.
2865 /* We're not on a preprocessor line. */
2866 if (toktype == st_C_gnumacro)
2873 if (toktype == st_C_define)
2875 definedef = ddefineseen;
2879 definedef = dignorerest;
2884 * Make a tag for any macro, unless it is a constant
2885 * and constantypedefs is FALSE.
2887 definedef = dignorerest;
2888 *is_func_or_var = (c == '(');
2889 if (!*is_func_or_var && !constantypedefs)
2896 error ("internal error: definedef value.", (char *)NULL);
2905 if (toktype == st_C_typedef)
2929 case st_C_attribute:
2930 case st_C_javastruct:
2941 if (structdef == snone && fvdef == fvnone)
2962 case st_C_attribute:
2963 case st_C_javastruct:
2983 case st_C_javastruct:
2984 if (structdef == stagseen)
2985 structdef = scolonseen;
2989 if ((*c_extp & C_AUTO) /* automatic detection of C++ language */
2991 && definedef == dnone && structdef == snone
2992 && typdef == tnone && fvdef == fvnone)
2993 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
2994 if (toktype == st_C_template)
3001 && (typdef == tkeyseen
3002 || (typedefs_or_cplusplus && structdef == snone)))
3004 structdef = skeyseen;
3005 structtype = toktype;
3006 structbracelev = bracelev;
3007 if (fvdef == fvnameseen)
3019 case st_C_attribute:
3028 if (structdef == skeyseen)
3030 structdef = stagseen;
3034 if (typdef != tnone)
3037 /* Detect Objective C constructs. */
3047 objdef = oimplementation;
3055 case st_C_attribute:
3056 case st_C_javastruct:
3069 case oimplementation:
3070 /* Save the class tag for functions or variables defined inside. */
3071 objtag = savenstr (str, len);
3075 /* Save the class tag for categories. */
3076 objtag = savenstr (str, len);
3078 *is_func_or_var = TRUE;
3082 *is_func_or_var = TRUE;
3090 objdef = omethodtag;
3091 linebuffer_setlen (&token_name, len+1);
3092 xstrncpy (token_name.buffer, str, len+1);
3093 token_name.buffer[len] = '\0';
3099 objdef = omethodparm;
3105 objdef = omethodtag;
3106 linebuffer_setlen (&token_name, token_name.len + len);
3107 strncat (token_name.buffer, str, len);
3112 if (toktype == st_C_objend)
3114 /* Memory leakage here: the string pointed by objtag is
3115 never released, because many tests would be needed to
3116 avoid breaking on incorrect input code. The amount of
3117 memory leaked here is the sum of the lengths of the
3132 /* A function, variable or enum constant? */
3160 *is_func_or_var = TRUE;
3164 && structdef == snone
3165 && structtype == st_C_enum && bracelev > structbracelev)
3166 return TRUE; /* enum constant */
3172 fvdef = fdefunname; /* GNU macro */
3173 *is_func_or_var = TRUE;
3181 if ((strneq (str, "asm", 3) && endtoken (str[3]))
3182 || (strneq (str, "__asm__", 7) && endtoken (str[7])))
3199 if (len >= 10 && strneq (str+len-10, "::operator", 10))
3201 if (*c_extp & C_AUTO) /* automatic detection of C++ */
3202 *c_extp = (*c_extp | C_PLPL) & ~C_AUTO;
3204 *is_func_or_var = TRUE;
3207 if (bracelev > 0 && !instruct)
3209 fvdef = fvnameseen; /* function or variable */
3210 *is_func_or_var = TRUE;
3231 case st_C_attribute:
3232 case st_C_javastruct:
3248 * C_entries often keeps pointers to tokens or lines which are older than
3249 * the line currently read. By keeping two line buffers, and switching
3250 * them at end of line, it is possible to use those pointers.
3258 #define current_lb_is_new (newndx == curndx)
3259 #define switch_line_buffers() (curndx = 1 - curndx)
3261 #define curlb (lbs[curndx].lb)
3262 #define newlb (lbs[newndx].lb)
3263 #define curlinepos (lbs[curndx].linepos)
3264 #define newlinepos (lbs[newndx].linepos)
3266 #define plainc ((c_ext & C_EXT) == C_PLAIN)
3267 #define cplpl (c_ext & C_PLPL)
3268 #define cjava ((c_ext & C_JAVA) == C_JAVA)
3270 #define CNL_SAVE_DEFINEDEF() \
3272 curlinepos = charno; \
3273 readline (&curlb, inf); \
3274 lp = curlb.buffer; \
3281 CNL_SAVE_DEFINEDEF(); \
3282 if (savetoken.valid) \
3284 token = savetoken; \
3285 savetoken.valid = FALSE; \
3287 definedef = dnone; \
3295 /* This function is never called when token.valid is FALSE, but
3296 we must protect against invalid input or internal errors. */
3298 make_tag (token_name.buffer, token_name.len, isfun, token.line,
3299 token.offset+token.length+1, token.lineno, token.linepos);
3301 { /* this branch is optimised away if !DEBUG */
3302 make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""),
3303 token_name.len + 17, isfun, token.line,
3304 token.offset+token.length+1, token.lineno, token.linepos);
3305 error ("INVALID TOKEN", NULL);
3308 token.valid = FALSE;
3314 * This routine finds functions, variables, typedefs,
3315 * #define's, enum constants and struct/union/enum definitions in
3316 * C syntax and adds them to the list.
3319 C_entries (c_ext, inf)
3320 int c_ext; /* extension of C */
3321 FILE *inf; /* input file */
3323 register char c; /* latest char read; '\0' for end of line */
3324 register char *lp; /* pointer one beyond the character `c' */
3325 int curndx, newndx; /* indices for current and new lb */
3326 register int tokoff; /* offset in line of start of current token */
3327 register int toklen; /* length of current token */
3328 char *qualifier; /* string used to qualify names */
3329 int qlen; /* length of qualifier */
3330 int bracelev; /* current brace level */
3331 int bracketlev; /* current bracket level */
3332 int parlev; /* current parenthesis level */
3333 int attrparlev; /* __attribute__ parenthesis level */
3334 int templatelev; /* current template level */
3335 int typdefbracelev; /* bracelev where a typedef struct body begun */
3336 bool incomm, inquote, inchar, quotednl, midtoken;
3337 bool yacc_rules; /* in the rules part of a yacc file */
3338 struct tok savetoken = {0}; /* token saved during preprocessor handling */
3341 linebuffer_init (&lbs[0].lb);
3342 linebuffer_init (&lbs[1].lb);
3343 if (cstack.size == 0)
3345 cstack.size = (DEBUG) ? 1 : 4;
3347 cstack.cname = xnew (cstack.size, char *);
3348 cstack.bracelev = xnew (cstack.size, int);
3351 tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */
3352 curndx = newndx = 0;
3356 fvdef = fvnone; fvextern = FALSE; typdef = tnone;
3357 structdef = snone; definedef = dnone; objdef = onone;
3359 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3360 token.valid = savetoken.valid = FALSE;
3361 bracelev = bracketlev = parlev = attrparlev = templatelev = 0;
3363 { qualifier = "."; qlen = 1; }
3365 { qualifier = "::"; qlen = 2; }
3373 /* If we are at the end of the line, the next character is a
3374 '\0'; do not skip it, because it is what tells us
3375 to read the next line. */
3396 /* Newlines inside comments do not end macro definitions in
3398 CNL_SAVE_DEFINEDEF ();
3413 /* Newlines inside strings do not end macro definitions
3414 in traditional cpp, even though compilers don't
3415 usually accept them. */
3416 CNL_SAVE_DEFINEDEF ();
3428 /* Hmmm, something went wrong. */
3439 else if (bracketlev > 0)
3444 if (--bracketlev > 0)
3448 CNL_SAVE_DEFINEDEF ();
3483 if (fvdef != finlist && fvdef != fignore && fvdef !=vignore)
3496 else if (/* cplpl && */ *lp == '/')
3502 if ((c_ext & YACC) && *lp == '%')
3504 /* Entering or exiting rules section in yacc file. */
3506 definedef = dnone; fvdef = fvnone; fvextern = FALSE;
3507 typdef = tnone; structdef = snone;
3508 midtoken = inquote = inchar = incomm = quotednl = FALSE;
3510 yacc_rules = !yacc_rules;
3516 if (definedef == dnone)
3519 bool cpptoken = TRUE;
3521 /* Look back on this line. If all blanks, or nonblanks
3522 followed by an end of comment, this is a preprocessor
3524 for (cp = newlb.buffer; cp < lp-1; cp++)
3527 if (*cp == '*' && *(cp+1) == '/')
3536 definedef = dsharpseen;
3537 } /* if (definedef == dnone) */
3547 /* Consider token only if some involved conditions are satisfied. */
3548 if (typdef != tignore
3549 && definedef != dignorerest
3552 && (definedef != dnone
3553 || structdef != scolonseen)
3560 if (c == ':' && *lp == ':' && begtoken (lp[1]))
3561 /* This handles :: in the middle,
3562 but not at the beginning of an identifier.
3563 Also, space-separated :: is not recognised. */
3565 if (c_ext & C_AUTO) /* automatic detection of C++ */
3566 c_ext = (c_ext | C_PLPL) & ~C_AUTO;
3570 goto still_in_token;
3574 bool funorvar = FALSE;
3577 || consider_token (newlb.buffer + tokoff, toklen, c,
3578 &c_ext, bracelev, parlev,
3581 if (fvdef == foperator)
3584 lp = skip_spaces (lp-1);
3588 && !iswhite (*lp) && *lp != '(')
3591 toklen += lp - oldlp;
3593 token.named = FALSE;
3595 && nestlev > 0 && definedef == dnone)
3596 /* in struct body */
3598 write_classname (&token_name, qualifier);
3599 linebuffer_setlen (&token_name,
3600 token_name.len+qlen+toklen);
3601 strcat (token_name.buffer, qualifier);
3602 strncat (token_name.buffer,
3603 newlb.buffer + tokoff, toklen);
3606 else if (objdef == ocatseen)
3607 /* Objective C category */
3609 int len = strlen (objtag) + 2 + toklen;
3610 linebuffer_setlen (&token_name, len);
3611 strcpy (token_name.buffer, objtag);
3612 strcat (token_name.buffer, "(");
3613 strncat (token_name.buffer,
3614 newlb.buffer + tokoff, toklen);
3615 strcat (token_name.buffer, ")");
3618 else if (objdef == omethodtag
3619 || objdef == omethodparm)
3620 /* Objective C method */
3624 else if (fvdef == fdefunname)
3625 /* GNU DEFUN and similar macros */
3627 bool defun = (newlb.buffer[tokoff] == 'F');
3631 /* Rewrite the tag so that emacs lisp DEFUNs
3632 can be found by their elisp name */
3638 linebuffer_setlen (&token_name, len+1);
3639 xstrncpy (token_name.buffer,
3640 newlb.buffer + off, len+1);
3643 if (token_name.buffer[len] == '_')
3644 token_name.buffer[len] = '-';
3645 token.named = defun;
3649 linebuffer_setlen (&token_name, toklen+1);
3650 xstrncpy (token_name.buffer,
3651 newlb.buffer + tokoff, toklen+1);
3652 token_name.buffer[toklen] = '\0';
3653 /* Name macros and members. */
3654 token.named = (structdef == stagseen
3655 || typdef == ttypeseen
3658 && definedef == dignorerest)
3660 && definedef == dnone
3661 && structdef == snone
3664 token.lineno = lineno;
3665 token.offset = tokoff;
3666 token.length = toklen;
3667 token.line = newlb.buffer;
3668 token.linepos = newlinepos;
3671 if (definedef == dnone
3672 && (fvdef == fvnameseen
3673 || fvdef == foperator
3674 || structdef == stagseen
3676 || typdef == ttypeseen
3677 || objdef != onone))
3679 if (current_lb_is_new)
3680 switch_line_buffers ();
3682 else if (definedef != dnone
3683 || fvdef == fdefunname
3685 make_C_tag (funorvar);
3687 else /* not yacc and consider_token failed */
3689 if (inattribute && fvdef == fignore)
3691 /* We have just met __attribute__ after a
3692 function parameter list: do not tag the
3699 } /* if (endtoken (c)) */
3700 else if (intoken (c))
3706 } /* if (midtoken) */
3707 else if (begtoken (c))
3715 /* This prevents tagging fb in
3716 void (__attribute__((noreturn)) *fb) (void);
3717 Fixing this is not easy and not very important. */
3721 if (plainc || declarations)
3723 make_C_tag (TRUE); /* a function */
3740 if (structdef == stagseen && !cjava)
3742 popclass_above (bracelev);
3756 if (!yacc_rules || lp == newlb.buffer + 1)
3758 tokoff = lp - 1 - newlb.buffer;
3763 } /* if (begtoken) */
3764 } /* if must look at token */
3767 /* Detect end of line, colon, comma, semicolon and various braces
3768 after having handled a token.*/
3774 if (yacc_rules && token.offset == 0 && token.valid)
3776 make_C_tag (FALSE); /* a yacc function */
3779 if (definedef != dnone)
3785 make_C_tag (TRUE); /* an Objective C class */
3789 objdef = omethodcolon;
3790 linebuffer_setlen (&token_name, token_name.len + 1);
3791 strcat (token_name.buffer, ":");
3797 case oimplementation:
3807 if (structdef == stagseen)
3809 structdef = scolonseen;
3812 /* Should be useless, but may be work as a safety net. */
3813 if (cplpl && fvdef == flistseen)
3815 make_C_tag (TRUE); /* a function */
3821 if (definedef != dnone || inattribute)
3827 make_C_tag (FALSE); /* a typedef */
3837 if (typdef == tignore || cplpl)
3841 if ((globals && bracelev == 0 && (!fvextern || declarations))
3842 || (members && instruct))
3843 make_C_tag (FALSE); /* a variable */
3846 token.valid = FALSE;
3850 && (cplpl || !instruct)
3851 && (typdef == tnone || (typdef != tignore && instruct)))
3853 && plainc && instruct))
3854 make_C_tag (TRUE); /* a function */
3867 && cplpl && structdef == stagseen)
3868 make_C_tag (FALSE); /* forward declaration */
3870 token.valid = FALSE;
3871 } /* switch (fvdef) */
3878 if (structdef == stagseen)
3882 if (definedef != dnone || inattribute)
3888 make_C_tag (TRUE); /* an Objective C method */
3895 case oimplementation:
3923 && (!fvextern || declarations))
3924 || (members && instruct)))
3925 make_C_tag (FALSE); /* a variable */
3928 if ((declarations && typdef == tnone && !instruct)
3929 || (members && typdef != tignore && instruct))
3931 make_C_tag (TRUE); /* a function */
3934 else if (!declarations)
3936 token.valid = FALSE;
3942 if (structdef == stagseen)
3946 if (definedef != dnone || inattribute)
3948 if (structdef == stagseen)
3955 make_C_tag (FALSE); /* a typedef */
3967 if ((members && bracelev == 1)
3968 || (globals && bracelev == 0
3969 && (!fvextern || declarations)))
3970 make_C_tag (FALSE); /* a variable */
3995 if (definedef != dnone)
3997 if (objdef == otagseen && parlev == 0)
3998 objdef = oparenseen;
4002 if (typdef == ttypeseen
4006 /* This handles constructs like:
4007 typedef void OperatorFun (int fun); */
4037 if (--attrparlev == 0)
4038 inattribute = FALSE;
4041 if (definedef != dnone)
4043 if (objdef == ocatseen && parlev == 1)
4045 make_C_tag (TRUE); /* an Objective C category */
4071 || typdef == ttypeseen))
4074 make_C_tag (FALSE); /* a typedef */
4077 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
4081 if (definedef != dnone)
4083 if (typdef == ttypeseen)
4085 /* Whenever typdef is set to tinbody (currently only
4086 here), typdefbracelev should be set to bracelev. */
4088 typdefbracelev = bracelev;
4093 make_C_tag (TRUE); /* a function */
4102 make_C_tag (TRUE); /* an Objective C class */
4107 make_C_tag (TRUE); /* an Objective C method */
4112 case oimplementation:
4120 /* Neutralize `extern "C" {' grot. */
4121 if (bracelev == 0 && structdef == snone && nestlev == 0
4140 case skeyseen: /* unnamed struct */
4141 pushclass_above (bracelev, NULL, 0);
4144 case stagseen: /* named struct or enum */
4145 case scolonseen: /* a class */
4146 pushclass_above (bracelev,token.line+token.offset, token.length);
4148 make_C_tag (FALSE); /* a struct or enum */
4159 if (definedef != dnone)
4161 if (fvdef == fstartlist)
4163 fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
4164 token.valid = FALSE;
4168 if (definedef != dnone)
4171 if (!ignoreindent && lp == newlb.buffer + 1)
4174 token.valid = FALSE; /* unexpected value, token unreliable */
4175 bracelev = 0; /* reset brace level if first column */
4176 parlev = 0; /* also reset paren level, just in case... */
4178 else if (bracelev < 0)
4180 token.valid = FALSE; /* something gone amiss, token unreliable */
4183 if (bracelev == 0 && fvdef == vignore)
4184 fvdef = fvnone; /* end of function */
4185 popclass_above (bracelev);
4187 /* Only if typdef == tinbody is typdefbracelev significant. */
4188 if (typdef == tinbody && bracelev <= typdefbracelev)
4190 assert (bracelev == typdefbracelev);
4195 if (definedef != dnone)
4205 if ((members && bracelev == 1)
4206 || (globals && bracelev == 0 && (!fvextern || declarations)))
4207 make_C_tag (FALSE); /* a variable */
4220 && (structdef == stagseen || fvdef == fvnameseen))
4227 if (templatelev > 0)
4235 if (objdef == oinbody && bracelev == 0)
4237 objdef = omethodsign;
4242 case '#': case '~': case '&': case '%': case '/':
4243 case '|': case '^': case '!': case '.': case '?':
4244 if (definedef != dnone)
4246 /* These surely cannot follow a function tag in C. */
4265 if (objdef == otagseen)
4267 make_C_tag (TRUE); /* an Objective C class */
4270 /* If a macro spans multiple lines don't reset its state. */
4272 CNL_SAVE_DEFINEDEF ();
4280 } /* while not eof */
4282 free (lbs[0].lb.buffer);
4283 free (lbs[1].lb.buffer);
4287 * Process either a C++ file or a C file depending on the setting
4291 default_C_entries (inf)
4294 C_entries (cplusplus ? C_PLPL : C_AUTO, inf);
4297 /* Always do plain C. */
4299 plain_C_entries (inf)
4305 /* Always do C++. */
4307 Cplusplus_entries (inf)
4310 C_entries (C_PLPL, inf);
4313 /* Always do Java. */
4318 C_entries (C_JAVA, inf);
4326 C_entries (C_STAR, inf);
4329 /* Always do Yacc. */
4334 C_entries (YACC, inf);
4338 /* Useful macros. */
4339 #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \
4340 for (; /* loop initialization */ \
4341 !feof (file_pointer) /* loop test */ \
4342 && /* instructions at start of loop */ \
4343 (readline (&line_buffer, file_pointer), \
4344 char_pointer = line_buffer.buffer, \
4348 #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \
4349 ((assert("" kw), TRUE) /* syntax error if not a literal string */ \
4350 && strneq ((cp), kw, sizeof(kw)-1) /* cp points at kw */ \
4351 && notinname ((cp)[sizeof(kw)-1]) /* end of kw */ \
4352 && ((cp) = skip_spaces((cp)+sizeof(kw)-1))) /* skip spaces */
4354 /* Similar to LOOKING_AT but does not use notinname, does not skip */
4355 #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \
4356 ((assert("" kw), TRUE) /* syntax error if not a literal string */ \
4357 && strncaseeq ((cp), kw, sizeof(kw)-1) /* cp points at kw */ \
4358 && ((cp) += sizeof(kw)-1)) /* skip spaces */
4361 * Read a file, but do no processing. This is used to do regexp
4362 * matching on files that have no language defined.
4365 just_read_file (inf)
4368 register char *dummy;
4370 LOOP_ON_INPUT_LINES (inf, lb, dummy)
4372 (void)dummy; // Silence set-not-read warning.
4376 /* Fortran parsing */
4378 static void F_takeprec __P((void));
4379 static void F_getit __P((FILE *));
4384 dbp = skip_spaces (dbp);
4388 dbp = skip_spaces (dbp);
4389 if (strneq (dbp, "(*)", 3))
4394 if (!ISDIGIT (*dbp))
4396 --dbp; /* force failure */
4401 while (ISDIGIT (*dbp));
4410 dbp = skip_spaces (dbp);
4413 readline (&lb, inf);
4418 dbp = skip_spaces (dbp);
4420 if (!ISALPHA (*dbp) && *dbp != '_' && *dbp != '$')
4422 for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++)
4424 make_tag (dbp, cp-dbp, TRUE,
4425 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4430 Fortran_functions (inf)
4433 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4436 dbp++; /* Ratfor escape to fortran */
4437 dbp = skip_spaces (dbp);
4440 switch (lowcase (*dbp))
4443 if (nocase_tail ("integer"))
4447 if (nocase_tail ("real"))
4451 if (nocase_tail ("logical"))
4455 if (nocase_tail ("complex") || nocase_tail ("character"))
4459 if (nocase_tail ("double"))
4461 dbp = skip_spaces (dbp);
4464 if (nocase_tail ("precision"))
4472 dbp = skip_spaces (dbp);
4475 switch (lowcase (*dbp))
4478 if (nocase_tail ("function"))
4482 if (nocase_tail ("subroutine"))
4486 if (nocase_tail ("entry"))
4490 if (nocase_tail ("blockdata") || nocase_tail ("block data"))
4492 dbp = skip_spaces (dbp);
4493 if (*dbp == '\0') /* assume un-named */
4494 make_tag ("blockdata", 9, TRUE,
4495 lb.buffer, dbp - lb.buffer, lineno, linecharno);
4497 F_getit (inf); /* look for name */
4510 * Philippe Waroquiers (1998)
4513 static void Ada_getit __P((FILE *, char *));
4515 /* Once we are positioned after an "interesting" keyword, let's get
4516 the real tag value necessary. */
4518 Ada_getit (inf, name_qualifier)
4520 char *name_qualifier;
4528 dbp = skip_spaces (dbp);
4530 || (dbp[0] == '-' && dbp[1] == '-'))
4532 readline (&lb, inf);
4535 switch (lowcase(*dbp))
4538 if (nocase_tail ("body"))
4540 /* Skipping body of procedure body or package body or ....
4541 resetting qualifier to body instead of spec. */
4542 name_qualifier = "/b";
4547 /* Skipping type of task type or protected type ... */
4548 if (nocase_tail ("type"))
4557 for (cp = dbp; *cp != '\0' && *cp != '"'; cp++)
4562 dbp = skip_spaces (dbp);
4565 && (ISALPHA (*cp) || ISDIGIT (*cp) || *cp == '_' || *cp == '.'));
4573 name = concat (dbp, name_qualifier, "");
4575 make_tag (name, strlen (name), TRUE,
4576 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4588 bool inquote = FALSE;
4589 bool skip_till_semicolumn = FALSE;
4591 LOOP_ON_INPUT_LINES (inf, lb, dbp)
4593 while (*dbp != '\0')
4595 /* Skip a string i.e. "abcd". */
4596 if (inquote || (*dbp == '"'))
4598 dbp = etags_strchr ((inquote) ? dbp : dbp+1, '"');
4603 continue; /* advance char */
4608 break; /* advance line */
4612 /* Skip comments. */
4613 if (dbp[0] == '-' && dbp[1] == '-')
4614 break; /* advance line */
4616 /* Skip character enclosed in single quote i.e. 'a'
4617 and skip single quote starting an attribute i.e. 'Image. */
4626 if (skip_till_semicolumn)
4629 skip_till_semicolumn = FALSE;
4631 continue; /* advance char */
4634 /* Search for beginning of a token. */
4635 if (!begtoken (*dbp))
4638 continue; /* advance char */
4641 /* We are at the beginning of a token. */
4642 switch (lowcase(*dbp))
4645 if (!packages_only && nocase_tail ("function"))
4646 Ada_getit (inf, "/f");
4648 break; /* from switch */
4649 continue; /* advance char */
4651 if (!packages_only && nocase_tail ("procedure"))
4652 Ada_getit (inf, "/p");
4653 else if (nocase_tail ("package"))
4654 Ada_getit (inf, "/s");
4655 else if (nocase_tail ("protected")) /* protected type */
4656 Ada_getit (inf, "/t");
4658 break; /* from switch */
4659 continue; /* advance char */
4662 if (typedefs && !packages_only && nocase_tail ("use"))
4664 /* when tagging types, avoid tagging use type Pack.Typename;
4665 for this, we will skip everything till a ; */
4666 skip_till_semicolumn = TRUE;
4667 continue; /* advance char */
4671 if (!packages_only && nocase_tail ("task"))
4672 Ada_getit (inf, "/k");
4673 else if (typedefs && !packages_only && nocase_tail ("type"))
4675 Ada_getit (inf, "/t");
4676 while (*dbp != '\0')
4680 break; /* from switch */
4681 continue; /* advance char */
4686 /* Look for the end of the token. */
4687 while (!endtoken (*dbp))
4690 } /* advance char */
4691 } /* advance line */
4696 * Unix and microcontroller assembly tag handling
4697 * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/
4698 * Idea by Bob Weiner, Motorola Inc. (1994)
4706 LOOP_ON_INPUT_LINES (inf, lb, cp)
4708 /* If first char is alphabetic or one of [_.$], test for colon
4709 following identifier. */
4710 if (ISALPHA (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4712 /* Read past label. */
4714 while (ISALNUM (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
4716 if (*cp == ':' || iswhite (*cp))
4717 /* Found end of label, so copy it and add it to the table. */
4718 make_tag (lb.buffer, cp - lb.buffer, TRUE,
4719 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4727 * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/
4728 * Perl variable names: /^(my|local).../
4729 * Original code by Bart Robinson <lomew@cs.utah.edu> (1995)
4730 * Additions by Michael Ernst <mernst@alum.mit.edu> (1997)
4731 * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001)
4734 Perl_functions (inf)
4737 char *package = savestr ("main"); /* current package name */
4740 LOOP_ON_INPUT_LINES (inf, lb, cp)
4742 cp = skip_spaces (cp);
4744 if (LOOKING_AT (cp, "package"))
4747 get_tag (cp, &package);
4749 else if (LOOKING_AT (cp, "sub"))
4754 while (!notinname (*cp))
4757 continue; /* nothing found */
4758 if ((pos = etags_strchr (sp, ':')) != NULL
4759 && pos < cp && pos[1] == ':')
4760 /* The name is already qualified. */
4761 make_tag (sp, cp - sp, TRUE,
4762 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4766 char savechar, *name;
4770 name = concat (package, "::", sp);
4772 make_tag (name, strlen(name), TRUE,
4773 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4777 else if (globals) /* only if we are tagging global vars */
4779 /* Skip a qualifier, if any. */
4780 bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local");
4781 /* After "my" or "local", but before any following paren or space. */
4782 char *varstart = cp;
4784 if (qual /* should this be removed? If yes, how? */
4785 && (*cp == '$' || *cp == '@' || *cp == '%'))
4790 while (ISALNUM (*cp) || *cp == '_');
4794 /* Should be examining a variable list at this point;
4795 could insist on seeing an open parenthesis. */
4796 while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')')
4802 make_tag (varstart, cp - varstart, FALSE,
4803 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4812 * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/
4813 * Idea by Eric S. Raymond <esr@thyrsus.com> (1997)
4814 * More ideas by seb bacon <seb@jamkit.com> (2002)
4817 Python_functions (inf)
4822 LOOP_ON_INPUT_LINES (inf, lb, cp)
4824 cp = skip_spaces (cp);
4825 if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class"))
4828 while (!notinname (*cp) && *cp != ':')
4830 make_tag (name, cp - name, TRUE,
4831 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4840 * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/
4841 * - /^[ \t]*class[ \t\n]+[^ \t\n]+/
4842 * - /^[ \t]*define\(\"[^\"]+/
4843 * Only with --members:
4844 * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/
4845 * Idea by Diez B. Roggisch (2001)
4851 register char *cp, *name;
4852 bool search_identifier = FALSE;
4854 LOOP_ON_INPUT_LINES (inf, lb, cp)
4856 cp = skip_spaces (cp);
4858 if (search_identifier
4861 while (!notinname (*cp))
4863 make_tag (name, cp - name, TRUE,
4864 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4865 search_identifier = FALSE;
4867 else if (LOOKING_AT (cp, "function"))
4870 cp = skip_spaces (cp+1);
4874 while (!notinname (*cp))
4876 make_tag (name, cp - name, TRUE,
4877 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4880 search_identifier = TRUE;
4882 else if (LOOKING_AT (cp, "class"))
4887 while (*cp != '\0' && !iswhite (*cp))
4889 make_tag (name, cp - name, FALSE,
4890 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4893 search_identifier = TRUE;
4895 else if (strneq (cp, "define", 6)
4896 && (cp = skip_spaces (cp+6))
4898 && (*cp == '"' || *cp == '\''))
4902 while (*cp != quote && *cp != '\0')
4904 make_tag (name, cp - name, FALSE,
4905 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4908 && LOOKING_AT (cp, "var")
4912 while (!notinname(*cp))
4914 make_tag (name, cp - name, FALSE,
4915 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
4922 * Cobol tag functions
4923 * We could look for anything that could be a paragraph name.
4924 * i.e. anything that starts in column 8 is one word and ends in a full stop.
4925 * Idea by Corny de Souza (1993)
4928 Cobol_paragraphs (inf)
4931 register char *bp, *ep;
4933 LOOP_ON_INPUT_LINES (inf, lb, bp)
4939 /* If eoln, compiler option or comment ignore whole line. */
4940 if (bp[-1] != ' ' || !ISALNUM (bp[0]))
4943 for (ep = bp; ISALNUM (*ep) || *ep == '-'; ep++)
4946 make_tag (bp, ep - bp, TRUE,
4947 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
4954 * Ideas by Assar Westerlund <assar@sics.se> (2001)
4957 Makefile_targets (inf)
4962 LOOP_ON_INPUT_LINES (inf, lb, bp)
4964 if (*bp == '\t' || *bp == '#')
4966 while (*bp != '\0' && *bp != '=' && *bp != ':')
4968 if (*bp == ':' || (globals && *bp == '='))
4970 /* We should detect if there is more than one tag, but we do not.
4971 We just skip initial and final spaces. */
4972 char * namestart = skip_spaces (lb.buffer);
4973 while (--bp > namestart)
4974 if (!notinname (*bp))
4976 make_tag (namestart, bp - namestart + 1, TRUE,
4977 lb.buffer, bp - lb.buffer + 2, lineno, linecharno);
4985 * Original code by Mosur K. Mohan (1989)
4987 * Locates tags for procedures & functions. Doesn't do any type- or
4988 * var-definitions. It does look for the keyword "extern" or
4989 * "forward" immediately following the procedure statement; if found,
4990 * the tag is skipped.
4993 Pascal_functions (inf)
4996 linebuffer tline; /* mostly copied from C_entries */
4998 int save_lineno, namelen, taglen;
5001 bool /* each of these flags is TRUE if: */
5002 incomment, /* point is inside a comment */
5003 inquote, /* point is inside '..' string */
5004 get_tagname, /* point is after PROCEDURE/FUNCTION
5005 keyword, so next item = potential tag */
5006 found_tag, /* point is after a potential tag */
5007 inparms, /* point is within parameter-list */
5008 verify_tag; /* point has passed the parm-list, so the
5009 next token will determine whether this
5010 is a FORWARD/EXTERN to be ignored, or
5011 whether it is a real tag */
5013 save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */
5014 name = NULL; /* keep compiler quiet */
5017 linebuffer_init (&tline);
5019 incomment = inquote = FALSE;
5020 found_tag = FALSE; /* have a proc name; check if extern */
5021 get_tagname = FALSE; /* found "procedure" keyword */
5022 inparms = FALSE; /* found '(' after "proc" */
5023 verify_tag = FALSE; /* check if "extern" is ahead */
5026 while (!feof (inf)) /* long main loop to get next char */
5029 if (c == '\0') /* if end of line */
5031 readline (&lb, inf);
5035 if (!((found_tag && verify_tag)
5037 c = *dbp++; /* only if don't need *dbp pointing
5038 to the beginning of the name of
5039 the procedure or function */
5043 if (c == '}') /* within { } comments */
5045 else if (c == '*' && *dbp == ')') /* within (* *) comments */
5062 inquote = TRUE; /* found first quote */
5064 case '{': /* found open { comment */
5068 if (*dbp == '*') /* found open (* comment */
5073 else if (found_tag) /* found '(' after tag, i.e., parm-list */
5076 case ')': /* end of parms list */
5081 if (found_tag && !inparms) /* end of proc or fn stmt */
5090 if (found_tag && verify_tag && (*dbp != ' '))
5092 /* Check if this is an "extern" declaration. */
5095 if (lowcase (*dbp == 'e'))
5097 if (nocase_tail ("extern")) /* superfluous, really! */
5103 else if (lowcase (*dbp) == 'f')
5105 if (nocase_tail ("forward")) /* check for forward reference */
5111 if (found_tag && verify_tag) /* not external proc, so make tag */
5115 make_tag (name, namelen, TRUE,
5116 tline.buffer, taglen, save_lineno, save_lcno);
5120 if (get_tagname) /* grab name of proc or fn */
5127 /* Find block name. */
5128 for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++)
5131 /* Save all values for later tagging. */
5132 linebuffer_setlen (&tline, lb.len+1);
5133 xstrncpy(tline.buffer, lb.buffer, lb.len+1);
5134 save_lineno = lineno;
5135 save_lcno = linecharno;
5136 name = tline.buffer + (dbp - lb.buffer);
5138 taglen = cp - lb.buffer + 1;
5140 dbp = cp; /* set dbp to e-o-token */
5141 get_tagname = FALSE;
5145 /* And proceed to check for "extern". */
5147 else if (!incomment && !inquote && !found_tag)
5149 /* Check for proc/fn keywords. */
5150 switch (lowcase (c))
5153 if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */
5157 if (nocase_tail ("unction"))
5164 } /* while not eof */
5166 free (tline.buffer);
5171 * Lisp tag functions
5172 * look for (def or (DEF, quote or QUOTE
5175 static void L_getit __P((void));
5180 if (*dbp == '\'') /* Skip prefix quote */
5182 else if (*dbp == '(')
5185 /* Try to skip "(quote " */
5186 if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE"))
5187 /* Ok, then skip "(" before name in (defstruct (foo)) */
5188 dbp = skip_spaces (dbp);
5190 get_tag (dbp, NULL);
5194 Lisp_functions (inf)
5197 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5202 if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3))
5204 dbp = skip_non_spaces (dbp);
5205 dbp = skip_spaces (dbp);
5210 /* Check for (foo::defmumble name-defined ... */
5213 while (!notinname (*dbp) && *dbp != ':');
5218 while (*dbp == ':');
5220 if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3))
5222 dbp = skip_non_spaces (dbp);
5223 dbp = skip_spaces (dbp);
5233 * Lua script language parsing
5234 * Original code by David A. Capello <dacap@users.sourceforge.net> (2004)
5236 * "function" and "local function" are tags if they start at column 1.
5244 LOOP_ON_INPUT_LINES (inf, lb, bp)
5246 if (bp[0] != 'f' && bp[0] != 'l')
5249 (void)LOOKING_AT (bp, "local"); /* skip possible "local" */
5251 if (LOOKING_AT (bp, "function"))
5259 * Just look for lines where the first character is '/'
5260 * Also look at "defineps" for PSWrap
5262 * Richard Mlynarik <mly@adoc.xerox.com> (1997)
5263 * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999)
5269 register char *bp, *ep;
5271 LOOP_ON_INPUT_LINES (inf, lb, bp)
5276 *ep != '\0' && *ep != ' ' && *ep != '{';
5279 make_tag (bp, ep - bp, TRUE,
5280 lb.buffer, ep - lb.buffer + 1, lineno, linecharno);
5282 else if (LOOKING_AT (bp, "defineps"))
5290 * Ignore anything after \ followed by space or in ( )
5291 * Look for words defined by :
5292 * Look for constant, code, create, defer, value, and variable
5293 * OBP extensions: Look for buffer:, field,
5294 * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004)
5302 LOOP_ON_INPUT_LINES (inf, lb, bp)
5303 while ((bp = skip_spaces (bp))[0] != '\0')
5304 if (bp[0] == '\\' && iswhite(bp[1]))
5305 break; /* read next line */
5306 else if (bp[0] == '(' && iswhite(bp[1]))
5307 do /* skip to ) or eol */
5309 while (*bp != ')' && *bp != '\0');
5310 else if ((bp[0] == ':' && iswhite(bp[1]) && bp++)
5311 || LOOKING_AT_NOCASE (bp, "constant")
5312 || LOOKING_AT_NOCASE (bp, "code")
5313 || LOOKING_AT_NOCASE (bp, "create")
5314 || LOOKING_AT_NOCASE (bp, "defer")
5315 || LOOKING_AT_NOCASE (bp, "value")
5316 || LOOKING_AT_NOCASE (bp, "variable")
5317 || LOOKING_AT_NOCASE (bp, "buffer:")
5318 || LOOKING_AT_NOCASE (bp, "field"))
5319 get_tag (skip_spaces (bp), NULL); /* Yay! A definition! */
5321 bp = skip_non_spaces (bp);
5326 * Scheme tag functions
5327 * look for (def... xyzzy
5329 * (def ... ((...(xyzzy ....
5331 * Original code by Ken Haase (1985?)
5334 Scheme_functions (inf)
5339 LOOP_ON_INPUT_LINES (inf, lb, bp)
5341 if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4))
5343 bp = skip_non_spaces (bp+4);
5344 /* Skip over open parens and white space */
5345 while (notinname (*bp))
5349 if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!"))
5355 /* Find tags in TeX and LaTeX input files. */
5357 /* TEX_toktab is a table of TeX control sequences that define tags.
5358 * Each entry records one such control sequence.
5360 * Original code from who knows whom.
5362 * Stefan Monnier (2002)
5365 static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */
5367 /* Default set of control sequences to put into TEX_toktab.
5368 The value of environment var TEXTAGS is prepended to this. */
5369 static char *TEX_defenv = "\
5370 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
5371 :part:appendix:entry:index:def\
5372 :newcommand:renewcommand:newenvironment:renewenvironment";
5374 static void TEX_mode __P((FILE *));
5375 static void TEX_decode_env __P((char *, char *));
5377 static char TEX_esc = '\\';
5378 static char TEX_opgrp = '{';
5379 static char TEX_clgrp = '}';
5382 * TeX/LaTeX scanning loop.
5391 /* Select either \ or ! as escape character. */
5394 /* Initialize token table once from environment. */
5395 if (TEX_toktab == NULL)
5396 TEX_decode_env ("TEXTAGS", TEX_defenv);
5398 LOOP_ON_INPUT_LINES (inf, lb, cp)
5400 /* Look at each TEX keyword in line. */
5403 /* Look for a TEX escape. */
5404 while (*cp++ != TEX_esc)
5405 if (cp[-1] == '\0' || cp[-1] == '%')
5408 for (key = TEX_toktab; key->buffer != NULL; key++)
5409 if (strneq (cp, key->buffer, key->len))
5412 int namelen, linelen;
5415 cp = skip_spaces (cp + key->len);
5416 if (*cp == TEX_opgrp)
5422 (!iswhite (*p) && *p != '#' &&
5423 *p != TEX_opgrp && *p != TEX_clgrp);
5428 if (!opgrp || *p == TEX_clgrp)
5430 while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp)
5432 linelen = p - lb.buffer + 1;
5434 make_tag (cp, namelen, TRUE,
5435 lb.buffer, linelen, lineno, linecharno);
5436 goto tex_next_line; /* We only tag a line once */
5444 #define TEX_LESC '\\'
5445 #define TEX_SESC '!'
5447 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
5448 chars accordingly. */
5455 while ((c = getc (inf)) != EOF)
5457 /* Skip to next line if we hit the TeX comment char. */
5459 while (c != '\n' && c != EOF)
5461 else if (c == TEX_LESC || c == TEX_SESC )
5477 /* If the input file is compressed, inf is a pipe, and rewind may fail.
5478 No attempt is made to correct the situation. */
5482 /* Read environment and prepend it to the default string.
5483 Build token table. */
5485 TEX_decode_env (evarname, defenv)
5489 register char *env, *p;
5492 /* Append default string to environment. */
5493 env = getenv (evarname);
5499 env = concat (oldenv, defenv, "");
5502 /* Allocate a token table */
5503 for (len = 1, p = env; p;)
5504 if ((p = etags_strchr (p, ':')) && *++p != '\0')
5506 TEX_toktab = xnew (len, linebuffer);
5508 /* Unpack environment string into token table. Be careful about */
5509 /* zero-length strings (leading ':', "::" and trailing ':') */
5510 for (i = 0; *env != '\0';)
5512 p = etags_strchr (env, ':');
5513 if (!p) /* End of environment string. */
5514 p = env + strlen (env);
5516 { /* Only non-zero strings. */
5517 TEX_toktab[i].buffer = savenstr (env, p - env);
5518 TEX_toktab[i].len = p - env;
5525 TEX_toktab[i].buffer = NULL; /* Mark end of table. */
5526 TEX_toktab[i].len = 0;
5533 /* Texinfo support. Dave Love, Mar. 2000. */
5539 LOOP_ON_INPUT_LINES (inf, lb, cp)
5540 if (LOOKING_AT (cp, "@node"))
5543 while (*cp != '\0' && *cp != ',')
5545 make_tag (start, cp - start, TRUE,
5546 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
5553 * Contents of <title>, <h1>, <h2>, <h3> are tags.
5554 * Contents of <a name=xxx> are tags with name xxx.
5556 * Francesco Potortì, 2002.
5562 bool getnext = FALSE; /* next text outside of HTML tags is a tag */
5563 bool skiptag = FALSE; /* skip to the end of the current HTML tag */
5564 bool intag = FALSE; /* inside an html tag, looking for ID= */
5565 bool inanchor = FALSE; /* when INTAG, is an anchor, look for NAME= */
5569 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5571 LOOP_ON_INPUT_LINES (inf, lb, dbp)
5572 for (;;) /* loop on the same line */
5574 if (skiptag) /* skip HTML tag */
5576 while (*dbp != '\0' && *dbp != '>')
5582 continue; /* look on the same line */
5584 break; /* go to next line */
5587 else if (intag) /* look for "name=" or "id=" */
5589 while (*dbp != '\0' && *dbp != '>'
5590 && lowcase (*dbp) != 'n' && lowcase (*dbp) != 'i')
5593 break; /* go to next line */
5598 continue; /* look on the same line */
5600 if ((inanchor && LOOKING_AT_NOCASE (dbp, "name="))
5601 || LOOKING_AT_NOCASE (dbp, "id="))
5603 bool quoted = (dbp[0] == '"');
5606 for (end = ++dbp; *end != '\0' && *end != '"'; end++)
5609 for (end = dbp; *end != '\0' && intoken (*end); end++)
5611 linebuffer_setlen (&token_name, end - dbp+1);
5612 xstrncpy (token_name.buffer, dbp, end - dbp+1);
5613 token_name.buffer[end - dbp] = '\0';
5616 intag = FALSE; /* we found what we looked for */
5617 skiptag = TRUE; /* skip to the end of the tag */
5618 getnext = TRUE; /* then grab the text */
5619 continue; /* look on the same line */
5624 else if (getnext) /* grab next tokens and tag them */
5626 dbp = skip_spaces (dbp);
5628 break; /* go to next line */
5632 inanchor = (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]));
5633 continue; /* look on the same line */
5636 for (end = dbp + 1; *end != '\0' && *end != '<'; end++)
5638 make_tag (token_name.buffer, token_name.len, TRUE,
5639 dbp, end - dbp, lineno, linecharno);
5640 linebuffer_setlen (&token_name, 0); /* no name in buffer */
5642 break; /* go to next line */
5645 else /* look for an interesting HTML tag */
5647 while (*dbp != '\0' && *dbp != '<')
5650 break; /* go to next line */
5652 if (lowcase (dbp[1]) == 'a' && !intoken (dbp[2]))
5655 continue; /* look on the same line */
5657 else if (LOOKING_AT_NOCASE (dbp, "<title>")
5658 || LOOKING_AT_NOCASE (dbp, "<h1>")
5659 || LOOKING_AT_NOCASE (dbp, "<h2>")
5660 || LOOKING_AT_NOCASE (dbp, "<h3>"))
5664 continue; /* look on the same line */
5675 * Assumes that the predicate or rule starts at column 0.
5676 * Only the first clause of a predicate or rule is added.
5677 * Original code by Sunichirou Sugou (1989)
5678 * Rewritten by Anders Lindgren (1996)
5680 static int prolog_pr __P((char *, char *));
5681 static void prolog_skip_comment __P((linebuffer *, FILE *));
5682 static int prolog_atom __P((char *, int));
5685 Prolog_functions (inf)
5696 LOOP_ON_INPUT_LINES (inf, lb, cp)
5698 if (cp[0] == '\0') /* Empty line */
5700 else if (iswhite (cp[0])) /* Not a predicate */
5702 else if (cp[0] == '/' && cp[1] == '*') /* comment. */
5703 prolog_skip_comment (&lb, inf);
5704 else if ((len = prolog_pr (cp, last)) > 0)
5706 /* Predicate or rule. Store the function name so that we
5707 only generate a tag for the first clause. */
5709 last = xnew(len + 1, char);
5710 else if (len + 1 > allocated)
5711 xrnew (last, len + 1, char);
5712 allocated = len + 1;
5713 xstrncpy (last, cp, len+1);
5721 prolog_skip_comment (plb, inf)
5729 for (cp = plb->buffer; *cp != '\0'; cp++)
5730 if (cp[0] == '*' && cp[1] == '/')
5732 readline (plb, inf);
5738 * A predicate or rule definition is added if it matches:
5739 * <beginning of line><Prolog Atom><whitespace>(
5740 * or <beginning of line><Prolog Atom><whitespace>:-
5742 * It is added to the tags database if it doesn't match the
5743 * name of the previous clause header.
5745 * Return the size of the name of the predicate or rule, or 0 if no
5751 char *last; /* Name of last clause. */
5756 pos = prolog_atom (s, 0);
5761 pos = skip_spaces (s + pos) - s;
5764 || (s[pos] == '(' && (pos += 1))
5765 || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2)))
5766 && (last == NULL /* save only the first clause */
5767 || len != (int)strlen (last)
5768 || !strneq (s, last, len)))
5770 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5778 * Consume a Prolog atom.
5779 * Return the number of bytes consumed, or -1 if there was an error.
5781 * A prolog atom, in this context, could be one of:
5782 * - An alphanumeric sequence, starting with a lower case letter.
5783 * - A quoted arbitrary string. Single quotes can escape themselves.
5784 * Backslash quotes everything.
5787 prolog_atom (s, pos)
5795 if (ISLOWER(s[pos]) || (s[pos] == '_'))
5797 /* The atom is unquoted. */
5799 while (ISALNUM(s[pos]) || (s[pos] == '_'))
5803 return pos - origpos;
5805 else if (s[pos] == '\'')
5816 pos++; /* A double quote */
5818 else if (s[pos] == '\0')
5819 /* Multiline quoted atoms are ignored. */
5821 else if (s[pos] == '\\')
5823 if (s[pos+1] == '\0')
5830 return pos - origpos;
5838 * Support for Erlang
5840 * Generates tags for functions, defines, and records.
5841 * Assumes that Erlang functions start at column 0.
5842 * Original code by Anders Lindgren (1996)
5844 static int erlang_func __P((char *, char *));
5845 static void erlang_attribute __P((char *));
5846 static int erlang_atom __P((char *));
5849 Erlang_functions (inf)
5860 LOOP_ON_INPUT_LINES (inf, lb, cp)
5862 if (cp[0] == '\0') /* Empty line */
5864 else if (iswhite (cp[0])) /* Not function nor attribute */
5866 else if (cp[0] == '%') /* comment */
5868 else if (cp[0] == '"') /* Sometimes, strings start in column one */
5870 else if (cp[0] == '-') /* attribute, e.g. "-define" */
5872 erlang_attribute (cp);
5879 else if ((len = erlang_func (cp, last)) > 0)
5882 * Function. Store the function name so that we only
5883 * generates a tag for the first clause.
5886 last = xnew (len + 1, char);
5887 else if (len + 1 > allocated)
5888 xrnew (last, len + 1, char);
5889 allocated = len + 1;
5890 xstrncpy (last, cp, allocated);
5898 * A function definition is added if it matches:
5899 * <beginning of line><Erlang Atom><whitespace>(
5901 * It is added to the tags database if it doesn't match the
5902 * name of the previous clause header.
5904 * Return the size of the name of the function, or 0 if no function
5908 erlang_func (s, last)
5910 char *last; /* Name of last clause. */
5915 pos = erlang_atom (s);
5920 pos = skip_spaces (s + pos) - s;
5922 /* Save only the first clause. */
5925 || len != (int)strlen (last)
5926 || !strneq (s, last, len)))
5928 make_tag (s, len, TRUE, s, pos, lineno, linecharno);
5937 * Handle attributes. Currently, tags are generated for defines
5940 * They are on the form:
5941 * -define(foo, bar).
5942 * -define(Foo(M, N), M+N).
5943 * -record(graph, {vtab = notable, cyclic = true}).
5946 erlang_attribute (s)
5951 if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record"))
5954 int len = erlang_atom (skip_spaces (cp));
5956 make_tag (cp, len, TRUE, s, cp + len - s, lineno, linecharno);
5963 * Consume an Erlang atom (or variable).
5964 * Return the number of bytes consumed, or -1 if there was an error.
5972 if (ISALPHA (s[pos]) || s[pos] == '_')
5974 /* The atom is unquoted. */
5977 while (ISALNUM (s[pos]) || s[pos] == '_');
5979 else if (s[pos] == '\'')
5981 for (pos++; s[pos] != '\''; pos++)
5982 if (s[pos] == '\0' /* multiline quoted atoms are ignored */
5983 || (s[pos] == '\\' && s[++pos] == '\0'))
5992 static char *scan_separators __P((char *));
5993 static void add_regex __P((char *, language *));
5994 static char *substitute __P((char *, char *, struct re_registers *));
5997 * Take a string like "/blah/" and turn it into "blah", verifying
5998 * that the first and last characters are the same, and handling
5999 * quoted separator characters. Actually, stops on the occurrence of
6000 * an unquoted separator. Also process \t, \n, etc. and turn into
6001 * appropriate characters. Works in place. Null terminates name string.
6002 * Returns pointer to terminating separator, or NULL for
6003 * unterminated regexps.
6006 scan_separators (name)
6010 char *copyto = name;
6011 bool quoted = FALSE;
6013 for (++name; *name != '\0'; ++name)
6019 case 'a': *copyto++ = '\007'; break; /* BEL (bell) */
6020 case 'b': *copyto++ = '\b'; break; /* BS (back space) */
6021 case 'd': *copyto++ = 0177; break; /* DEL (delete) */
6022 case 'e': *copyto++ = 033; break; /* ESC (delete) */
6023 case 'f': *copyto++ = '\f'; break; /* FF (form feed) */
6024 case 'n': *copyto++ = '\n'; break; /* NL (new line) */
6025 case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */
6026 case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */
6027 case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */
6033 /* Something else is quoted, so preserve the quote. */
6041 else if (*name == '\\')
6043 else if (*name == sep)
6049 name = NULL; /* signal unterminated regexp */
6051 /* Terminate copied string. */
6056 /* Look at the argument of --regex or --no-regex and do the right
6057 thing. Same for each line of a regexp file. */
6059 analyse_regex (regex_arg)
6062 if (regex_arg == NULL)
6064 free_regexps (); /* --no-regex: remove existing regexps */
6068 /* A real --regexp option or a line in a regexp file. */
6069 switch (regex_arg[0])
6071 /* Comments in regexp file or null arg to --regex. */
6077 /* Read a regex file. This is recursive and may result in a
6078 loop, which will stop when the file descriptors are exhausted. */
6082 linebuffer regexbuf;
6083 char *regexfile = regex_arg + 1;
6085 /* regexfile is a file containing regexps, one per line. */
6086 regexfp = fopen (regexfile, "r");
6087 if (regexfp == NULL)
6092 linebuffer_init (®exbuf);
6093 while (readline_internal (®exbuf, regexfp) > 0)
6094 analyse_regex (regexbuf.buffer);
6095 free (regexbuf.buffer);
6100 /* Regexp to be used for a specific language only. */
6104 char *lang_name = regex_arg + 1;
6107 for (cp = lang_name; *cp != '}'; cp++)
6110 error ("unterminated language name in regex: %s", regex_arg);
6114 lang = get_language_from_langname (lang_name);
6117 add_regex (cp, lang);
6121 /* Regexp to be used for any language. */
6123 add_regex (regex_arg, NULL);
6128 /* Separate the regexp pattern, compile it,
6129 and care for optional name and modifiers. */
6131 add_regex (regexp_pattern, lang)
6132 char *regexp_pattern;
6135 static struct re_pattern_buffer zeropattern;
6136 char sep, *pat, *name, *modifiers;
6138 struct re_pattern_buffer *patbuf;
6141 force_explicit_name = TRUE, /* do not use implicit tag names */
6142 ignore_case = FALSE, /* case is significant */
6143 multi_line = FALSE, /* matches are done one line at a time */
6144 single_line = FALSE; /* dot does not match newline */
6147 if (strlen(regexp_pattern) < 3)
6149 error ("null regexp", (char *)NULL);
6152 sep = regexp_pattern[0];
6153 name = scan_separators (regexp_pattern);
6156 error ("%s: unterminated regexp", regexp_pattern);
6161 error ("null name for regexp \"%s\"", regexp_pattern);
6164 modifiers = scan_separators (name);
6165 if (modifiers == NULL) /* no terminating separator --> no name */
6171 modifiers += 1; /* skip separator */
6173 /* Parse regex modifiers. */
6174 for (; modifiers[0] != '\0'; modifiers++)
6175 switch (modifiers[0])
6178 if (modifiers == name)
6179 error ("forcing explicit tag name but no name, ignoring", NULL);
6180 force_explicit_name = TRUE;
6190 need_filebuf = TRUE;
6195 wrongmod[0] = modifiers[0];
6197 error ("invalid regexp modifier `%s', ignoring", wrongmod);
6202 patbuf = xnew (1, struct re_pattern_buffer);
6203 *patbuf = zeropattern;
6206 static char lc_trans[CHARS];
6208 for (i = 0; i < CHARS; i++)
6209 lc_trans[i] = lowcase (i);
6210 patbuf->translate = lc_trans; /* translation table to fold case */
6214 pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */
6216 pat = regexp_pattern;
6219 re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE);
6221 re_set_syntax (RE_SYNTAX_EMACS);
6223 err = re_compile_pattern (pat, strlen (regexp_pattern), patbuf);
6228 error ("%s while compiling pattern", err);
6233 p_head = xnew (1, regexp);
6234 p_head->pattern = savestr (regexp_pattern);
6235 p_head->p_next = rp;
6236 p_head->lang = lang;
6237 p_head->pat = patbuf;
6238 p_head->name = savestr (name);
6239 p_head->error_signaled = FALSE;
6240 p_head->force_explicit_name = force_explicit_name;
6241 p_head->ignore_case = ignore_case;
6242 p_head->multi_line = multi_line;
6246 * Do the substitutions indicated by the regular expression and
6250 substitute (in, out, regs)
6252 struct re_registers *regs;
6255 int size, dig, diglen;
6258 size = strlen (out);
6260 /* Pass 1: figure out how much to allocate by finding all \N strings. */
6261 if (out[size - 1] == '\\')
6262 fatal ("pattern error in \"%s\"", out);
6263 for (t = etags_strchr (out, '\\');
6265 t = etags_strchr (t + 2, '\\'))
6269 diglen = regs->end[dig] - regs->start[dig];
6275 /* Allocate space and do the substitutions. */
6277 size_t avail = size + 1;
6278 result = xnew (avail, char);
6280 for (t = result; *out != '\0'; out++)
6281 if (*out == '\\' && ISDIGIT (*++out))
6284 diglen = regs->end[dig] - regs->start[dig];
6285 xstrncpy (t, in + regs->start[dig], avail);
6295 assert (t <= result + size);
6296 assert (t - result == (int)strlen (result));
6301 /* Deallocate all regexps. */
6306 while (p_head != NULL)
6308 rp = p_head->p_next;
6309 free (p_head->pattern);
6310 free (p_head->name);
6318 * Reads the whole file as a single string from `filebuf' and looks for
6319 * multi-line regular expressions, creating tags on matches.
6320 * readline already dealt with normal regexps.
6322 * Idea by Ben Wing <ben@666.com> (2002).
6325 regex_tag_multiline ()
6327 char *buffer = filebuf.buffer;
6331 for (rp = p_head; rp != NULL; rp = rp->p_next)
6335 if (!rp->multi_line)
6336 continue; /* skip normal regexps */
6338 /* Generic initialisations before parsing file from memory. */
6339 lineno = 1; /* reset global line number */
6340 charno = 0; /* reset global char number */
6341 linecharno = 0; /* reset global char number of line start */
6343 /* Only use generic regexps or those for the current language. */
6344 if (rp->lang != NULL && rp->lang != curfdp->lang)
6347 while (match >= 0 && match < filebuf.len)
6349 match = re_search (rp->pat, buffer, filebuf.len, charno,
6350 filebuf.len - match, &rp->regs);
6355 if (!rp->error_signaled)
6357 error ("regexp stack overflow while matching \"%s\"",
6359 rp->error_signaled = TRUE;
6366 if (match == rp->regs.end[0])
6368 if (!rp->error_signaled)
6370 error ("regexp matches the empty string: \"%s\"",
6372 rp->error_signaled = TRUE;
6374 match = -3; /* exit from while loop */
6378 /* Match occurred. Construct a tag. */
6379 while (charno < rp->regs.end[0])
6380 if (buffer[charno++] == '\n')
6381 lineno++, linecharno = charno;
6382 if (! rp->name || rp->name[0] == '\0')
6384 else /* make a named tag */
6385 name = substitute (buffer, rp->name, &rp->regs);
6386 if (rp->force_explicit_name)
6387 /* Force explicit tag name, if a name
6389 pfnote (name, TRUE, buffer + linecharno,
6390 charno - linecharno + 1, lineno,
6392 else if(name == NULL)
6395 make_tag (name, strlen (name), TRUE,
6396 buffer + linecharno,
6397 charno - linecharno + 1,
6398 lineno, linecharno);
6412 register int len = 0;
6414 while (*cp != '\0' && lowcase (*cp) == lowcase (dbp[len]))
6416 if (*cp == '\0' && !intoken (dbp[len]))
6425 get_tag (bp, namepp)
6429 register char *cp = bp;
6433 /* Go till you get to white space or a syntactic break */
6434 for (cp = bp + 1; !notinname (*cp); cp++)
6436 make_tag (bp, cp - bp, TRUE,
6437 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
6441 *namepp = savenstr (bp, cp - bp);
6445 * Read a line of text from `stream' into `lbp', excluding the
6446 * newline or CR-NL, if any. Return the number of characters read from
6447 * `stream', which is the length of the line including the newline.
6449 * On DOS or Windows we do not count the CR character, if any before the
6450 * NL, in the returned length; this mirrors the behavior of Emacs on those
6451 * platforms (for text files, it translates CR-NL to NL as it reads in the
6454 * If multi-line regular expressions are requested, each line read is
6455 * appended to `filebuf'.
6458 readline_internal (lbp, stream)
6460 register FILE *stream;
6462 char *buffer = lbp->buffer;
6463 register char *p = lbp->buffer;
6464 register char *pend;
6467 pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */
6471 register int c = getc (stream);
6474 /* We're at the end of linebuffer: expand it. */
6476 xrnew (buffer, lbp->size, char);
6477 p += buffer - lbp->buffer;
6478 pend = buffer + lbp->size;
6479 lbp->buffer = buffer;
6489 if (p > buffer && p[-1] == '\r')
6503 lbp->len = p - buffer;
6505 if (need_filebuf /* we need filebuf for multi-line regexps */
6506 && chars_deleted > 0) /* not at EOF */
6508 size_t need = filebuf.len + lbp->len + 1; /* +1 for \n */
6509 while (filebuf.size <= need )
6511 /* Expand filebuf. */
6512 xrnew (filebuf.buffer, filebuf.size, char);
6513 xstrncpy (filebuf.buffer + filebuf.len, lbp->buffer, filebuf.size - filebuf.len);
6514 filebuf.len += lbp->len;
6515 filebuf.buffer[filebuf.len++] = '\n';
6516 filebuf.buffer[filebuf.len] = '\0';
6519 return lbp->len + chars_deleted;
6523 * Like readline_internal, above, but in addition try to match the
6524 * input line against relevant regular expressions and manage #line
6528 readline (lbp, stream)
6534 linecharno = charno; /* update global char number of line start */
6535 result = readline_internal (lbp, stream); /* read line */
6536 lineno += 1; /* increment global line number */
6537 charno += result; /* increment global char number */
6539 /* Honour #line directives. */
6540 if (!no_line_directive)
6542 static bool discard_until_line_directive;
6544 /* Check whether this is a #line directive. */
6545 if (result > 12 && strneq (lbp->buffer, "#line ", 6))
6550 if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1
6551 && start > 0) /* double quote character found */
6553 char *endp = lbp->buffer + start;
6555 while ((endp = etags_strchr (endp, '"')) != NULL
6556 && endp[-1] == '\\')
6559 /* Ok, this is a real #line directive. Let's deal with it. */
6561 char *taggedabsname; /* absolute name of original file */
6562 char *taggedfname; /* name of original file as given */
6563 char *name; /* temp var */
6565 discard_until_line_directive = FALSE; /* found it */
6566 name = lbp->buffer + start;
6568 canonicalize_filename (name);
6569 taggedabsname = absolute_filename (name, tagfiledir);
6570 if (filename_is_absolute (name)
6571 || filename_is_absolute (curfdp->infname))
6572 taggedfname = savestr (taggedabsname);
6574 taggedfname = relative_filename (taggedabsname,tagfiledir);
6576 if (streq (curfdp->taggedfname, taggedfname))
6577 /* The #line directive is only a line number change. We
6578 deal with this afterwards. */
6581 /* The tags following this #line directive should be
6582 attributed to taggedfname. In order to do this, set
6583 curfdp accordingly. */
6585 fdesc *fdp; /* file description pointer */
6587 /* Go look for a file description already set up for the
6588 file indicated in the #line directive. If there is
6589 one, use it from now until the next #line
6591 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6592 if (streq (fdp->infname, curfdp->infname)
6593 && streq (fdp->taggedfname, taggedfname))
6594 /* If we remove the second test above (after the &&)
6595 then all entries pertaining to the same file are
6596 coalesced in the tags file. If we use it, then
6597 entries pertaining to the same file but generated
6598 from different files (via #line directives) will
6599 go into separate sections in the tags file. These
6600 alternatives look equivalent. The first one
6601 destroys some apparently useless information. */
6607 /* Else, if we already tagged the real file, skip all
6608 input lines until the next #line directive. */
6609 if (fdp == NULL) /* not found */
6610 for (fdp = fdhead; fdp != NULL; fdp = fdp->next)
6611 if (streq (fdp->infabsname, taggedabsname))
6613 discard_until_line_directive = TRUE;
6617 /* Else create a new file description and use that from
6618 now on, until the next #line directive. */
6619 if (fdp == NULL) /* not found */
6622 fdhead = xnew (1, fdesc);
6623 *fdhead = *curfdp; /* copy curr. file description */
6625 fdhead->infname = savestr (curfdp->infname);
6626 fdhead->infabsname = savestr (curfdp->infabsname);
6627 fdhead->infabsdir = savestr (curfdp->infabsdir);
6628 fdhead->taggedfname = taggedfname;
6629 fdhead->usecharno = FALSE;
6630 fdhead->prop = NULL;
6631 fdhead->written = FALSE;
6635 free (taggedabsname);
6637 readline (lbp, stream);
6639 } /* if a real #line directive */
6640 } /* if #line is followed by a a number */
6641 } /* if line begins with "#line " */
6643 /* If we are here, no #line directive was found. */
6644 if (discard_until_line_directive)
6648 /* Do a tail recursion on ourselves, thus discarding the contents
6649 of the line buffer. */
6650 readline (lbp, stream);
6654 discard_until_line_directive = FALSE;
6657 } /* if #line directives should be considered */
6664 /* Match against relevant regexps. */
6666 for (rp = p_head; rp != NULL; rp = rp->p_next)
6668 /* Only use generic regexps or those for the current language.
6669 Also do not use multiline regexps, which is the job of
6670 regex_tag_multiline. */
6671 if ((rp->lang != NULL && rp->lang != fdhead->lang)
6675 match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs);
6680 if (!rp->error_signaled)
6682 error ("regexp stack overflow while matching \"%s\"",
6684 rp->error_signaled = TRUE;
6691 /* Empty string matched. */
6692 if (!rp->error_signaled)
6694 error ("regexp matches the empty string: \"%s\"", rp->pattern);
6695 rp->error_signaled = TRUE;
6699 /* Match occurred. Construct a tag. */
6700 if (rp->name[0] != '\0')
6701 /* make a named tag */
6702 name = substitute (lbp->buffer, rp->name, &rp->regs);
6703 if (rp->force_explicit_name)
6704 /* Force explicit tag name, if a name is there. */
6705 pfnote (name, TRUE, lbp->buffer, match, lineno, linecharno);
6707 make_tag (name, strlen (name), TRUE,
6708 lbp->buffer, match, lineno, linecharno);
6712 make_tag (rp->name, strlen (rp->name), TRUE,
6713 lbp->buffer, match, lineno, linecharno);
6722 * Return a pointer to a space of size strlen(cp)+1 allocated
6723 * with xnew where the string CP has been copied.
6729 return savenstr (cp, strlen (cp));
6733 * Return a pointer to a space of size LEN+1 allocated with xnew where
6734 * the string CP has been copied for at most the first LEN characters.
6743 dp = xnew (len + 1, char);
6744 xstrncpy (dp, cp, len+1);
6750 /* Skip spaces (end of string is not space), return new pointer. */
6755 while (iswhite (*cp))
6760 /* Skip non spaces, except end of string, return new pointer. */
6762 skip_non_spaces (cp)
6765 while (*cp != '\0' && !iswhite (*cp))
6770 /* Print error message and exit. */
6776 exit (EXIT_FAILURE);
6784 exit (EXIT_FAILURE);
6788 suggest_asking_for_help ()
6790 fprintf (stderr, "\tTry `%s %s' for a complete list of options.\n",
6791 progname, NO_LONG_OPTIONS ? "-h" : "--help");
6792 exit (EXIT_FAILURE);
6795 /* Print error message. `s1' is printf control string, `s2' is arg for it. */
6798 const char *s1, *s2;
6800 fprintf (stderr, "%s: ", progname);
6801 fprintf (stderr, s1, s2);
6802 fprintf (stderr, "\n");
6805 /* Return a newly-allocated string whose contents
6806 concatenate those of s1, s2, s3. */
6811 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
6812 char *result = xnew (len1 + len2 + len3 + 1, char);
6814 xstrncpy(result, s1, len1+1);
6815 xstrncpy(result + len1, s2, len2+1);
6816 xstrncpy(result + len1 + len2, s3, len3+1);
6817 result[len1 + len2 + len3] = '\0';
6823 /* Does the same work as the system V getcwd, but does not need to
6824 guess the buffer size in advance. */
6830 char *path = xnew (bufsize, char);
6832 while (getcwd (path, bufsize) == NULL)
6834 if (errno != ERANGE)
6838 path = xnew (bufsize, char);
6841 canonicalize_filename (path);
6844 #else /* not HAVE_GETCWD */
6848 linebuffer_init (&path);
6849 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
6850 if (pipe == NULL || readline_internal (&path, pipe) == 0)
6855 #endif /* not HAVE_GETCWD */
6858 /* Return a newly allocated string containing the file name of FILE
6859 relative to the absolute directory DIR (which should end with a slash). */
6861 relative_filename (file, dir)
6864 char *fp, *dp, *afn, *res;
6868 /* Find the common root of file and dir (with a trailing slash). */
6869 afn = absolute_filename (file, cwd);
6872 while (*fp++ == *dp++)
6874 fp--, dp--; /* back to the first differing char */
6875 do /* look at the equal chars until '/' */
6878 fp ++; /* Advance past the '/' */
6880 /* Build a sequence of "../" strings for the resulting relative file name. */
6882 while ((dp = etags_strchr (dp + 1, '/')) != NULL)
6884 res_left = 3 * i + strlen(fp);
6885 res = xnew( res_left + 1, char);
6887 for ( ; i-- > 0 ; res_left -= 3 )
6888 strncat(res, "../", res_left );
6890 /* Add the file name relative to the common root of file and dir. */
6891 strncat(res, fp, res_left);
6897 /* Return a newly allocated string containing the absolute file name
6898 of FILE given DIR (which should end with a slash). */
6900 absolute_filename (file, dir)
6903 char *slashp, *cp, *res;
6905 if (filename_is_absolute (file))
6906 res = savestr (file);
6908 res = concat (dir, file, "");
6910 /* Delete the "/dirname/.." and "/." substrings. */
6911 slashp = etags_strchr (res, '/');
6912 while (slashp != NULL && slashp[0] != '\0')
6914 if (slashp[1] == '.')
6916 if (slashp[2] == '.'
6917 && (slashp[3] == '/' || slashp[3] == '\0'))
6922 while (cp >= res && !filename_is_absolute (cp));
6924 cp = slashp; /* the absolute name begins with "/.." */
6926 memmove(cp, slashp,strlen(slashp)+1);
6930 else if (slashp[2] == '/' || slashp[2] == '\0')
6932 strcpy (slashp, slashp + 2);
6937 slashp = etags_strchr (slashp + 1, '/');
6940 if (res[0] == '\0') /* just a safety net: should never happen */
6943 return savestr ("/");
6949 /* Return a newly allocated string containing the absolute
6950 file name of dir where FILE resides given DIR (which should
6951 end with a slash). */
6953 absolute_dirname (file, dir)
6959 slashp = etags_strrchr (file, '/');
6961 return savestr (dir);
6964 res = absolute_filename (file, dir);
6970 /* Whether the argument string is an absolute file name. The argument
6971 string must have been canonicalized with canonicalize_filename. */
6973 filename_is_absolute (fn)
6976 return (fn[0] == '/');
6979 /* Upcase DOS drive letter and collapse separators into single slashes.
6982 canonicalize_filename (fn)
6988 /* Collapse multiple separators into a single slash. */
6989 for (cp = fn; *cp != '\0'; cp++, fn++)
6993 while (cp[1] == sep)
7002 /* Initialize a linebuffer for use. */
7004 linebuffer_init (lbp)
7007 lbp->size = (DEBUG) ? 3 : 200;
7008 lbp->buffer = xnew (lbp->size, char);
7009 lbp->buffer[0] = '\0';
7013 /* Set the minimum size of a string contained in a linebuffer. */
7015 linebuffer_setlen (lbp, toksize)
7019 while (lbp->size <= toksize)
7021 xrnew (lbp->buffer, lbp->size, char);
7025 /* Like malloc but get fatal error if memory is exhausted. */
7030 PTR result = (PTR) malloc (size);
7032 fatal ("virtual memory exhausted", (char *)NULL);
7037 xrealloc (ptr, size)
7041 PTR result = (PTR) realloc (ptr, size);
7043 fatal ("virtual memory exhausted", (char *)NULL);
7049 * indent-tabs-mode: t
7052 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp")
7056 /* etags.c ends here */