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