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