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