(tmm-add-prompt): If tmm-completion-prompt is nil,
[emacs.git] / lib-src / etags.c
blobe2737a3e66723b4de0f09524122f68e5510689b3
1 /* Tags file maker to go with GNU Emacs
2 Copyright (C) 1984, 87, 88, 89, 93, 94, 95
3 Free Software Foundation, Inc. and Ken Arnold
5 This file is not considered part of GNU Emacs.
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.
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.
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. */
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 * Sam Kendall added C++.
28 * Francesco Potorti` reorganised C and C++ based on work by Joe Wells.
29 * Regexp tags by Tom Tromey.
31 * Francesco Potorti` (F.Potorti@cnuce.cnr.it) is the current maintainer.
34 char pot_etags_version[] = "@(#) pot revision number is 11.63";
36 #define TRUE 1
37 #define FALSE 0
39 #ifndef DEBUG
40 # define DEBUG FALSE
41 #endif
43 #ifdef MSDOS
44 # include <string.h>
45 # include <fcntl.h>
46 # include <sys/param.h>
47 #endif /* MSDOS */
49 #ifdef WINDOWSNT
50 # include <stdlib.h>
51 # include <fcntl.h>
52 # include <string.h>
53 # include <io.h>
54 # define MAXPATHLEN _MAX_PATH
55 #endif
57 #ifdef HAVE_CONFIG_H
58 # include <config.h>
59 /* On some systems, Emacs defines static as nothing for the sake
60 of unexec. We don't want that here since we don't use unexec. */
61 # undef static
62 #endif
64 #include <stdio.h>
65 #include <ctype.h>
66 #include <errno.h>
67 #ifndef errno
68 extern int errno;
69 #endif
70 #include <sys/types.h>
71 #include <sys/stat.h>
73 #if !defined (S_ISREG) && defined (S_IFREG)
74 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
75 #endif
77 #include <getopt.h>
79 #ifdef ETAGS_REGEXPS
80 # include <regex.h>
81 #endif /* ETAGS_REGEXPS */
83 /* Define CTAGS to make the program "ctags" compatible with the usual one.
84 Let it undefined to make the program "etags", which makes emacs-style
85 tag tables and tags typedefs, #defines and struct/union/enum by default. */
86 #ifdef CTAGS
87 # undef CTAGS
88 # define CTAGS TRUE
89 #else
90 # define CTAGS FALSE
91 #endif
93 /* Exit codes for success and failure. */
94 #ifdef VMS
95 # define GOOD 1
96 # define BAD 0
97 #else
98 # define GOOD 0
99 # define BAD 1
100 #endif
102 /* C extensions. */
103 #define C_PLPL 0x00001 /* C++ */
104 #define C_STAR 0x00003 /* C* */
105 #define YACC 0x10000 /* yacc file */
107 #define streq(s,t) ((DEBUG &&!(s)&&!(t)&&(abort(),1)) || !strcmp(s,t))
108 #define strneq(s,t,n) ((DEBUG &&!(s)&&!(t)&&(abort(),1)) || !strncmp(s,t,n))
110 #define lowcase(c) tolower ((unsigned char)c)
112 #define iswhite(arg) (_wht[arg]) /* T if char is white */
113 #define begtoken(arg) (_btk[arg]) /* T if char can start token */
114 #define intoken(arg) (_itk[arg]) /* T if char can be in token */
115 #define endtoken(arg) (_etk[arg]) /* T if char ends tokens */
117 #ifdef DOS_NT
118 # define absolutefn(fn) (fn[0] == '/' \
119 || (fn[1] == ':' && fn[2] == '/'))
120 #else
121 # define absolutefn(fn) (fn[0] == '/')
122 #endif
126 * xnew -- allocate storage
128 * SYNOPSIS: Type *xnew (int n, Type);
130 #define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
132 typedef int logical;
134 typedef struct nd_st
135 { /* sorting structure */
136 char *name; /* function or type name */
137 char *file; /* file name */
138 logical is_func; /* use pattern or line no */
139 logical been_warned; /* set if noticed dup */
140 int lno; /* line number tag is on */
141 long cno; /* character number line starts on */
142 char *pat; /* search pattern */
143 struct nd_st *left, *right; /* left and right sons */
144 } NODE;
146 extern char *getenv ();
148 char *concat ();
149 char *savenstr (), *savestr ();
150 char *etags_strchr (), *etags_strrchr ();
151 char *etags_getcwd ();
152 char *relative_filename (), *absolute_filename (), *absolute_dirname ();
153 long *xmalloc (), *xrealloc ();
155 typedef void Lang_function ();
156 #if FALSE /* many compilers barf on this */
157 Lang_function Asm_labels;
158 Lang_function default_C_entries;
159 Lang_function C_entries;
160 Lang_function Cplusplus_entries;
161 Lang_function Cstar_entries;
162 Lang_function Erlang_functions;
163 Lang_function Fortran_functions;
164 Lang_function Yacc_entries;
165 Lang_function Lisp_functions;
166 Lang_function Pascal_functions;
167 Lang_function Perl_functions;
168 Lang_function Prolog_functions;
169 Lang_function Scheme_functions;
170 Lang_function TeX_functions;
171 Lang_function just_read_file;
172 #else /* so let's write it this way */
173 void Asm_labels ();
174 void C_entries ();
175 void default_C_entries ();
176 void plain_C_entries ();
177 void Cplusplus_entries ();
178 void Cstar_entries ();
179 void Erlang_functions ();
180 void Fortran_functions ();
181 void Yacc_entries ();
182 void Lisp_functions ();
183 void Pascal_functions ();
184 void Perl_functions ();
185 void Prolog_functions ();
186 void Scheme_functions ();
187 void TeX_functions ();
188 void just_read_file ();
189 #endif
191 Lang_function *get_language_from_name ();
192 Lang_function *get_language_from_interpreter ();
193 Lang_function *get_language_from_suffix ();
194 int total_size_of_entries ();
195 long readline ();
196 long readline_internal ();
197 #ifdef ETAGS_REGEXPS
198 void add_regex ();
199 #endif
200 void add_node ();
201 void error ();
202 void suggest_asking_for_help ();
203 void fatal (), pfatal ();
204 void find_entries ();
205 void free_tree ();
206 void getit ();
207 void init ();
208 void initbuffer ();
209 void pfnote ();
210 void process_file ();
211 void put_entries ();
212 void takeprec ();
215 char searchar = '/'; /* use /.../ searches */
217 int lineno; /* line number of current line */
218 long charno; /* current character number */
219 long linecharno; /* charno of start of line */
221 char *curfile; /* current input file name */
222 char *tagfile; /* output file */
223 char *progname; /* name this program was invoked with */
224 char *cwd; /* current working directory */
225 char *tagfiledir; /* directory of tagfile */
227 FILE *tagf; /* ioptr for tags file */
228 NODE *head; /* the head of the binary tree of tags */
231 * A `struct linebuffer' is a structure which holds a line of text.
232 * `readline' reads a line from a stream into a linebuffer and works
233 * regardless of the length of the line.
235 #define GROW_LINEBUFFER(buf,toksize) \
236 while (buf.size < toksize) \
237 buf.buffer = (char *) xrealloc (buf.buffer, buf.size *= 2)
238 struct linebuffer
240 long size;
241 char *buffer;
244 struct linebuffer lb; /* the current line */
245 struct linebuffer token_name; /* used by C_entries as a temporary area */
246 struct
248 long linepos;
249 struct linebuffer lb; /* used by C_entries instead of lb */
250 } lbs[2];
252 /* boolean "functions" (see init) */
253 logical _wht[0177], _etk[0177], _itk[0177], _btk[0177];
254 char
255 /* white chars */
256 *white = " \f\t\n\013",
257 /* token ending chars */
258 *endtk = " \t\n\013\"'#()[]{}=-+%*/&|^~!<>;,.:?",
259 /* token starting chars */
260 *begtk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$~@",
261 /* valid in-token chars */
262 *intk = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz$0123456789";
264 logical append_to_tagfile; /* -a: append to tags */
265 /* The following three default to TRUE for etags, but to FALSE for ctags. */
266 logical typedefs; /* -t: create tags for typedefs */
267 logical typedefs_and_cplusplus; /* -T: create tags for typedefs, level */
268 /* 0 struct/enum/union decls, and C++ */
269 /* member functions. */
270 logical constantypedefs; /* -d: create tags for C #define and enum */
271 /* constants. Enum consts not implemented. */
272 /* -D: opposite of -d. Default under ctags. */
273 logical update; /* -u: update tags */
274 logical vgrind_style; /* -v: create vgrind style index output */
275 logical no_warnings; /* -w: suppress warnings */
276 logical cxref_style; /* -x: create cxref style output */
277 logical cplusplus; /* .[hc] means C++, not C */
278 logical noindentypedefs; /* -I: ignore indentation in C */
280 struct option longopts[] =
282 { "append", no_argument, NULL, 'a' },
283 { "backward-search", no_argument, NULL, 'B' },
284 { "c++", no_argument, NULL, 'C' },
285 { "cxref", no_argument, NULL, 'x' },
286 { "defines", no_argument, NULL, 'd' },
287 { "help", no_argument, NULL, 'h' },
288 { "help", no_argument, NULL, 'H' },
289 { "ignore-indentation", no_argument, NULL, 'I' },
290 { "include", required_argument, NULL, 'i' },
291 { "language", required_argument, NULL, 'l' },
292 { "no-defines", no_argument, NULL, 'D' },
293 { "no-regex", no_argument, NULL, 'R' },
294 { "no-warn", no_argument, NULL, 'w' },
295 { "output", required_argument, NULL, 'o' },
296 { "regex", required_argument, NULL, 'r' },
297 { "typedefs", no_argument, NULL, 't' },
298 { "typedefs-and-c++", no_argument, NULL, 'T' },
299 { "update", no_argument, NULL, 'u' },
300 { "version", no_argument, NULL, 'V' },
301 { "vgrind", no_argument, NULL, 'v' },
302 { 0 }
305 #ifdef ETAGS_REGEXPS
306 /* Structure defining a regular expression. Elements are
307 the compiled pattern, and the name string. */
308 struct pattern
310 struct re_pattern_buffer *pattern;
311 struct re_registers regs;
312 char *name_pattern;
313 logical error_signaled;
316 /* Number of regexps found. */
317 int num_patterns = 0;
319 /* Array of all regexps. */
320 struct pattern *patterns = NULL;
321 #endif /* ETAGS_REGEXPS */
324 * Language stuff.
327 /* Non-NULL if language fixed. */
328 Lang_function *lang_func = NULL;
330 /* Assembly code */
331 char *Asm_suffixes [] = { "a", /* Unix assembler */
332 "asm", /* Microcontroller assembly */
333 "def", /* BSO/Tasking definition includes */
334 "inc", /* Microcontroller include files */
335 "ins", /* Microcontroller include files */
336 "s", "sa", /* Unix assembler */
337 "src", /* BSO/Tasking C compiler output */
338 NULL
341 /* Note that .c and .h can be considered C++, if the --c++ flag was
342 given. That is why default_C_entries is called here. */
343 char *default_C_suffixes [] =
344 { "c", "h", NULL };
346 /* .M is for Objective C++ files. */
347 char *Cplusplus_suffixes [] =
348 { "C", "H", "c++", "cc", "cpp", "cxx", "h++", "hh", "hpp", "hxx", "M", NULL};
350 char *Cstar_suffixes [] =
351 { "cs", "hs", NULL };
353 char *Erlang_suffixes [] =
354 { "erl", "hrl", NULL };
356 char *Fortran_suffixes [] =
357 { "F", "f", "f90", "for", NULL };
359 char *Lisp_suffixes [] =
360 { "cl", "clisp", "el", "l", "lisp", "lsp", "ml", NULL };
362 char *Pascal_suffixes [] =
363 { "p", "pas", NULL };
365 char *Perl_suffixes [] =
366 { "pl", "pm", NULL };
367 char *Perl_interpreters [] =
368 { "perl", "@PERL@", NULL };
370 char *plain_C_suffixes [] =
371 { "pc", /* Pro*C file */
372 "m", /* Objective C file */
373 "lm", /* Objective lex file */
374 NULL };
376 char *Prolog_suffixes [] =
377 { "prolog", NULL };
379 /* Can't do the `SCM' or `scm' prefix with a version number. */
380 char *Scheme_suffixes [] =
381 { "SCM", "SM", "oak", "sch", "scheme", "scm", "sm", "t", NULL };
383 char *TeX_suffixes [] =
384 { "TeX", "bib", "clo", "cls", "ltx", "sty", "tex", NULL };
386 char *Yacc_suffixes [] =
387 { "y", "ym", NULL }; /* .ym is Objective yacc file */
389 /* Table of language names and corresponding functions, file suffixes
390 and interpreter names.
391 It is ok for a given function to be listed under more than one
392 name. I just didn't. */
393 struct lang_entry
395 char *name;
396 Lang_function *function;
397 char **suffixes;
398 char **interpreters;
401 struct lang_entry lang_names [] =
403 { "asm", Asm_labels, Asm_suffixes, NULL },
404 { "c", default_C_entries, default_C_suffixes, NULL },
405 { "c++", Cplusplus_entries, Cplusplus_suffixes, NULL },
406 { "c*", Cstar_entries, Cstar_suffixes, NULL },
407 { "erlang", Erlang_functions, Erlang_suffixes, NULL },
408 { "fortran", Fortran_functions, Fortran_suffixes, NULL },
409 { "lisp", Lisp_functions, Lisp_suffixes, NULL },
410 { "pascal", Pascal_functions, Pascal_suffixes, NULL },
411 { "perl", Perl_functions, Perl_suffixes, Perl_interpreters },
412 { "proc", plain_C_entries, plain_C_suffixes, NULL },
413 { "prolog", Prolog_functions, Prolog_suffixes, NULL },
414 { "scheme", Scheme_functions, Scheme_suffixes, NULL },
415 { "tex", TeX_functions, TeX_suffixes, NULL },
416 { "yacc", Yacc_entries, Yacc_suffixes, NULL },
417 { "auto", NULL }, /* default guessing scheme */
418 { "none", just_read_file }, /* regexp matching only */
419 { NULL, NULL } /* end of list */
423 void
424 print_language_names ()
426 struct lang_entry *lang;
427 char **ext;
429 puts ("\nThese are the currently supported languages, along with the\n\
430 default file name suffixes:");
431 for (lang = lang_names; lang->name != NULL; lang++)
433 printf ("\t%s\t", lang->name);
434 if (lang->suffixes != NULL)
435 for (ext = lang->suffixes; *ext != NULL; ext++)
436 printf (" .%s", *ext);
437 puts ("");
439 puts ("Where `auto' means use default language for files based on file\n\
440 name suffix, and `none' means only do regexp processing on files.\n\
441 If no language is specified and no matching suffix is found,\n\
442 the first line of the file is read for a sharp-bang (#!) sequence\n\
443 followed by the name of an interpreter. If no such sequence is found,\n\
444 Fortran is tried first; if no tags are found, C is tried next.");
447 #ifndef VERSION
448 # define VERSION "19"
449 #endif
450 void
451 print_version ()
453 printf ("%s for Emacs version %s\n", (CTAGS) ? "ctags" : "etags", VERSION);
455 exit (GOOD);
458 void
459 print_help ()
461 printf ("These are the options accepted by %s. You may use unambiguous\n\
462 abbreviations for the long option names. A - as file name means read\n\
463 names from stdin.", progname);
464 if (!CTAGS)
465 printf (" Absolute names are stored in the output file as they\n\
466 are. Relative ones are stored relative to the output file's directory.");
467 puts ("\n");
469 puts ("-a, --append\n\
470 Append tag entries to existing tags file.");
472 if (CTAGS)
473 puts ("-B, --backward-search\n\
474 Write the search commands for the tag entries using '?', the\n\
475 backward-search command instead of '/', the forward-search command.");
477 puts ("-C, --c++\n\
478 Treat files whose name suffix defaults to C language as C++ files.");
480 if (CTAGS)
481 puts ("-d, --defines\n\
482 Create tag entries for constant C #defines, too.");
483 else
484 puts ("-D, --no-defines\n\
485 Don't create tag entries for constant C #defines. This makes\n\
486 the tags file smaller.");
488 if (!CTAGS)
490 puts ("-i FILE, --include=FILE\n\
491 Include a note in tag file indicating that, when searching for\n\
492 a tag, one should also consult the tags file FILE after\n\
493 checking the current file.");
494 puts ("-l LANG, --language=LANG\n\
495 Force the following files to be considered as written in the\n\
496 named language up to the next --language=LANG option.");
499 #ifdef ETAGS_REGEXPS
500 puts ("-r /REGEXP/, --regex=/REGEXP/\n\
501 Make a tag for each line matching pattern REGEXP in the\n\
502 following files. REGEXP is anchored (as if preceded by ^).\n\
503 The form /REGEXP/NAME/ creates a named tag. For example Tcl\n\
504 named tags can be created with:\n\
505 --regex=/proc[ \\t]+\\([^ \\t]+\\)/\\1/.");
506 puts ("-R, --no-regex\n\
507 Don't create tags from regexps for the following files.");
508 #endif /* ETAGS_REGEXPS */
509 puts ("-o FILE, --output=FILE\n\
510 Write the tags to FILE.");
511 puts ("-I, --ignore-indentation\n\
512 Don't rely on indentation quite as much as normal. Currently,\n\
513 this means not to assume that a closing brace in the first\n\
514 column is the final brace of a function or structure\n\
515 definition in C and C++.");
517 if (CTAGS)
519 puts ("-t, --typedefs\n\
520 Generate tag entries for C typedefs.");
521 puts ("-T, --typedefs-and-c++\n\
522 Generate tag entries for C typedefs, C struct/enum/union tags,\n\
523 and C++ member functions.");
524 puts ("-u, --update\n\
525 Update the tag entries for the given files, leaving tag\n\
526 entries for other files in place. Currently, this is\n\
527 implemented by deleting the existing entries for the given\n\
528 files and then rewriting the new entries at the end of the\n\
529 tags file. It is often faster to simply rebuild the entire\n\
530 tag file than to use this.");
531 puts ("-v, --vgrind\n\
532 Generates an index of items intended for human consumption,\n\
533 similar to the output of vgrind. The index is sorted, and\n\
534 gives the page number of each item.");
535 puts ("-w, --no-warn\n\
536 Suppress warning messages about entries defined in multiple\n\
537 files.");
538 puts ("-x, --cxref\n\
539 Like --vgrind, but in the style of cxref, rather than vgrind.\n\
540 The output uses line numbers instead of page numbers, but\n\
541 beyond that the differences are cosmetic; try both to see\n\
542 which you like.");
545 puts ("-V, --version\n\
546 Print the version of the program.\n\
547 -h, --help\n\
548 Print this help message.");
550 print_language_names ();
552 exit (GOOD);
556 enum argument_type
558 at_language,
559 at_regexp,
560 at_filename
563 /* This structure helps us allow mixing of --lang and filenames. */
564 typedef struct
566 enum argument_type arg_type;
567 char *what;
568 Lang_function *function;
569 } argument;
571 #ifdef VMS /* VMS specific functions */
573 #define EOS '\0'
575 /* This is a BUG! ANY arbitrary limit is a BUG!
576 Won't someone please fix this? */
577 #define MAX_FILE_SPEC_LEN 255
578 typedef struct {
579 short curlen;
580 char body[MAX_FILE_SPEC_LEN + 1];
581 } vspec;
584 v1.05 nmm 26-Jun-86 fn_exp - expand specification of list of file names
585 returning in each successive call the next filename matching the input
586 spec. The function expects that each in_spec passed
587 to it will be processed to completion; in particular, up to and
588 including the call following that in which the last matching name
589 is returned, the function ignores the value of in_spec, and will
590 only start processing a new spec with the following call.
591 If an error occurs, on return out_spec contains the value
592 of in_spec when the error occurred.
594 With each successive filename returned in out_spec, the
595 function's return value is one. When there are no more matching
596 names the function returns zero. If on the first call no file
597 matches in_spec, or there is any other error, -1 is returned.
600 #include <rmsdef.h>
601 #include <descrip.h>
602 #define OUTSIZE MAX_FILE_SPEC_LEN
603 short
604 fn_exp (out, in)
605 vspec *out;
606 char *in;
608 static long context = 0;
609 static struct dsc$descriptor_s o;
610 static struct dsc$descriptor_s i;
611 static logical pass1 = TRUE;
612 long status;
613 short retval;
615 if (pass1)
617 pass1 = FALSE;
618 o.dsc$a_pointer = (char *) out;
619 o.dsc$w_length = (short)OUTSIZE;
620 i.dsc$a_pointer = in;
621 i.dsc$w_length = (short)strlen(in);
622 i.dsc$b_dtype = DSC$K_DTYPE_T;
623 i.dsc$b_class = DSC$K_CLASS_S;
624 o.dsc$b_dtype = DSC$K_DTYPE_VT;
625 o.dsc$b_class = DSC$K_CLASS_VS;
627 if ((status = lib$find_file(&i, &o, &context, 0, 0)) == RMS$_NORMAL)
629 out->body[out->curlen] = EOS;
630 return 1;
632 else if (status == RMS$_NMF)
633 retval = 0;
634 else
636 strcpy(out->body, in);
637 retval = -1;
639 lib$find_file_end(&context);
640 pass1 = TRUE;
641 return retval;
645 v1.01 nmm 19-Aug-85 gfnames - return in successive calls the
646 name of each file specified by the provided arg expanding wildcards.
648 char *
649 gfnames (arg, p_error)
650 char *arg;
651 logical *p_error;
653 static vspec filename = {MAX_FILE_SPEC_LEN, "\0"};
655 switch (fn_exp (&filename, arg))
657 case 1:
658 *p_error = FALSE;
659 return filename.body;
660 case 0:
661 *p_error = FALSE;
662 return NULL;
663 default:
664 *p_error = TRUE;
665 return filename.body;
669 #ifndef OLD /* Newer versions of VMS do provide `system'. */
670 system (cmd)
671 char *cmd;
673 fprintf (stderr, "system() function not implemented under VMS\n");
675 #endif
677 #define VERSION_DELIM ';'
678 char *massage_name (s)
679 char *s;
681 char *start = s;
683 for ( ; *s; s++)
684 if (*s == VERSION_DELIM)
686 *s = EOS;
687 break;
689 else
690 *s = lowcase (*s);
691 return start;
693 #endif /* VMS */
696 void
697 main (argc, argv)
698 int argc;
699 char *argv[];
701 int i;
702 unsigned int nincluded_files = 0;
703 char **included_files = xnew (argc, char *);
704 char *this_file;
705 argument *argbuffer;
706 int current_arg = 0, file_count = 0;
707 struct linebuffer filename_lb;
708 #ifdef VMS
709 logical got_err;
710 #endif
712 #ifdef DOS_NT
713 _fmode = O_BINARY; /* all of files are treated as binary files */
714 #endif /* DOS_NT */
716 progname = argv[0];
718 /* Allocate enough no matter what happens. Overkill, but each one
719 is small. */
720 argbuffer = xnew (argc, argument);
722 #ifdef ETAGS_REGEXPS
723 /* Set syntax for regular expression routines. */
724 re_set_syntax (RE_SYNTAX_EMACS);
725 #endif /* ETAGS_REGEXPS */
728 * If etags, always find typedefs and structure tags. Why not?
729 * Also default is to find macro constants.
731 if (!CTAGS)
732 typedefs = typedefs_and_cplusplus = constantypedefs = TRUE;
734 while (1)
736 int opt = getopt_long (argc, argv,
737 "-aCdDf:Il:o:r:RStTi:BuvxwVhH", longopts, 0);
739 if (opt == EOF)
740 break;
742 switch (opt)
744 case 0:
745 /* If getopt returns 0, then it has already processed a
746 long-named option. We should do nothing. */
747 break;
749 case 1:
750 /* This means that a filename has been seen. Record it. */
751 argbuffer[current_arg].arg_type = at_filename;
752 argbuffer[current_arg].what = optarg;
753 ++current_arg;
754 ++file_count;
755 break;
757 /* Common options. */
758 case 'a':
759 append_to_tagfile = TRUE;
760 break;
761 case 'C':
762 cplusplus = TRUE;
763 break;
764 case 'd':
765 constantypedefs = TRUE;
766 break;
767 case 'D':
768 constantypedefs = FALSE;
769 break;
770 case 'f': /* for compatibility with old makefiles */
771 case 'o':
772 if (tagfile)
774 fprintf (stderr, "%s: -%c option may only be given once.\n",
775 progname, opt);
776 suggest_asking_for_help ();
778 tagfile = optarg;
779 break;
780 case 'I':
781 case 'S': /* for backward compatibility */
782 noindentypedefs = TRUE;
783 break;
784 case 'l':
785 argbuffer[current_arg].function = get_language_from_name (optarg);
786 argbuffer[current_arg].arg_type = at_language;
787 ++current_arg;
788 break;
789 #ifdef ETAGS_REGEXPS
790 case 'r':
791 argbuffer[current_arg].arg_type = at_regexp;
792 argbuffer[current_arg].what = optarg;
793 ++current_arg;
794 break;
795 case 'R':
796 argbuffer[current_arg].arg_type = at_regexp;
797 argbuffer[current_arg].what = NULL;
798 ++current_arg;
799 break;
800 #endif /* ETAGS_REGEXPS */
801 case 'V':
802 print_version ();
803 break;
804 case 'h':
805 case 'H':
806 print_help ();
807 break;
808 case 't':
809 typedefs = TRUE;
810 break;
811 case 'T':
812 typedefs = typedefs_and_cplusplus = TRUE;
813 break;
814 #if (!CTAGS)
815 /* Etags options */
816 case 'i':
817 included_files[nincluded_files++] = optarg;
818 break;
819 #else /* CTAGS */
820 /* Ctags options. */
821 case 'B':
822 searchar = '?';
823 break;
824 case 'u':
825 update = TRUE;
826 break;
827 case 'v':
828 vgrind_style = TRUE;
829 /*FALLTHRU*/
830 case 'x':
831 cxref_style = TRUE;
832 break;
833 case 'w':
834 no_warnings = TRUE;
835 break;
836 #endif /* CTAGS */
837 default:
838 suggest_asking_for_help ();
842 for (; optind < argc; ++optind)
844 argbuffer[current_arg].arg_type = at_filename;
845 argbuffer[current_arg].what = argv[optind];
846 ++current_arg;
847 ++file_count;
850 if (nincluded_files == 0 && file_count == 0)
852 fprintf (stderr, "%s: No input files specified.\n", progname);
853 suggest_asking_for_help ();
856 if (tagfile == NULL)
857 tagfile = CTAGS ? "tags" : "TAGS";
858 cwd = etags_getcwd (); /* the current working directory */
859 if (cwd[strlen (cwd) - 1] != '/')
860 cwd = concat (cwd, "/", "");
861 if (streq (tagfile, "-"))
862 tagfiledir = cwd;
863 else
864 tagfiledir = absolute_dirname (tagfile, cwd);
866 init (); /* set up boolean "functions" */
868 initbuffer (&lb);
869 initbuffer (&token_name);
870 initbuffer (&lbs[0].lb);
871 initbuffer (&lbs[1].lb);
872 initbuffer (&filename_lb);
874 if (!CTAGS)
876 if (streq (tagfile, "-"))
878 tagf = stdout;
879 #ifdef DOS_NT
880 /* Switch redirected `stdout' to binary mode (setting `_fmode'
881 doesn't take effect until after `stdout' is already open). */
882 if (!isatty (fileno (stdout)))
883 setmode (fileno (stdout), O_BINARY);
884 #endif /* DOS_NT */
886 else
887 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
888 if (tagf == NULL)
889 pfatal (tagfile);
893 * Loop through files finding functions.
895 for (i = 0; i < current_arg; ++i)
897 switch (argbuffer[i].arg_type)
899 case at_language:
900 lang_func = argbuffer[i].function;
901 break;
902 #ifdef ETAGS_REGEXPS
903 case at_regexp:
904 add_regex (argbuffer[i].what);
905 break;
906 #endif
907 case at_filename:
908 #ifdef VMS
909 while ((this_file = gfnames (argbuffer[i].what, &got_err)) != NULL)
911 if (got_err)
913 error ("Can't find file %s\n", this_file);
914 argc--, argv++;
916 else
918 this_file = massage_name (this_file);
920 #else
921 this_file = argbuffer[i].what;
922 #endif
923 /* Input file named "-" means read file names from stdin
924 and use them. */
925 if (streq (this_file, "-"))
926 while (readline_internal (&filename_lb, stdin) > 0)
927 process_file (filename_lb.buffer);
928 else
929 process_file (this_file);
930 #ifdef VMS
932 #endif
933 break;
937 if (!CTAGS)
939 while (nincluded_files-- > 0)
940 fprintf (tagf, "\f\n%s,include\n", *included_files++);
942 fclose (tagf);
943 exit (GOOD);
946 /* If CTAGS, we are here. process_file did not write the tags yet,
947 because we want them ordered. Let's do it now. */
948 if (cxref_style)
950 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
951 if (tagf == NULL)
952 pfatal (tagfile);
953 put_entries (head);
954 exit (GOOD);
957 if (update)
959 char cmd[BUFSIZ];
960 for (i = 0; i < current_arg; ++i)
962 if (argbuffer[i].arg_type != at_filename)
963 continue;
964 sprintf (cmd,
965 "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
966 tagfile, argbuffer[i].what, tagfile);
967 if (system (cmd) != GOOD)
968 fatal ("failed to execute shell command");
970 append_to_tagfile = TRUE;
973 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
974 if (tagf == NULL)
975 pfatal (tagfile);
976 put_entries (head);
977 fclose (tagf);
979 if (update)
981 char cmd[BUFSIZ];
982 sprintf (cmd, "sort %s -o %s", tagfile, tagfile);
983 exit (system (cmd));
985 exit (GOOD);
990 * Return a Lang_function given the name.
992 Lang_function *
993 get_language_from_name (name)
994 char *name;
996 struct lang_entry *lang;
998 if (name != NULL)
999 for (lang = lang_names; lang->name != NULL; lang++)
1001 if (streq (name, lang->name))
1002 return lang->function;
1005 fprintf (stderr, "%s: language \"%s\" not recognized.\n",
1006 progname, optarg);
1007 suggest_asking_for_help ();
1009 /* This point should never be reached. The function should either
1010 return a function pointer or never return. Note that a NULL
1011 pointer cannot be considered as an error, as it means that the
1012 language has not been explicitely imposed by the user ("auto"). */
1013 return NULL; /* avoid warnings from compiler */
1018 * Return a Lang_function given the interpreter name.
1020 Lang_function *
1021 get_language_from_interpreter (interpreter)
1022 char *interpreter;
1024 struct lang_entry *lang;
1025 char **iname;
1027 if (interpreter == NULL)
1028 return NULL;
1029 for (lang = lang_names; lang->name != NULL; lang++)
1030 if (lang->interpreters != NULL)
1031 for (iname = lang->interpreters; *iname != NULL; iname++)
1032 if (streq (*iname, interpreter))
1033 return lang->function;
1035 return NULL;
1041 * Return a Lang_function given the file suffix.
1043 Lang_function *
1044 get_language_from_suffix (suffix)
1045 char *suffix;
1047 struct lang_entry *lang;
1048 char **ext;
1050 if (suffix == NULL)
1051 return NULL;
1052 for (lang = lang_names; lang->name != NULL; lang++)
1053 if (lang->suffixes != NULL)
1054 for (ext = lang->suffixes; *ext != NULL; ext++)
1055 if (streq (*ext, suffix))
1056 return lang->function;
1058 return NULL;
1063 * This routine is called on each file argument.
1065 void
1066 process_file (file)
1067 char *file;
1069 struct stat stat_buf;
1070 FILE *inf;
1071 #ifdef DOS_NT
1072 char *p;
1074 for (p = file; *p != '\0'; p++)
1075 if (*p == '\\')
1076 *p = '/';
1077 #endif
1079 if (stat (file, &stat_buf) == 0 && !S_ISREG (stat_buf.st_mode))
1081 fprintf (stderr, "Skipping %s: it is not a regular file.\n", file);
1082 return;
1084 if (streq (file, tagfile) && !streq (tagfile, "-"))
1086 fprintf (stderr, "Skipping inclusion of %s in self.\n", file);
1087 return;
1089 inf = fopen (file, "r");
1090 if (inf == NULL)
1092 perror (file);
1093 return;
1096 find_entries (file, inf);
1098 if (!CTAGS)
1100 char *filename;
1102 if (absolutefn (file))
1104 /* file is an absolute filename. Canonicalise it. */
1105 filename = absolute_filename (file, cwd);
1107 else
1109 /* file is a filename relative to cwd. Make it relative
1110 to the directory of the tags file. */
1111 filename = relative_filename (file, tagfiledir);
1113 fprintf (tagf, "\f\n%s,%d\n", filename, total_size_of_entries (head));
1114 free (filename);
1115 put_entries (head);
1116 free_tree (head);
1117 head = NULL;
1122 * This routine sets up the boolean pseudo-functions which work
1123 * by setting boolean flags dependent upon the corresponding character
1124 * Every char which is NOT in that string is not a white char. Therefore,
1125 * all of the array "_wht" is set to FALSE, and then the elements
1126 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1127 * of a char is TRUE if it is the string "white", else FALSE.
1129 void
1130 init ()
1132 register char *sp;
1133 register int i;
1135 for (i = 0; i < 0177; i++)
1136 _wht[i] = _etk[i] = _itk[i] = _btk[i] = FALSE;
1137 for (sp = white; *sp; sp++)
1138 _wht[*sp] = TRUE;
1139 for (sp = endtk; *sp; sp++)
1140 _etk[*sp] = TRUE;
1141 for (sp = intk; *sp; sp++)
1142 _itk[*sp] = TRUE;
1143 for (sp = begtk; *sp; sp++)
1144 _btk[*sp] = TRUE;
1145 _wht[0] = _wht['\n'];
1146 _etk[0] = _etk['\n'];
1147 _btk[0] = _btk['\n'];
1148 _itk[0] = _itk['\n'];
1152 * This routine opens the specified file and calls the function
1153 * which finds the function and type definitions.
1155 void
1156 find_entries (file, inf)
1157 char *file;
1158 FILE *inf;
1160 char *cp;
1161 Lang_function *function;
1162 NODE *old_last_node;
1163 extern NODE *last_node;
1166 /* Memory leakage here: the memory block pointed by curfile is never
1167 released. The amount of memory leaked here is the sum of the
1168 lengths of the input file names. */
1169 curfile = savestr (file);
1171 /* If user specified a language, use it. */
1172 function = lang_func;
1173 if (function != NULL)
1175 function (inf);
1176 fclose (inf);
1177 return;
1180 cp = etags_strrchr (file, '.');
1181 if (cp != NULL)
1183 cp += 1;
1184 function = get_language_from_suffix (cp);
1185 if (function != NULL)
1187 function (inf);
1188 fclose (inf);
1189 return;
1193 /* Look for sharp-bang as the first two characters. */
1194 if (readline_internal (&lb, inf) > 2
1195 && lb.buffer[0] == '#'
1196 && lb.buffer[1] == '!')
1198 char *lp;
1200 /* Set lp to point at the first char after the last slash in the
1201 line or, if no slashes, at the first nonblank. Then set cp to
1202 the first successive blank and terminate the string. */
1203 lp = etags_strrchr (lb.buffer+2, '/');
1204 if (lp != NULL)
1205 lp += 1;
1206 else
1207 for (lp = lb.buffer+2; *lp != '\0' && isspace (*lp); lp++)
1208 continue;
1209 for (cp = lp; *cp != '\0' && !isspace (*cp); cp++)
1210 continue;
1211 *cp = '\0';
1213 if (strlen (lp) > 0)
1215 function = get_language_from_interpreter (lp);
1216 if (function != NULL)
1218 function (inf);
1219 fclose (inf);
1220 return;
1224 rewind (inf);
1226 /* Try Fortran. */
1227 old_last_node = last_node;
1228 Fortran_functions (inf);
1230 /* No Fortran entries found. Try C. */
1231 if (old_last_node == last_node)
1233 rewind (inf);
1234 default_C_entries (inf);
1236 fclose (inf);
1237 return;
1240 /* Record a tag. */
1241 void
1242 pfnote (name, is_func, linestart, linelen, lno, cno)
1243 char *name; /* tag name, or NULL if unnamed */
1244 logical is_func; /* tag is a function */
1245 char *linestart; /* start of the line where tag is */
1246 int linelen; /* length of the line where tag is */
1247 int lno; /* line number */
1248 long cno; /* character number */
1250 register NODE *np;
1252 if (CTAGS && name == NULL)
1253 return;
1255 np = xnew (1, NODE);
1257 /* If ctags mode, change name "main" to M<thisfilename>. */
1258 if (CTAGS && !cxref_style && streq (name, "main"))
1260 register char *fp = etags_strrchr (curfile, '/');
1261 np->name = concat ("M", fp == 0 ? curfile : fp + 1, "");
1262 fp = etags_strrchr (np->name, '.');
1263 if (fp && fp[1] != '\0' && fp[2] == '\0')
1264 fp[0] = 0;
1266 else
1267 np->name = name;
1268 np->been_warned = FALSE;
1269 np->file = curfile;
1270 np->is_func = is_func;
1271 np->lno = lno;
1272 /* Our char numbers are 0-base, because of C language tradition?
1273 ctags compatibility? old versions compatibility? I don't know.
1274 Anyway, since emacs's are 1-base we expect etags.el to take care
1275 of the difference. If we wanted to have 1-based numbers, we would
1276 uncomment the +1 below. */
1277 np->cno = cno /* + 1 */ ;
1278 np->left = np->right = NULL;
1279 if (CTAGS && !cxref_style)
1281 if (strlen (linestart) < 50)
1282 np->pat = concat (linestart, "$", "");
1283 else
1284 np->pat = savenstr (linestart, 50);
1286 else
1287 np->pat = savenstr (linestart, linelen);
1289 add_node (np, &head);
1293 * free_tree ()
1294 * recurse on left children, iterate on right children.
1296 void
1297 free_tree (node)
1298 register NODE *node;
1300 while (node)
1302 register NODE *node_right = node->right;
1303 free_tree (node->left);
1304 if (node->name != NULL)
1305 free (node->name);
1306 free (node->pat);
1307 free ((char *) node);
1308 node = node_right;
1313 * add_node ()
1314 * Adds a node to the tree of nodes. In etags mode, we don't keep
1315 * it sorted; we just keep a linear list. In ctags mode, maintain
1316 * an ordered tree, with no attempt at balancing.
1318 * add_node is the only function allowed to add nodes, so it can
1319 * maintain state.
1321 NODE *last_node = NULL;
1322 void
1323 add_node (node, cur_node_p)
1324 NODE *node, **cur_node_p;
1326 register int dif;
1327 register NODE *cur_node = *cur_node_p;
1329 if (cur_node == NULL)
1331 *cur_node_p = node;
1332 last_node = node;
1333 return;
1336 if (!CTAGS)
1338 /* Etags Mode */
1339 if (last_node == NULL)
1340 fatal ("internal error in add_node", 0);
1341 last_node->right = node;
1342 last_node = node;
1344 else
1346 /* Ctags Mode */
1347 dif = strcmp (node->name, cur_node->name);
1350 * If this tag name matches an existing one, then
1351 * do not add the node, but maybe print a warning.
1353 if (!dif)
1355 if (streq (node->file, cur_node->file))
1357 if (!no_warnings)
1359 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
1360 node->file, lineno, node->name);
1361 fprintf (stderr, "Second entry ignored\n");
1364 else if (!cur_node->been_warned && !no_warnings)
1366 fprintf
1367 (stderr,
1368 "Duplicate entry in files %s and %s: %s (Warning only)\n",
1369 node->file, cur_node->file, node->name);
1370 cur_node->been_warned = TRUE;
1372 return;
1375 /* Actually add the node */
1376 add_node (node, dif < 0 ? &cur_node->left : &cur_node->right);
1380 void
1381 put_entries (node)
1382 register NODE *node;
1384 register char *sp;
1386 if (node == NULL)
1387 return;
1389 /* Output subentries that precede this one */
1390 put_entries (node->left);
1392 /* Output this entry */
1394 if (!CTAGS)
1396 if (node->name != NULL)
1397 fprintf (tagf, "%s\177%s\001%d,%d\n",
1398 node->pat, node->name, node->lno, node->cno);
1399 else
1400 fprintf (tagf, "%s\177%d,%d\n",
1401 node->pat, node->lno, node->cno);
1403 else
1405 if (node->name == NULL)
1406 error ("internal error: NULL name in ctags mode.", 0);
1408 if (cxref_style)
1410 if (vgrind_style)
1411 fprintf (stdout, "%s %s %d\n",
1412 node->name, node->file, (node->lno + 63) / 64);
1413 else
1414 fprintf (stdout, "%-16s %3d %-16s %s\n",
1415 node->name, node->lno, node->file, node->pat);
1417 else
1419 fprintf (tagf, "%s\t%s\t", node->name, node->file);
1421 if (node->is_func)
1422 { /* a function */
1423 putc (searchar, tagf);
1424 putc ('^', tagf);
1426 for (sp = node->pat; *sp; sp++)
1428 if (*sp == '\\' || *sp == searchar)
1429 putc ('\\', tagf);
1430 putc (*sp, tagf);
1432 putc (searchar, tagf);
1434 else
1435 { /* a typedef; text pattern inadequate */
1436 fprintf (tagf, "%d", node->lno);
1438 putc ('\n', tagf);
1442 /* Output subentries that follow this one */
1443 put_entries (node->right);
1446 /* Length of a number's decimal representation. */
1448 number_len (num)
1449 long num;
1451 int len = 0;
1452 if (!num)
1453 return 1;
1454 for (; num; num /= 10)
1455 ++len;
1456 return len;
1460 * Return total number of characters that put_entries will output for
1461 * the nodes in the subtree of the specified node. Works only if
1462 * we are not ctags, but called only in that case. This count
1463 * is irrelevant with the new tags.el, but is still supplied for
1464 * backward compatibility.
1467 total_size_of_entries (node)
1468 register NODE *node;
1470 register int total;
1472 if (node == NULL)
1473 return 0;
1475 total = 0;
1476 for (; node; node = node->right)
1478 /* Count left subentries. */
1479 total += total_size_of_entries (node->left);
1481 /* Count this entry */
1482 total += strlen (node->pat) + 1;
1483 total += number_len ((long) node->lno) + 1 + number_len (node->cno) + 1;
1484 if (node->name != NULL)
1485 total += 1 + strlen (node->name); /* \001name */
1488 return total;
1492 * The C symbol tables.
1494 enum sym_type
1496 st_none, st_C_objprot, st_C_objimpl, st_C_objend, st_C_gnumacro,
1497 st_C_struct, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
1500 /* Feed stuff between (but not including) %[ and %] lines to:
1501 gperf -c -k1,3 -o -p -r -t
1503 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
1505 @interface, 0, st_C_objprot
1506 @protocol, 0, st_C_objprot
1507 @implementation,0, st_C_objimpl
1508 @end, 0, st_C_objend
1509 class, C_PLPL, st_C_struct
1510 domain, C_STAR, st_C_struct
1511 union, 0, st_C_struct
1512 struct, 0, st_C_struct
1513 enum, 0, st_C_enum
1514 typedef, 0, st_C_typedef
1515 define, 0, st_C_define
1516 long, 0, st_C_typespec
1517 short, 0, st_C_typespec
1518 int, 0, st_C_typespec
1519 char, 0, st_C_typespec
1520 float, 0, st_C_typespec
1521 double, 0, st_C_typespec
1522 signed, 0, st_C_typespec
1523 unsigned, 0, st_C_typespec
1524 auto, 0, st_C_typespec
1525 void, 0, st_C_typespec
1526 extern, 0, st_C_typespec
1527 static, 0, st_C_typespec
1528 const, 0, st_C_typespec
1529 volatile, 0, st_C_typespec
1530 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
1531 DEFUN, 0, st_C_gnumacro
1532 SYSCALL, 0, st_C_gnumacro
1533 ENTRY, 0, st_C_gnumacro
1534 PSEUDO, 0, st_C_gnumacro
1535 # These are defined inside C functions, so currently they are not met.
1536 # EXFUN used in glibc, DEFVAR_* in emacs.
1537 #EXFUN, 0, st_C_gnumacro
1538 #DEFVAR_, 0, st_C_gnumacro
1540 and replace lines between %< and %> with its output. */
1541 /*%<*/
1542 /* C code produced by gperf version 1.8.1 (K&R C version) */
1543 /* Command-line: gperf -c -k1,3 -o -p -r -t */
1546 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
1548 #define MIN_WORD_LENGTH 3
1549 #define MAX_WORD_LENGTH 15
1550 #define MIN_HASH_VALUE 7
1551 #define MAX_HASH_VALUE 63
1553 29 keywords
1554 57 is the maximum key range
1557 static int
1558 hash (str, len)
1559 register char *str;
1560 register int len;
1562 static unsigned char hash_table[] =
1564 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1565 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1566 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1567 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1568 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1569 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1570 63, 63, 63, 63, 17, 63, 63, 63, 4, 14,
1571 4, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1572 8, 63, 63, 0, 23, 63, 63, 63, 63, 63,
1573 63, 63, 63, 63, 63, 63, 63, 28, 63, 28,
1574 10, 31, 27, 18, 63, 6, 63, 63, 26, 1,
1575 11, 2, 29, 63, 29, 16, 26, 13, 15, 63,
1576 63, 63, 63, 63, 63, 63, 63, 63,
1578 return len + hash_table[str[2]] + hash_table[str[0]];
1581 struct C_stab_entry *
1582 in_word_set (str, len)
1583 register char *str;
1584 register int len;
1587 static struct C_stab_entry wordlist[] =
1589 {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",},
1590 {"SYSCALL", 0, st_C_gnumacro},
1591 {"",}, {"",}, {"",}, {"",}, {"",},
1592 {"DEFUN", 0, st_C_gnumacro},
1593 {"",}, {"",}, {"",},
1594 {"domain", C_STAR, st_C_struct},
1595 {"",}, {"",}, {"",}, {"",}, {"",},
1596 {"short", 0, st_C_typespec},
1597 {"union", 0, st_C_struct},
1598 {"void", 0, st_C_typespec},
1599 {"",}, {"",},
1600 {"PSEUDO", 0, st_C_gnumacro},
1601 {"double", 0, st_C_typespec},
1602 {"",}, {"",},
1603 {"@end", 0, st_C_objend},
1604 {"@implementation", 0, st_C_objimpl},
1605 {"float", 0, st_C_typespec},
1606 {"int", 0, st_C_typespec},
1607 {"",},
1608 {"unsigned", 0, st_C_typespec},
1609 {"@interface", 0, st_C_objprot},
1610 {"",},
1611 {"signed", 0, st_C_typespec},
1612 {"long", 0, st_C_typespec},
1613 {"ENTRY", 0, st_C_gnumacro},
1614 {"define", 0, st_C_define},
1615 {"const", 0, st_C_typespec},
1616 {"",}, {"",}, {"",},
1617 {"enum", 0, st_C_enum},
1618 {"volatile", 0, st_C_typespec},
1619 {"static", 0, st_C_typespec},
1620 {"struct", 0, st_C_struct},
1621 {"",}, {"",}, {"",},
1622 {"@protocol", 0, st_C_objprot},
1623 {"",}, {"",},
1624 {"auto", 0, st_C_typespec},
1625 {"",},
1626 {"char", 0, st_C_typespec},
1627 {"class", C_PLPL, st_C_struct},
1628 {"typedef", 0, st_C_typedef},
1629 {"extern", 0, st_C_typespec},
1632 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
1634 register int key = hash (str, len);
1636 if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)
1638 register char *s = wordlist[key].name;
1640 if (*s == *str && !strncmp (str + 1, s + 1, len - 1))
1641 return &wordlist[key];
1644 return 0;
1646 /*%>*/
1648 enum sym_type
1649 C_symtype(str, len, c_ext)
1650 char *str;
1651 int len;
1652 int c_ext;
1654 register struct C_stab_entry *se = in_word_set(str, len);
1656 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
1657 return st_none;
1658 return se->type;
1662 * C functions are recognized using a simple finite automaton.
1663 * funcdef is its state variable.
1665 enum
1667 fnone, /* nothing seen */
1668 ftagseen, /* function-like tag seen */
1669 fstartlist, /* just after open parenthesis */
1670 finlist, /* in parameter list */
1671 flistseen, /* after parameter list */
1672 fignore /* before open brace */
1673 } funcdef;
1677 * typedefs are recognized using a simple finite automaton.
1678 * typdef is its state variable.
1680 enum
1682 tnone, /* nothing seen */
1683 ttypedseen, /* typedef keyword seen */
1684 tinbody, /* inside typedef body */
1685 tend, /* just before typedef tag */
1686 tignore /* junk after typedef tag */
1687 } typdef;
1691 * struct-like structures (enum, struct and union) are recognized
1692 * using another simple finite automaton. `structdef' is its state
1693 * variable.
1695 enum
1697 snone, /* nothing seen yet */
1698 skeyseen, /* struct-like keyword seen */
1699 stagseen, /* struct-like tag seen */
1700 scolonseen, /* colon seen after struct-like tag */
1701 sinbody /* in struct body: recognize member func defs*/
1702 } structdef;
1705 * When structdef is stagseen, scolonseen, or sinbody, structtag is the
1706 * struct tag, and structtype is the type of the preceding struct-like
1707 * keyword.
1709 char *structtag = "<uninited>";
1710 enum sym_type structtype;
1713 * When objdef is different from onone, objtag is the name of the class.
1715 char *objtag = "<uninited>";
1718 * Yet another little state machine to deal with preprocessor lines.
1720 enum
1722 dnone, /* nothing seen */
1723 dsharpseen, /* '#' seen as first char on line */
1724 ddefineseen, /* '#' and 'define' seen */
1725 dignorerest /* ignore rest of line */
1726 } definedef;
1729 * State machine for Objective C protocols and implementations.
1731 enum
1733 onone, /* nothing seen */
1734 oprotocol, /* @interface or @protocol seen */
1735 oimplementation, /* @implementations seen */
1736 otagseen, /* class name seen */
1737 oparenseen, /* parenthesis before category seen */
1738 ocatseen, /* category name seen */
1739 oinbody, /* in @implementation body */
1740 omethodsign, /* in @implementation body, after +/- */
1741 omethodtag, /* after method name */
1742 omethodcolon, /* after method colon */
1743 omethodparm, /* after method parameter */
1744 oignore /* wait for @end */
1745 } objdef;
1748 * Set this to TRUE, and the next token considered is called a function.
1749 * Used only for GNU emacs's function-defining macros.
1751 logical next_token_is_func;
1754 * TRUE in the rules part of a yacc file, FALSE outside (parse as C).
1756 logical yacc_rules;
1759 * methodlen is the length of the method name stored in token_name.
1761 int methodlen;
1764 * consider_token ()
1765 * checks to see if the current token is at the start of a
1766 * function, or corresponds to a typedef, or is a struct/union/enum
1767 * tag.
1769 * *IS_FUNC gets TRUE iff the token is a function or macro with args.
1770 * C_EXT is which language we are looking at.
1772 * In the future we will need some way to adjust where the end of
1773 * the token is; for instance, implementing the C++ keyword
1774 * `operator' properly will adjust the end of the token to be after
1775 * whatever follows `operator'.
1777 * Globals
1778 * funcdef IN OUT
1779 * structdef IN OUT
1780 * definedef IN OUT
1781 * typdef IN OUT
1782 * objdef IN OUT
1783 * next_token_is_func IN OUT
1786 logical
1787 consider_token (str, len, c, c_ext, cblev, parlev, is_func)
1788 register char *str; /* IN: token pointer */
1789 register int len; /* IN: token length */
1790 register char c; /* IN: first char after the token */
1791 int c_ext; /* IN: C extensions mask */
1792 int cblev; /* IN: curly brace level */
1793 int parlev; /* IN: parenthesis level */
1794 logical *is_func; /* OUT: function found */
1796 enum sym_type toktype = C_symtype (str, len, c_ext);
1799 * Advance the definedef state machine.
1801 switch (definedef)
1803 case dnone:
1804 /* We're not on a preprocessor line. */
1805 break;
1806 case dsharpseen:
1807 if (toktype == st_C_define)
1809 definedef = ddefineseen;
1811 else
1813 definedef = dignorerest;
1815 return FALSE;
1816 case ddefineseen:
1818 * Make a tag for any macro, unless it is a constant
1819 * and constantypedefs is FALSE.
1821 definedef = dignorerest;
1822 *is_func = (c == '(');
1823 if (!*is_func && !constantypedefs)
1824 return FALSE;
1825 else
1826 return TRUE;
1827 case dignorerest:
1828 return FALSE;
1829 default:
1830 error ("internal error: definedef value.", 0);
1834 * Now typedefs
1836 switch (typdef)
1838 case tnone:
1839 if (toktype == st_C_typedef)
1841 if (typedefs)
1842 typdef = ttypedseen;
1843 funcdef = fnone;
1844 return FALSE;
1846 break;
1847 case ttypedseen:
1848 switch (toktype)
1850 case st_none:
1851 case st_C_typespec:
1852 typdef = tend;
1853 break;
1854 case st_C_struct:
1855 case st_C_enum:
1856 break;
1858 /* Do not return here, so the structdef stuff has a chance. */
1859 break;
1860 case tend:
1861 switch (toktype)
1863 case st_C_typespec:
1864 case st_C_struct:
1865 case st_C_enum:
1866 return FALSE;
1868 return TRUE;
1872 * This structdef business is currently only invoked when cblev==0.
1873 * It should be recursively invoked whatever the curly brace level,
1874 * and a stack of states kept, to allow for definitions of structs
1875 * within structs.
1877 * This structdef business is NOT invoked when we are ctags and the
1878 * file is plain C. This is because a struct tag may have the same
1879 * name as another tag, and this loses with ctags.
1881 * This if statement deals with the typdef state machine as
1882 * follows: if typdef==ttypedseen and token is struct/union/class/enum,
1883 * return FALSE. All the other code here is for the structdef
1884 * state machine.
1886 switch (toktype)
1888 case st_C_struct:
1889 case st_C_enum:
1890 if (typdef == ttypedseen
1891 || (typedefs_and_cplusplus && cblev == 0 && structdef == snone))
1893 structdef = skeyseen;
1894 structtype = toktype;
1896 return FALSE;
1898 if (structdef == skeyseen)
1900 /* Save the tag for struct/union/class, for functions that may be
1901 defined inside. */
1902 if (structtype == st_C_struct)
1903 structtag = savenstr (str, len);
1904 else
1905 structtag = "<enum>";
1906 structdef = stagseen;
1907 return TRUE;
1910 /* Avoid entering funcdef stuff if typdef is going on. */
1911 if (typdef != tnone)
1913 definedef = dnone;
1914 return FALSE;
1917 /* Detect GNU macros. */
1918 if (definedef == dnone && toktype == st_C_gnumacro)
1920 next_token_is_func = TRUE;
1921 return FALSE;
1923 if (next_token_is_func)
1925 next_token_is_func = FALSE;
1926 funcdef = fignore;
1927 *is_func = TRUE;
1928 return TRUE;
1932 * Detecting Objective C constructs.
1934 switch (objdef)
1936 case onone:
1937 switch (toktype)
1939 case st_C_objprot:
1940 objdef = oprotocol;
1941 return FALSE;
1942 case st_C_objimpl:
1943 objdef = oimplementation;
1944 return FALSE;
1946 break;
1947 case oimplementation:
1948 /* Save the class tag for functions that may be defined inside. */
1949 objtag = savenstr (str, len);
1950 objdef = oinbody;
1951 return FALSE;
1952 case oprotocol:
1953 /* Save the class tag for categories. */
1954 objtag = savenstr (str, len);
1955 objdef = otagseen;
1956 *is_func = TRUE;
1957 return TRUE;
1958 case oparenseen:
1959 objdef = ocatseen;
1960 *is_func = TRUE;
1961 return TRUE;
1962 case oinbody:
1963 break;
1964 case omethodsign:
1965 if (parlev == 0)
1967 objdef = omethodtag;
1968 methodlen = len;
1969 GROW_LINEBUFFER (token_name, methodlen+1);
1970 strncpy (token_name.buffer, str, len);
1971 token_name.buffer[methodlen] = '\0';
1972 return TRUE;
1974 return FALSE;
1975 case omethodcolon:
1976 if (parlev == 0)
1977 objdef = omethodparm;
1978 return FALSE;
1979 case omethodparm:
1980 if (parlev == 0)
1982 objdef = omethodtag;
1983 methodlen += len;
1984 GROW_LINEBUFFER (token_name, methodlen+1);
1985 strncat (token_name.buffer, str, len);
1986 return TRUE;
1988 return FALSE;
1989 case oignore:
1990 if (toktype == st_C_objend)
1992 /* Memory leakage here: the string pointed by objtag is
1993 never released, because many tests would be needed to
1994 avoid breaking on incorrect input code. The amount of
1995 memory leaked here is the sum of the lengths of the
1996 class tags.
1997 free (objtag); */
1998 objdef = onone;
2000 return FALSE;
2003 /* A function? */
2004 switch (toktype)
2006 case st_C_typespec:
2007 if (funcdef != finlist && funcdef != fignore)
2008 funcdef = fnone; /* should be useless */
2009 return FALSE;
2010 default:
2011 if (funcdef == fnone)
2013 funcdef = ftagseen;
2014 *is_func = TRUE;
2015 return TRUE;
2019 return FALSE;
2023 * C_entries ()
2024 * This routine finds functions, typedefs, #define's and
2025 * struct/union/enum definitions in C syntax and adds them
2026 * to the list.
2028 typedef struct
2030 logical valid;
2031 char *str;
2032 logical named;
2033 int linelen;
2034 int lineno;
2035 long linepos;
2036 char *buffer;
2037 } TOKEN;
2039 #define current_lb_is_new (newndx == curndx)
2040 #define switch_line_buffers() (curndx = 1 - curndx)
2042 #define curlb (lbs[curndx].lb)
2043 #define othlb (lbs[1-curndx].lb)
2044 #define newlb (lbs[newndx].lb)
2045 #define curlinepos (lbs[curndx].linepos)
2046 #define othlinepos (lbs[1-curndx].linepos)
2047 #define newlinepos (lbs[newndx].linepos)
2049 #define CNL_SAVE_DEFINEDEF \
2050 do { \
2051 curlinepos = charno; \
2052 lineno++; \
2053 linecharno = charno; \
2054 charno += readline (&curlb, inf); \
2055 lp = curlb.buffer; \
2056 quotednl = FALSE; \
2057 newndx = curndx; \
2058 } while (0)
2060 #define CNL \
2061 do { \
2062 CNL_SAVE_DEFINEDEF; \
2063 if (savetok.valid) \
2065 tok = savetok; \
2066 savetok.valid = FALSE; \
2068 definedef = dnone; \
2069 } while (0)
2071 /* Ideally this macro should never be called wihen tok.valid is FALSE,
2072 but this would mean that the state machines always guess right. */
2073 #define make_tag(isfun) do \
2074 if (tok.valid) { \
2075 char *name = NULL; \
2076 if (CTAGS || tok.named) \
2077 name = savestr (token_name.buffer); \
2078 pfnote (name, isfun, tok.buffer, tok.linelen, tok.lineno, tok.linepos); \
2079 tok.valid = FALSE; \
2080 } while (0)
2082 void
2083 C_entries (c_ext, inf)
2084 int c_ext; /* extension of C */
2085 FILE *inf; /* input file */
2087 register char c; /* latest char read; '\0' for end of line */
2088 register char *lp; /* pointer one beyond the character `c' */
2089 int curndx, newndx; /* indices for current and new lb */
2090 TOKEN tok; /* latest token read */
2091 register int tokoff; /* offset in line of start of current token */
2092 register int toklen; /* length of current token */
2093 int cblev; /* current curly brace level */
2094 int parlev; /* current parenthesis level */
2095 logical incomm, inquote, inchar, quotednl, midtoken;
2096 logical cplpl;
2097 TOKEN savetok; /* token saved during preprocessor handling */
2100 curndx = newndx = 0;
2101 lineno = 0;
2102 charno = 0;
2103 lp = curlb.buffer;
2104 *lp = 0;
2106 funcdef = fnone; typdef = tnone; structdef = snone;
2107 definedef = dnone; objdef = onone;
2108 next_token_is_func = yacc_rules = FALSE;
2109 midtoken = inquote = inchar = incomm = quotednl = FALSE;
2110 tok.valid = savetok.valid = FALSE;
2111 cblev = 0;
2112 parlev = 0;
2113 cplpl = c_ext & C_PLPL;
2115 while (!feof (inf))
2117 c = *lp++;
2118 if (c == '\\')
2120 /* If we're at the end of the line, the next character is a
2121 '\0'; don't skip it, because it's the thing that tells us
2122 to read the next line. */
2123 if (*lp == '\0')
2125 quotednl = TRUE;
2126 continue;
2128 lp++;
2129 c = ' ';
2131 else if (incomm)
2133 switch (c)
2135 case '*':
2136 if (*lp == '/')
2138 c = *lp++;
2139 incomm = FALSE;
2141 break;
2142 case '\0':
2143 /* Newlines inside comments do not end macro definitions in
2144 traditional cpp. */
2145 CNL_SAVE_DEFINEDEF;
2146 break;
2148 continue;
2150 else if (inquote)
2152 switch (c)
2154 case '"':
2155 inquote = FALSE;
2156 break;
2157 case '\0':
2158 /* Newlines inside strings do not end macro definitions
2159 in traditional cpp, even though compilers don't
2160 usually accept them. */
2161 CNL_SAVE_DEFINEDEF;
2162 break;
2164 continue;
2166 else if (inchar)
2168 switch (c)
2170 case '\0':
2171 /* Hmmm, something went wrong. */
2172 CNL;
2173 /* FALLTHRU */
2174 case '\'':
2175 inchar = FALSE;
2176 break;
2178 continue;
2180 else
2181 switch (c)
2183 case '"':
2184 inquote = TRUE;
2185 if (funcdef != finlist && funcdef != fignore)
2186 funcdef = fnone;
2187 continue;
2188 case '\'':
2189 inchar = TRUE;
2190 if (funcdef != finlist && funcdef != fignore)
2191 funcdef = fnone;
2192 continue;
2193 case '/':
2194 if (*lp == '*')
2196 lp++;
2197 incomm = TRUE;
2198 continue;
2200 else if (/* cplpl && */ *lp == '/')
2202 c = '\0';
2203 break;
2205 else
2206 break;
2207 case '%':
2208 if ((c_ext & YACC) && *lp == '%')
2210 /* entering or exiting rules section in yacc file */
2211 lp++;
2212 definedef = dnone; funcdef = fnone;
2213 typdef = tnone; structdef = snone;
2214 next_token_is_func = FALSE;
2215 midtoken = inquote = inchar = incomm = quotednl = FALSE;
2216 cblev = 0;
2217 yacc_rules = !yacc_rules;
2218 continue;
2220 else
2221 break;
2222 case '#':
2223 if (definedef == dnone)
2225 char *cp;
2226 logical cpptoken = TRUE;
2228 /* Look back on this line. If all blanks, or nonblanks
2229 followed by an end of comment, this is a preprocessor
2230 token. */
2231 for (cp = newlb.buffer; cp < lp-1; cp++)
2232 if (!iswhite (*cp))
2234 if (*cp == '*' && *(cp+1) == '/')
2236 cp++;
2237 cpptoken = TRUE;
2239 else
2240 cpptoken = FALSE;
2242 if (cpptoken)
2243 definedef = dsharpseen;
2244 } /* if (definedef == dnone) */
2246 continue;
2247 } /* switch (c) */
2250 /* Consider token only if some complicated conditions are satisfied. */
2251 if ((definedef != dnone
2252 || (cblev == 0 && structdef != scolonseen)
2253 || (cblev == 1 && cplpl && structdef == sinbody))
2254 && typdef != tignore
2255 && definedef != dignorerest
2256 && funcdef != finlist)
2258 if (midtoken)
2260 if (endtoken (c))
2262 if (c == ':' && cplpl && *lp == ':' && begtoken(*(lp + 1)))
2265 * This handles :: in the middle, but not at the
2266 * beginning of an identifier.
2268 lp += 2;
2269 toklen += 3;
2271 else
2273 logical is_func = FALSE;
2275 if (yacc_rules
2276 || consider_token (newlb.buffer + tokoff, toklen, c,
2277 c_ext, cblev, parlev, &is_func))
2279 if (structdef == sinbody
2280 && definedef == dnone
2281 && is_func)
2282 /* function defined in C++ class body */
2284 GROW_LINEBUFFER (token_name,
2285 strlen(structtag)+2+toklen+1);
2286 strcpy (token_name.buffer, structtag);
2287 strcat (token_name.buffer, "::");
2288 strncat (token_name.buffer,
2289 newlb.buffer+tokoff, toklen);
2290 tok.named = TRUE;
2292 else if (objdef == ocatseen)
2293 /* Objective C category */
2295 GROW_LINEBUFFER (token_name,
2296 strlen(objtag)+2+toklen+1);
2297 strcpy (token_name.buffer, objtag);
2298 strcat (token_name.buffer, "(");
2299 strncat (token_name.buffer,
2300 newlb.buffer+tokoff, toklen);
2301 strcat (token_name.buffer, ")");
2302 tok.named = TRUE;
2304 else if (objdef == omethodtag
2305 || objdef == omethodparm)
2306 /* Objective C method */
2308 tok.named = TRUE;
2310 else
2312 GROW_LINEBUFFER (token_name, toklen+1);
2313 strncpy (token_name.buffer,
2314 newlb.buffer+tokoff, toklen);
2315 token_name.buffer[toklen] = '\0';
2316 if (structdef == stagseen
2317 || typdef == tend
2318 || (is_func
2319 && definedef == dignorerest)) /* macro */
2320 tok.named = TRUE;
2321 else
2322 tok.named = FALSE;
2324 tok.lineno = lineno;
2325 tok.linelen = tokoff + toklen + 1;
2326 tok.buffer = newlb.buffer;
2327 tok.linepos = newlinepos;
2328 tok.valid = TRUE;
2330 if (definedef == dnone
2331 && (funcdef == ftagseen
2332 || structdef == stagseen
2333 || typdef == tend
2334 || objdef != onone))
2336 if (current_lb_is_new)
2337 switch_line_buffers ();
2339 else
2340 make_tag (is_func);
2342 midtoken = FALSE;
2344 } /* if (endtoken (c)) */
2345 else if (intoken (c))
2347 toklen++;
2348 continue;
2350 } /* if (midtoken) */
2351 else if (begtoken (c))
2353 switch (definedef)
2355 case dnone:
2356 switch (funcdef)
2358 case fstartlist:
2359 funcdef = finlist;
2360 continue;
2361 case flistseen:
2362 make_tag (TRUE);
2363 funcdef = fignore;
2364 break;
2365 case ftagseen:
2366 funcdef = fnone;
2367 break;
2369 if (structdef == stagseen)
2370 structdef = snone;
2371 break;
2372 case dsharpseen:
2373 savetok = tok;
2375 if (!yacc_rules || lp == newlb.buffer + 1)
2377 tokoff = lp - 1 - newlb.buffer;
2378 toklen = 1;
2379 midtoken = TRUE;
2381 continue;
2382 } /* if (begtoken) */
2383 } /* if must look at token */
2386 /* Detect end of line, colon, comma, semicolon and various braces
2387 after having handled a token.*/
2388 switch (c)
2390 case ':':
2391 if (definedef != dnone)
2392 break;
2393 switch (objdef)
2395 case otagseen:
2396 objdef = oignore;
2397 make_tag (TRUE);
2398 break;
2399 case omethodtag:
2400 case omethodparm:
2401 objdef = omethodcolon;
2402 methodlen += 1;
2403 GROW_LINEBUFFER (token_name, methodlen+1);
2404 strcat (token_name.buffer, ":");
2405 break;
2407 if (structdef == stagseen)
2408 structdef = scolonseen;
2409 else
2410 switch (funcdef)
2412 case ftagseen:
2413 if (yacc_rules)
2415 make_tag (FALSE);
2416 funcdef = fignore;
2418 break;
2419 case fstartlist:
2420 funcdef = fnone;
2421 break;
2423 break;
2424 case ';':
2425 if (definedef != dnone)
2426 break;
2427 if (cblev == 0)
2428 switch (typdef)
2430 case tend:
2431 make_tag (FALSE);
2432 /* FALLTHRU */
2433 default:
2434 typdef = tnone;
2436 if (funcdef != fignore)
2438 funcdef = fnone;
2439 /* The following instruction invalidates the token.
2440 Probably the token should be invalidated in all
2441 other cases where some state machine is reset. */
2442 tok.valid = FALSE;
2444 if (structdef == stagseen)
2445 structdef = snone;
2446 break;
2447 case ',':
2448 if (definedef != dnone)
2449 break;
2450 switch (objdef)
2452 case omethodtag:
2453 case omethodparm:
2454 make_tag (TRUE);
2455 objdef = oinbody;
2456 break;
2458 if (funcdef != finlist && funcdef != fignore)
2459 funcdef = fnone;
2460 if (structdef == stagseen)
2461 structdef = snone;
2462 break;
2463 case '[':
2464 if (definedef != dnone)
2465 break;
2466 if (cblev == 0 && typdef == tend)
2468 typdef = tignore;
2469 make_tag (FALSE);
2470 break;
2472 if (funcdef != finlist && funcdef != fignore)
2473 funcdef = fnone;
2474 if (structdef == stagseen)
2475 structdef = snone;
2476 break;
2477 case '(':
2478 if (definedef != dnone)
2479 break;
2480 if (objdef == otagseen && parlev == 0)
2481 objdef = oparenseen;
2482 switch (funcdef)
2484 case fnone:
2485 switch (typdef)
2487 case ttypedseen:
2488 case tend:
2489 /* Make sure that the next char is not a '*'.
2490 This handles constructs like:
2491 typedef void OperatorFun (int fun); */
2492 if (*lp != '*')
2494 typdef = tignore;
2495 make_tag (FALSE);
2497 break;
2498 } /* switch (typdef) */
2499 break;
2500 case ftagseen:
2501 funcdef = fstartlist;
2502 break;
2503 case flistseen:
2504 funcdef = finlist;
2505 break;
2507 parlev++;
2508 break;
2509 case ')':
2510 if (definedef != dnone)
2511 break;
2512 if (objdef == ocatseen && parlev == 1)
2514 make_tag (TRUE);
2515 objdef = oignore;
2517 if (--parlev == 0)
2519 switch (funcdef)
2521 case fstartlist:
2522 case finlist:
2523 funcdef = flistseen;
2524 break;
2526 if (cblev == 0 && typdef == tend)
2528 typdef = tignore;
2529 make_tag (FALSE);
2532 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
2533 parlev = 0;
2534 break;
2535 case '{':
2536 if (definedef != dnone)
2537 break;
2538 if (typdef == ttypedseen)
2539 typdef = tinbody;
2540 switch (structdef)
2542 case skeyseen: /* unnamed struct */
2543 structtag = "_anonymous_";
2544 structdef = sinbody;
2545 break;
2546 case stagseen:
2547 case scolonseen: /* named struct */
2548 structdef = sinbody;
2549 make_tag (FALSE);
2550 break;
2552 switch (funcdef)
2554 case flistseen:
2555 make_tag (TRUE);
2556 /* FALLTHRU */
2557 case fignore:
2558 funcdef = fnone;
2559 break;
2560 case fnone:
2561 switch (objdef)
2563 case otagseen:
2564 make_tag (TRUE);
2565 objdef = oignore;
2566 break;
2567 case omethodtag:
2568 case omethodparm:
2569 make_tag (TRUE);
2570 objdef = oinbody;
2571 break;
2572 default:
2573 /* Neutralize `extern "C" {' grot and look inside structs. */
2574 if (cblev == 0 && structdef == snone && typdef == tnone)
2575 cblev = -1;
2578 cblev++;
2579 break;
2580 case '*':
2581 if (definedef != dnone)
2582 break;
2583 if (funcdef == fstartlist)
2584 funcdef = fnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
2585 break;
2586 case '}':
2587 if (definedef != dnone)
2588 break;
2589 if (!noindentypedefs && lp == newlb.buffer + 1)
2591 cblev = 0; /* reset curly brace level if first column */
2592 parlev = 0; /* also reset paren level, just in case... */
2594 else if (cblev > 0)
2595 cblev--;
2596 if (cblev == 0)
2598 if (typdef == tinbody)
2599 typdef = tend;
2600 /* Memory leakage here: the string pointed by structtag is
2601 never released, because I fear to miss something and
2602 break things while freeing the area. The amount of
2603 memory leaked here is the sum of the lengths of the
2604 struct tags.
2605 if (structdef == sinbody)
2606 free (structtag); */
2608 structdef = snone;
2609 structtag = "<error>";
2611 break;
2612 case '+':
2613 case '-':
2614 if (objdef == oinbody && cblev == 0)
2616 objdef = omethodsign;
2617 break;
2619 /* FALLTHRU */
2620 case '=': case '#': case '~': case '&': case '%': case '/':
2621 case '|': case '^': case '!': case '<': case '>': case '.': case '?':
2622 if (definedef != dnone)
2623 break;
2624 /* These surely cannot follow a function tag. */
2625 if (funcdef != finlist && funcdef != fignore)
2626 funcdef = fnone;
2627 break;
2628 case '\0':
2629 if (objdef == otagseen)
2631 make_tag (TRUE);
2632 objdef = oignore;
2634 /* If a macro spans multiple lines don't reset its state. */
2635 if (quotednl)
2636 CNL_SAVE_DEFINEDEF;
2637 else
2638 CNL;
2639 break;
2640 } /* switch (c) */
2642 } /* while not eof */
2646 * Process either a C++ file or a C file depending on the setting
2647 * of a global flag.
2649 void
2650 default_C_entries (inf)
2651 FILE *inf;
2653 C_entries (cplusplus ? C_PLPL : 0, inf);
2656 /* Always do plain ANSI C. */
2657 void
2658 plain_C_entries (inf)
2659 FILE *inf;
2661 C_entries (0, inf);
2664 /* Always do C++. */
2665 void
2666 Cplusplus_entries (inf)
2667 FILE *inf;
2669 C_entries (C_PLPL, inf);
2672 /* Always do C*. */
2673 void
2674 Cstar_entries (inf)
2675 FILE *inf;
2677 C_entries (C_STAR, inf);
2680 /* Always do Yacc. */
2681 void
2682 Yacc_entries (inf)
2683 FILE *inf;
2685 C_entries (YACC, inf);
2688 /* Fortran parsing */
2690 char *dbp;
2692 logical
2693 tail (cp)
2694 char *cp;
2696 register int len = 0;
2698 while (*cp && lowcase(*cp) == lowcase(dbp[len]))
2699 cp++, len++;
2700 if (*cp == '\0' && !intoken(dbp[len]))
2702 dbp += len;
2703 return TRUE;
2705 return FALSE;
2708 void
2709 takeprec ()
2711 while (isspace (*dbp))
2712 dbp++;
2713 if (*dbp != '*')
2714 return;
2715 dbp++;
2716 while (isspace (*dbp))
2717 dbp++;
2718 if (strneq (dbp, "(*)", 3))
2720 dbp += 3;
2721 return;
2723 if (!isdigit (*dbp))
2725 --dbp; /* force failure */
2726 return;
2729 dbp++;
2730 while (isdigit (*dbp));
2733 void
2734 getit (inf)
2735 FILE *inf;
2737 register char *cp;
2739 while (isspace (*dbp))
2740 dbp++;
2741 if (*dbp == '\0')
2743 lineno++;
2744 linecharno = charno;
2745 charno += readline (&lb, inf);
2746 dbp = lb.buffer;
2747 if (dbp[5] != '&')
2748 return;
2749 dbp += 6;
2750 while (isspace (*dbp))
2751 dbp++;
2753 if (!isalpha (*dbp)
2754 && *dbp != '_'
2755 && *dbp != '$')
2756 return;
2757 for (cp = dbp + 1;
2758 (*cp
2759 && (isalpha (*cp) || isdigit (*cp) || (*cp == '_') || (*cp == '$')));
2760 cp++)
2761 continue;
2762 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
2763 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2766 void
2767 Fortran_functions (inf)
2768 FILE *inf;
2770 lineno = 0;
2771 charno = 0;
2773 while (!feof (inf))
2775 lineno++;
2776 linecharno = charno;
2777 charno += readline (&lb, inf);
2778 dbp = lb.buffer;
2779 if (*dbp == '%')
2780 dbp++; /* Ratfor escape to fortran */
2781 while (isspace (*dbp))
2782 dbp++;
2783 if (*dbp == '\0')
2784 continue;
2785 switch (lowcase (*dbp))
2787 case 'i':
2788 if (tail ("integer"))
2789 takeprec ();
2790 break;
2791 case 'r':
2792 if (tail ("real"))
2793 takeprec ();
2794 break;
2795 case 'l':
2796 if (tail ("logical"))
2797 takeprec ();
2798 break;
2799 case 'c':
2800 if (tail ("complex") || tail ("character"))
2801 takeprec ();
2802 break;
2803 case 'd':
2804 if (tail ("double"))
2806 while (isspace (*dbp))
2807 dbp++;
2808 if (*dbp == '\0')
2809 continue;
2810 if (tail ("precision"))
2811 break;
2812 continue;
2814 break;
2816 while (isspace (*dbp))
2817 dbp++;
2818 if (*dbp == '\0')
2819 continue;
2820 switch (lowcase (*dbp))
2822 case 'f':
2823 if (tail ("function"))
2824 getit (inf);
2825 continue;
2826 case 's':
2827 if (tail ("subroutine"))
2828 getit (inf);
2829 continue;
2830 case 'e':
2831 if (tail ("entry"))
2832 getit (inf);
2833 continue;
2834 case 'p':
2835 if (tail ("program"))
2837 getit (inf);
2838 continue;
2840 if (tail ("procedure"))
2841 getit (inf);
2842 continue;
2848 * Bob Weiner, Motorola Inc., 4/3/94
2849 * Unix and microcontroller assembly tag handling
2850 * look for '^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]'
2852 void
2853 Asm_labels (inf)
2854 FILE *inf;
2856 register char *cp;
2858 lineno = 0;
2859 charno = 0;
2861 while (!feof (inf))
2863 lineno++;
2864 linecharno = charno;
2865 charno += readline (&lb, inf);
2866 cp = lb.buffer;
2868 /* If first char is alphabetic or one of [_.$], test for colon
2869 following identifier. */
2870 if (isalpha (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
2872 /* Read past label. */
2873 cp++;
2874 while (isalnum (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
2875 cp++;
2876 if (*cp == ':' || isspace (*cp))
2878 /* Found end of label, so copy it and add it to the table. */
2879 pfnote ((CTAGS) ? savenstr(lb.buffer, cp-lb.buffer) : NULL, TRUE,
2880 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2887 * Perl support by Bart Robinson <lomew@cs.utah.edu>
2888 * Perl sub names: look for /^sub[ \t\n]+[^ \t\n{]+/
2890 void
2891 Perl_functions (inf)
2892 FILE *inf;
2894 register char *cp;
2896 lineno = 0;
2897 charno = 0;
2899 while (!feof (inf))
2901 lineno++;
2902 linecharno = charno;
2903 charno += readline (&lb, inf);
2904 cp = lb.buffer;
2906 if (*cp++ == 's' && *cp++ == 'u' && *cp++ == 'b' && isspace(*cp++))
2908 while (*cp && isspace(*cp))
2909 cp++;
2910 while (*cp && ! isspace(*cp) && *cp != '{')
2911 cp++;
2912 pfnote ((CTAGS) ? savenstr (lb.buffer, cp-lb.buffer) : NULL, TRUE,
2913 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2918 /* Added by Mosur Mohan, 4/22/88 */
2919 /* Pascal parsing */
2922 * Locates tags for procedures & functions. Doesn't do any type- or
2923 * var-definitions. It does look for the keyword "extern" or
2924 * "forward" immediately following the procedure statement; if found,
2925 * the tag is skipped.
2927 void
2928 Pascal_functions (inf)
2929 FILE *inf;
2931 struct linebuffer tline; /* mostly copied from C_entries */
2932 long save_lcno;
2933 int save_lineno, save_len;
2934 char c, *cp, *namebuf;
2936 logical /* each of these flags is TRUE iff: */
2937 incomment, /* point is inside a comment */
2938 inquote, /* point is inside '..' string */
2939 get_tagname, /* point is after PROCEDURE/FUNCTION
2940 keyword, so next item = potential tag */
2941 found_tag, /* point is after a potential tag */
2942 inparms, /* point is within parameter-list */
2943 verify_tag; /* point has passed the parm-list, so the
2944 next token will determine whether this
2945 is a FORWARD/EXTERN to be ignored, or
2946 whether it is a real tag */
2948 lineno = 0;
2949 charno = 0;
2950 dbp = lb.buffer;
2951 *dbp = '\0';
2952 save_len = 0;
2953 initbuffer (&tline);
2955 incomment = inquote = FALSE;
2956 found_tag = FALSE; /* have a proc name; check if extern */
2957 get_tagname = FALSE; /* have found "procedure" keyword */
2958 inparms = FALSE; /* found '(' after "proc" */
2959 verify_tag = FALSE; /* check if "extern" is ahead */
2961 /* long main loop to get next char */
2962 while (!feof (inf))
2964 c = *dbp++;
2965 if (c == '\0') /* if end of line */
2967 lineno++;
2968 linecharno = charno;
2969 charno += readline (&lb, inf);
2970 dbp = lb.buffer;
2971 if (*dbp == '\0')
2972 continue;
2973 if (!((found_tag && verify_tag) ||
2974 get_tagname))
2975 c = *dbp++; /* only if don't need *dbp pointing
2976 to the beginning of the name of
2977 the procedure or function */
2979 if (incomment)
2981 if (c == '}') /* within { } comments */
2982 incomment = FALSE;
2983 else if (c == '*' && *dbp == ')') /* within (* *) comments */
2985 dbp++;
2986 incomment = FALSE;
2988 continue;
2990 else if (inquote)
2992 if (c == '\'')
2993 inquote = FALSE;
2994 continue;
2996 else
2997 switch (c)
2999 case '\'':
3000 inquote = TRUE; /* found first quote */
3001 continue;
3002 case '{': /* found open { comment */
3003 incomment = TRUE;
3004 continue;
3005 case '(':
3006 if (*dbp == '*') /* found open (* comment */
3008 incomment = TRUE;
3009 dbp++;
3011 else if (found_tag) /* found '(' after tag, i.e., parm-list */
3012 inparms = TRUE;
3013 continue;
3014 case ')': /* end of parms list */
3015 if (inparms)
3016 inparms = FALSE;
3017 continue;
3018 case ';':
3019 if (found_tag && !inparms) /* end of proc or fn stmt */
3021 verify_tag = TRUE;
3022 break;
3024 continue;
3026 if (found_tag && verify_tag && (*dbp != ' '))
3028 /* check if this is an "extern" declaration */
3029 if (*dbp == '\0')
3030 continue;
3031 if (lowcase (*dbp == 'e'))
3033 if (tail ("extern")) /* superfluous, really! */
3035 found_tag = FALSE;
3036 verify_tag = FALSE;
3039 else if (lowcase (*dbp) == 'f')
3041 if (tail ("forward")) /* check for forward reference */
3043 found_tag = FALSE;
3044 verify_tag = FALSE;
3047 if (found_tag && verify_tag) /* not external proc, so make tag */
3049 found_tag = FALSE;
3050 verify_tag = FALSE;
3051 pfnote (namebuf, TRUE,
3052 tline.buffer, save_len, save_lineno, save_lcno);
3053 continue;
3056 if (get_tagname) /* grab name of proc or fn */
3058 if (*dbp == '\0')
3059 continue;
3061 /* save all values for later tagging */
3062 GROW_LINEBUFFER (tline, strlen (lb.buffer) + 1);
3063 strcpy (tline.buffer, lb.buffer);
3064 save_lineno = lineno;
3065 save_lcno = linecharno;
3067 /* grab block name */
3068 for (cp = dbp + 1; *cp && (!endtoken (*cp)); cp++)
3069 continue;
3070 namebuf = (CTAGS) ? savenstr (dbp, cp-dbp) : NULL;
3071 dbp = cp; /* set dbp to e-o-token */
3072 save_len = dbp - lb.buffer + 1;
3073 get_tagname = FALSE;
3074 found_tag = TRUE;
3075 continue;
3077 /* and proceed to check for "extern" */
3079 else if (!incomment && !inquote && !found_tag)
3081 /* check for proc/fn keywords */
3082 switch (lowcase (c))
3084 case 'p':
3085 if (tail ("rocedure")) /* c = 'p', dbp has advanced */
3086 get_tagname = TRUE;
3087 continue;
3088 case 'f':
3089 if (tail ("unction"))
3090 get_tagname = TRUE;
3091 continue;
3094 } /* while not eof */
3096 free (tline.buffer);
3100 * lisp tag functions
3101 * look for (def or (DEF, quote or QUOTE
3104 L_isdef (strp)
3105 register char *strp;
3107 return ((strp[1] == 'd' || strp[1] == 'D')
3108 && (strp[2] == 'e' || strp[2] == 'E')
3109 && (strp[3] == 'f' || strp[3] == 'F'));
3113 L_isquote (strp)
3114 register char *strp;
3116 return ((*(++strp) == 'q' || *strp == 'Q')
3117 && (*(++strp) == 'u' || *strp == 'U')
3118 && (*(++strp) == 'o' || *strp == 'O')
3119 && (*(++strp) == 't' || *strp == 'T')
3120 && (*(++strp) == 'e' || *strp == 'E')
3121 && isspace(*(++strp)));
3124 void
3125 L_getit ()
3127 register char *cp;
3129 if (*dbp == '\'') /* Skip prefix quote */
3130 dbp++;
3131 else if (*dbp == '(' && L_isquote (dbp)) /* Skip "(quote " */
3133 dbp += 7;
3134 while (isspace(*dbp))
3135 dbp++;
3137 for (cp = dbp /*+1*/;
3138 *cp && *cp != '(' && *cp != ' ' && *cp != ')';
3139 cp++)
3140 continue;
3141 if (cp == dbp)
3142 return;
3144 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
3145 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
3148 void
3149 Lisp_functions (inf)
3150 FILE *inf;
3152 lineno = 0;
3153 charno = 0;
3155 while (!feof (inf))
3157 lineno++;
3158 linecharno = charno;
3159 charno += readline (&lb, inf);
3160 dbp = lb.buffer;
3161 if (dbp[0] == '(')
3163 if (L_isdef (dbp))
3165 while (!isspace (*dbp))
3166 dbp++;
3167 while (isspace (*dbp))
3168 dbp++;
3169 L_getit ();
3171 else
3173 /* Check for (foo::defmumble name-defined ... */
3175 dbp++;
3176 while (*dbp && !isspace (*dbp)
3177 && *dbp != ':' && *dbp != '(' && *dbp != ')');
3178 if (*dbp == ':')
3181 dbp++;
3182 while (*dbp == ':');
3184 if (L_isdef (dbp - 1))
3186 while (!isspace (*dbp))
3187 dbp++;
3188 while (isspace (*dbp))
3189 dbp++;
3190 L_getit ();
3199 * Scheme tag functions
3200 * look for (def... xyzzy
3201 * look for (def... (xyzzy
3202 * look for (def ... ((...(xyzzy ....
3203 * look for (set! xyzzy
3206 void get_scheme ();
3208 void
3209 Scheme_functions (inf)
3210 FILE *inf;
3212 lineno = 0;
3213 charno = 0;
3215 while (!feof (inf))
3217 lineno++;
3218 linecharno = charno;
3219 charno += readline (&lb, inf);
3220 dbp = lb.buffer;
3221 if (dbp[0] == '(' &&
3222 (dbp[1] == 'D' || dbp[1] == 'd') &&
3223 (dbp[2] == 'E' || dbp[2] == 'e') &&
3224 (dbp[3] == 'F' || dbp[3] == 'f'))
3226 while (!isspace (*dbp))
3227 dbp++;
3228 /* Skip over open parens and white space */
3229 while (*dbp && (isspace (*dbp) || *dbp == '('))
3230 dbp++;
3231 get_scheme ();
3233 if (dbp[0] == '(' &&
3234 (dbp[1] == 'S' || dbp[1] == 's') &&
3235 (dbp[2] == 'E' || dbp[2] == 'e') &&
3236 (dbp[3] == 'T' || dbp[3] == 't') &&
3237 (dbp[4] == '!' || dbp[4] == '!') &&
3238 (isspace (dbp[5])))
3240 while (!isspace (*dbp))
3241 dbp++;
3242 /* Skip over white space */
3243 while (isspace (*dbp))
3244 dbp++;
3245 get_scheme ();
3250 void
3251 get_scheme ()
3253 register char *cp;
3255 if (*dbp == '\0')
3256 return;
3257 /* Go till you get to white space or a syntactic break */
3258 for (cp = dbp + 1;
3259 *cp && *cp != '(' && *cp != ')' && !isspace (*cp);
3260 cp++)
3261 continue;
3262 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
3263 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
3266 /* Find tags in TeX and LaTeX input files. */
3268 /* TEX_toktab is a table of TeX control sequences that define tags.
3269 Each TEX_tabent records one such control sequence.
3270 CONVERT THIS TO USE THE Stab TYPE!! */
3271 struct TEX_tabent
3273 char *name;
3274 int len;
3277 struct TEX_tabent *TEX_toktab = NULL; /* Table with tag tokens */
3279 /* Default set of control sequences to put into TEX_toktab.
3280 The value of environment var TEXTAGS is prepended to this. */
3282 char *TEX_defenv = "\
3283 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
3284 :part:appendix:entry:index";
3286 void TEX_mode ();
3287 struct TEX_tabent *TEX_decode_env ();
3288 int TEX_Token ();
3289 #if TeX_named_tokens
3290 void TEX_getit ();
3291 #endif
3293 char TEX_esc = '\\';
3294 char TEX_opgrp = '{';
3295 char TEX_clgrp = '}';
3298 * TeX/LaTeX scanning loop.
3300 void
3301 TeX_functions (inf)
3302 FILE *inf;
3304 char *lasthit;
3306 lineno = 0;
3307 charno = 0;
3309 /* Select either \ or ! as escape character. */
3310 TEX_mode (inf);
3312 /* Initialize token table once from environment. */
3313 if (!TEX_toktab)
3314 TEX_toktab = TEX_decode_env ("TEXTAGS", TEX_defenv);
3316 while (!feof (inf))
3317 { /* Scan each line in file */
3318 lineno++;
3319 linecharno = charno;
3320 charno += readline (&lb, inf);
3321 dbp = lb.buffer;
3322 lasthit = dbp;
3323 while (dbp = etags_strchr (dbp, TEX_esc)) /* Look at each esc in line */
3325 register int i;
3327 if (!*(++dbp))
3328 break;
3329 linecharno += dbp - lasthit;
3330 lasthit = dbp;
3331 i = TEX_Token (lasthit);
3332 if (0 <= i)
3334 pfnote (NULL, TRUE,
3335 lb.buffer, strlen (lb.buffer), lineno, linecharno);
3336 #if TeX_named_tokens
3337 TEX_getit (lasthit, TEX_toktab[i].len);
3338 #endif
3339 break; /* We only save a line once */
3345 #define TEX_LESC '\\'
3346 #define TEX_SESC '!'
3347 #define TEX_cmt '%'
3349 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
3350 chars accordingly. */
3351 void
3352 TEX_mode (inf)
3353 FILE *inf;
3355 int c;
3357 while ((c = getc (inf)) != EOF)
3359 /* Skip to next line if we hit the TeX comment char. */
3360 if (c == TEX_cmt)
3361 while (c != '\n')
3362 c = getc (inf);
3363 else if (c == TEX_LESC || c == TEX_SESC )
3364 break;
3367 if (c == TEX_LESC)
3369 TEX_esc = TEX_LESC;
3370 TEX_opgrp = '{';
3371 TEX_clgrp = '}';
3373 else
3375 TEX_esc = TEX_SESC;
3376 TEX_opgrp = '<';
3377 TEX_clgrp = '>';
3379 rewind (inf);
3382 /* Read environment and prepend it to the default string.
3383 Build token table. */
3384 struct TEX_tabent *
3385 TEX_decode_env (evarname, defenv)
3386 char *evarname;
3387 char *defenv;
3389 register char *env, *p;
3391 struct TEX_tabent *tab;
3392 int size, i;
3394 /* Append default string to environment. */
3395 env = getenv (evarname);
3396 if (!env)
3397 env = defenv;
3398 else
3399 env = concat (env, defenv, "");
3401 /* Allocate a token table */
3402 for (size = 1, p = env; p;)
3403 if ((p = etags_strchr (p, ':')) && *(++p))
3404 size++;
3405 /* Add 1 to leave room for null terminator. */
3406 tab = xnew (size + 1, struct TEX_tabent);
3408 /* Unpack environment string into token table. Be careful about */
3409 /* zero-length strings (leading ':', "::" and trailing ':') */
3410 for (i = 0; *env;)
3412 p = etags_strchr (env, ':');
3413 if (!p) /* End of environment string. */
3414 p = env + strlen (env);
3415 if (p - env > 0)
3416 { /* Only non-zero strings. */
3417 tab[i].name = savenstr (env, p - env);
3418 tab[i].len = strlen (tab[i].name);
3419 i++;
3421 if (*p)
3422 env = p + 1;
3423 else
3425 tab[i].name = NULL; /* Mark end of table. */
3426 tab[i].len = 0;
3427 break;
3430 return tab;
3433 #if TeX_named_tokens
3434 /* Record a tag defined by a TeX command of length LEN and starting at NAME.
3435 The name being defined actually starts at (NAME + LEN + 1).
3436 But we seem to include the TeX command in the tag name. */
3437 void
3438 TEX_getit (name, len)
3439 char *name;
3440 int len;
3442 char *p = name + len;
3444 if (*name == '\0')
3445 return;
3447 /* Let tag name extend to next group close (or end of line) */
3448 while (*p && *p != TEX_clgrp)
3449 p++;
3450 pfnote (savenstr (name, p-name), TRUE,
3451 lb.buffer, strlen (lb.buffer), lineno, linecharno);
3453 #endif
3455 /* If the text at CP matches one of the tag-defining TeX command names,
3456 return the pointer to the first occurrence of that command in TEX_toktab.
3457 Otherwise return -1.
3458 Keep the capital `T' in `Token' for dumb truncating compilers
3459 (this distinguishes it from `TEX_toktab' */
3461 TEX_Token (cp)
3462 char *cp;
3464 int i;
3466 for (i = 0; TEX_toktab[i].len > 0; i++)
3467 if (strneq (TEX_toktab[i].name, cp, TEX_toktab[i].len))
3468 return i;
3469 return -1;
3473 * Prolog support (rewritten) by Anders Lindgren, Mar. 96
3475 * Assumes that the predicate starts at column 0.
3476 * Only the first clause of a predicate is added.
3478 void
3479 Prolog_functions (inf)
3480 FILE *inf;
3482 int prolog_pred ();
3483 void prolog_skip_comment ();
3485 char * last;
3486 int len;
3487 int allocated;
3489 allocated = 0;
3490 len = 0;
3491 last = NULL;
3493 lineno = 0;
3494 linecharno = 0;
3495 charno = 0;
3497 while (!feof (inf))
3499 lineno++;
3500 linecharno += charno;
3501 charno = readline (&lb, inf);
3502 dbp = lb.buffer;
3503 if (dbp[0] == '\0') /* Empty line */
3504 continue;
3505 else if (isspace (dbp[0])) /* Not a predicate */
3506 continue;
3507 else if (dbp[0] == '/' && dbp[1] == '*') /* comment. */
3508 prolog_skip_comment (&lb, inf, &lineno, &linecharno);
3509 else if (len = prolog_pred (dbp, last))
3511 /* Predicate. Store the function name so that we only
3512 * generates a tag for the first clause. */
3513 if (last == NULL)
3514 last = xnew(len + 1, char);
3515 else if (len + 1 > allocated)
3516 last = (char *) xrealloc(last, len + 1);
3517 allocated = len + 1;
3518 strncpy (last, dbp, len);
3519 last[len] = '\0';
3525 void
3526 prolog_skip_comment (plb, inf)
3527 struct linebuffer *plb;
3528 FILE *inf;
3530 char *cp;
3534 for (cp = plb->buffer; *cp != '\0'; cp++)
3535 if (cp[0] == '*' && cp[1] == '/')
3536 return;
3537 lineno++;
3538 linecharno += readline (plb, inf);
3540 while (!feof(inf));
3544 * A predicate definition is added if it matches:
3545 * <beginning of line><Prolog Atom><whitespace>(
3547 * It is added to the tags database if it doesn't match the
3548 * name of the previous clause header.
3550 * Return the size of the name of the predicate, or 0 if no header
3551 * was found.
3554 prolog_pred (s, last)
3555 char *s;
3556 char *last; /* Name of last clause. */
3558 int prolog_atom();
3559 int prolog_white();
3561 int pos;
3562 int len;
3564 pos = prolog_atom(s, 0);
3565 if (pos < 1)
3566 return 0;
3568 len = pos;
3569 pos += prolog_white(s, pos);
3571 if ((s[pos] == '(') || (s[pos] == '.'))
3573 if (s[pos] == '(')
3574 pos++;
3576 /* Save only the first clause. */
3577 if ((last == NULL) ||
3578 (len != strlen(last)) ||
3579 (strncmp(s, last, len) != 0))
3581 pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
3582 s, pos, lineno, linecharno);
3583 return len;
3586 return 0;
3590 * Consume a Prolog atom.
3591 * Return the number of bytes consumed, or -1 if there was an error.
3593 * A prolog atom, in this context, could be one of:
3594 * - An alphanumeric sequence, starting with a lower case letter.
3595 * - A quoted arbitrary string. Single quotes can escape themselves.
3596 * Backslash quotes everything.
3599 prolog_atom (s, pos)
3600 char *s;
3601 int pos;
3603 int origpos;
3605 origpos = pos;
3607 if (islower(s[pos]) || (s[pos] == '_'))
3609 /* The atom is unquoted. */
3610 pos++;
3611 while (isalnum(s[pos]) || (s[pos] == '_'))
3613 pos++;
3615 return pos - origpos;
3617 else if (s[pos] == '\'')
3619 pos++;
3621 while (1)
3623 if (s[pos] == '\'')
3625 pos++;
3626 if (s[pos] != '\'')
3627 break;
3628 pos++; /* A double quote */
3630 else if (s[pos] == '\0')
3631 /* Multiline quoted atoms are ignored. */
3632 return -1;
3633 else if (s[pos] == '\\')
3635 if (s[pos+1] == '\0')
3636 return -1;
3637 pos += 2;
3639 else
3640 pos++;
3642 return pos - origpos;
3644 else
3645 return -1;
3648 /* Consume whitespace. Return the number of bytes eaten. */
3650 prolog_white (s, pos)
3651 char *s;
3652 int pos;
3654 int origpos;
3656 origpos = pos;
3658 while (isspace(s[pos]))
3659 pos++;
3661 return pos - origpos;
3665 * Support for Erlang -- Anders Lindgren, Feb 1996.
3667 * Generates tags for functions, defines, and records.
3669 * Assumes that Erlang functions start at column 0.
3671 void
3672 Erlang_functions (inf)
3673 FILE *inf;
3675 int erlang_func ();
3676 void erlang_attribute ();
3678 char * last;
3679 int len;
3680 int allocated;
3682 allocated = 0;
3683 len = 0;
3684 last = NULL;
3686 lineno = 0;
3687 linecharno = 0;
3688 charno = 0;
3690 while (!feof (inf))
3692 lineno++;
3693 linecharno += charno;
3694 charno = readline (&lb, inf);
3695 dbp = lb.buffer;
3696 if (dbp[0] == '\0') /* Empty line */
3697 continue;
3698 else if (isspace (dbp[0])) /* Not function nor attribute */
3699 continue;
3700 else if (dbp[0] == '%') /* comment */
3701 continue;
3702 else if (dbp[0] == '"') /* Sometimes, strings start in column one */
3703 continue;
3704 else if (dbp[0] == '-') /* attribute, e.g. "-define" */
3706 erlang_attribute(dbp);
3707 last = NULL;
3709 else if (len = erlang_func (dbp, last))
3712 * Function. Store the function name so that we only
3713 * generates a tag for the first clause.
3715 if (last == NULL)
3716 last = xnew(len + 1, char);
3717 else if (len + 1 > allocated)
3718 last = (char *) xrealloc(last, len + 1);
3719 allocated = len + 1;
3720 strncpy (last, dbp, len);
3721 last[len] = '\0';
3728 * A function definition is added if it matches:
3729 * <beginning of line><Erlang Atom><whitespace>(
3731 * It is added to the tags database if it doesn't match the
3732 * name of the previous clause header.
3734 * Return the size of the name of the function, or 0 if no function
3735 * was found.
3738 erlang_func (s, last)
3739 char *s;
3740 char *last; /* Name of last clause. */
3742 int erlang_atom ();
3743 int erlang_white ();
3745 int pos;
3746 int len;
3748 pos = erlang_atom(s, 0);
3749 if (pos < 1)
3750 return 0;
3752 len = pos;
3753 pos += erlang_white(s, pos);
3755 if (s[pos++] == '(')
3757 /* Save only the first clause. */
3758 if ((last == NULL) ||
3759 (len != strlen(last)) ||
3760 (strncmp(s, last, len) != 0))
3762 pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
3763 s, pos, lineno, linecharno);
3764 return len;
3767 return 0;
3772 * Handle attributes. Currently, tags are generated for defines
3773 * and records.
3775 * They are on the form:
3776 * -define(foo, bar).
3777 * -define(Foo(M, N), M+N).
3778 * -record(graph, {vtab = notable, cyclic = true}).
3780 void
3781 erlang_attribute (s)
3782 char *s;
3784 int erlang_atom ();
3785 int erlang_white ();
3787 int pos;
3788 int len;
3790 if ((strncmp(s, "-define", 7) == 0) ||
3791 (strncmp(s, "-record", 7) == 0))
3793 pos = 7;
3794 pos += erlang_white(s, pos);
3796 if (s[pos++] == '(')
3798 pos += erlang_white(s, pos);
3800 if (len = erlang_atom(s, pos))
3802 pfnote ((CTAGS) ? savenstr (& s[pos], len) : NULL, TRUE,
3803 s, pos + len, lineno, linecharno);
3807 return;
3812 * Consume an Erlang atom (or variable).
3813 * Return the number of bytes consumed, or -1 if there was an error.
3816 erlang_atom (s, pos)
3817 char *s;
3818 int pos;
3820 int origpos;
3822 origpos = pos;
3824 if (isalpha (s[pos]) || s[pos] == '_')
3826 /* The atom is unquoted. */
3827 pos++;
3828 while (isalnum (s[pos]) || s[pos] == '_')
3829 pos++;
3830 return pos - origpos;
3832 else if (s[pos] == '\'')
3834 pos++;
3836 while (1)
3838 if (s[pos] == '\'')
3840 pos++;
3841 break;
3843 else if (s[pos] == '\0')
3844 /* Multiline quoted atoms are ignored. */
3845 return -1;
3846 else if (s[pos] == '\\')
3848 if (s[pos+1] == '\0')
3849 return -1;
3850 pos += 2;
3852 else
3853 pos++;
3855 return pos - origpos;
3857 else
3858 return -1;
3861 /* Consume whitespace. Return the number of bytes eaten */
3863 erlang_white (s, pos)
3864 char *s;
3865 int pos;
3867 int origpos;
3869 origpos = pos;
3871 while (isspace (s[pos]))
3872 pos++;
3874 return pos - origpos;
3877 #ifdef ETAGS_REGEXPS
3878 /* Take a string like "/blah/" and turn it into "blah", making sure
3879 that the first and last characters are the same, and handling
3880 quoted separator characters. Actually, stops on the occurrence of
3881 an unquoted separator. Also turns "\t" into a Tab character.
3882 Returns pointer to terminating separator. Works in place. Null
3883 terminates name string. */
3884 char *
3885 scan_separators (name)
3886 char *name;
3888 char sep = name[0];
3889 char *copyto = name;
3890 logical quoted = FALSE;
3892 for (++name; *name != '\0'; ++name)
3894 if (quoted)
3896 if (*name == 't')
3897 *copyto++ = '\t';
3898 else if (*name == sep)
3899 *copyto++ = sep;
3900 else
3902 /* Something else is quoted, so preserve the quote. */
3903 *copyto++ = '\\';
3904 *copyto++ = *name;
3906 quoted = FALSE;
3908 else if (*name == '\\')
3909 quoted = TRUE;
3910 else if (*name == sep)
3911 break;
3912 else
3913 *copyto++ = *name;
3916 /* Terminate copied string. */
3917 *copyto = '\0';
3918 return name;
3921 /* Turn a name, which is an ed-style (but Emacs syntax) regular
3922 expression, into a real regular expression by compiling it. */
3923 void
3924 add_regex (regexp_pattern)
3925 char *regexp_pattern;
3927 char *name;
3928 const char *err;
3929 struct re_pattern_buffer *patbuf;
3931 if (regexp_pattern == NULL)
3933 /* Remove existing regexps. */
3934 num_patterns = 0;
3935 patterns = NULL;
3936 return;
3939 if (regexp_pattern[0] == '\0')
3941 error ("missing regexp", 0);
3942 return;
3944 if (regexp_pattern[strlen(regexp_pattern)-1] != regexp_pattern[0])
3946 error ("%s: unterminated regexp", regexp_pattern);
3947 return;
3949 name = scan_separators (regexp_pattern);
3950 if (regexp_pattern[0] == '\0')
3952 error ("null regexp", 0);
3953 return;
3955 (void) scan_separators (name);
3957 patbuf = xnew (1, struct re_pattern_buffer);
3958 patbuf->translate = NULL;
3959 patbuf->fastmap = NULL;
3960 patbuf->buffer = NULL;
3961 patbuf->allocated = 0;
3963 err = re_compile_pattern (regexp_pattern, strlen (regexp_pattern), patbuf);
3964 if (err != NULL)
3966 error ("%s while compiling pattern", err);
3967 return;
3970 num_patterns += 1;
3971 if (num_patterns == 1)
3972 patterns = xnew (1, struct pattern);
3973 else
3974 patterns = ((struct pattern *)
3975 xrealloc (patterns,
3976 (num_patterns * sizeof (struct pattern))));
3977 patterns[num_patterns - 1].pattern = patbuf;
3978 patterns[num_patterns - 1].name_pattern = savestr (name);
3979 patterns[num_patterns - 1].error_signaled = FALSE;
3983 * Do the substitutions indicated by the regular expression and
3984 * arguments.
3986 char *
3987 substitute (in, out, regs)
3988 char *in, *out;
3989 struct re_registers *regs;
3991 char *result = NULL, *t;
3992 int size = 0;
3994 /* Pass 1: figure out how much size to allocate. */
3995 for (t = out; *t; ++t)
3997 if (*t == '\\')
3999 ++t;
4000 if (!*t)
4002 fprintf (stderr, "%s: pattern substitution ends prematurely\n",
4003 progname);
4004 return NULL;
4006 if (isdigit (*t))
4008 int dig = *t - '0';
4009 size += regs->end[dig] - regs->start[dig];
4014 /* Allocate space and do the substitutions. */
4015 result = xnew (size + 1, char);
4016 size = 0;
4017 for (; *out; ++out)
4019 if (*out == '\\')
4021 ++out;
4022 if (isdigit (*out))
4024 /* Using "dig2" satisfies my debugger. Bleah. */
4025 int dig2 = *out - '0';
4026 strncpy (result + size, in + regs->start[dig2],
4027 regs->end[dig2] - regs->start[dig2]);
4028 size += regs->end[dig2] - regs->start[dig2];
4030 else
4031 result[size++] = *out;
4033 else
4034 result[size++] = *out;
4036 result[size] = '\0';
4038 return result;
4041 #endif /* ETAGS_REGEXPS */
4042 /* Initialize a linebuffer for use */
4043 void
4044 initbuffer (linebuffer)
4045 struct linebuffer *linebuffer;
4047 linebuffer->size = 200;
4048 linebuffer->buffer = xnew (200, char);
4052 * Read a line of text from `stream' into `linebuffer'.
4053 * Return the number of characters read from `stream',
4054 * which is the length of the line including the newline, if any.
4056 long
4057 readline_internal (linebuffer, stream)
4058 struct linebuffer *linebuffer;
4059 register FILE *stream;
4061 char *buffer = linebuffer->buffer;
4062 register char *p = linebuffer->buffer;
4063 register char *pend;
4064 int chars_deleted;
4066 pend = p + linebuffer->size; /* Separate to avoid 386/IX compiler bug. */
4068 while (1)
4070 register int c = getc (stream);
4071 if (p == pend)
4073 linebuffer->size *= 2;
4074 buffer = (char *) xrealloc (buffer, linebuffer->size);
4075 p += buffer - linebuffer->buffer;
4076 pend = buffer + linebuffer->size;
4077 linebuffer->buffer = buffer;
4079 if (c == EOF)
4081 *p = '\0';
4082 chars_deleted = 0;
4083 break;
4085 if (c == '\n')
4087 if (p > buffer && p[-1] == '\r')
4089 *--p = '\0';
4090 chars_deleted = 2;
4092 else
4094 *p = '\0';
4095 chars_deleted = 1;
4097 break;
4099 *p++ = c;
4102 return p - buffer + chars_deleted;
4106 * Like readline_internal, above, but try to match the input
4107 * line against any existing regular expressions.
4109 long
4110 readline (linebuffer, stream)
4111 struct linebuffer *linebuffer;
4112 FILE *stream;
4114 /* Read new line. */
4115 long result = readline_internal (linebuffer, stream);
4116 #ifdef ETAGS_REGEXPS
4117 int i;
4119 /* Match against all listed patterns. */
4120 for (i = 0; i < num_patterns; ++i)
4122 int match = re_match (patterns[i].pattern, linebuffer->buffer,
4123 (int)result, 0, &patterns[i].regs);
4124 switch (match)
4126 case -2:
4127 /* Some error. */
4128 if (!patterns[i].error_signaled)
4130 error ("error while matching pattern %d", i);
4131 patterns[i].error_signaled = TRUE;
4133 break;
4134 case -1:
4135 /* No match. */
4136 break;
4137 default:
4138 /* Match occurred. Construct a tag. */
4139 if (patterns[i].name_pattern[0] != '\0')
4141 /* Make a named tag. */
4142 char *name = substitute (linebuffer->buffer,
4143 patterns[i].name_pattern,
4144 &patterns[i].regs);
4145 if (name != NULL)
4146 pfnote (name, TRUE,
4147 linebuffer->buffer, match, lineno, linecharno);
4149 else
4151 /* Make an unnamed tag. */
4152 pfnote (NULL, TRUE,
4153 linebuffer->buffer, match, lineno, linecharno);
4155 break;
4158 #endif /* ETAGS_REGEXPS */
4160 return result;
4164 * Read a file, but do no processing. This is used to do regexp
4165 * matching on files that have no language defined.
4167 void
4168 just_read_file (inf)
4169 FILE *inf;
4171 lineno = 0;
4172 charno = 0;
4174 while (!feof (inf))
4176 ++lineno;
4177 linecharno = charno;
4178 charno += readline (&lb, inf) + 1;
4184 * Return a pointer to a space of size strlen(cp)+1 allocated
4185 * with xnew where the string CP has been copied.
4187 char *
4188 savestr (cp)
4189 char *cp;
4191 return savenstr (cp, strlen (cp));
4195 * Return a pointer to a space of size LEN+1 allocated with xnew where
4196 * the string CP has been copied for at most the first LEN characters.
4198 char *
4199 savenstr (cp, len)
4200 char *cp;
4201 int len;
4203 register char *dp;
4205 dp = xnew (len + 1, char);
4206 strncpy (dp, cp, len);
4207 dp[len] = '\0';
4208 return dp;
4212 * Return the ptr in sp at which the character c last
4213 * appears; NULL if not found
4215 * Identical to System V strrchr, included for portability.
4217 char *
4218 etags_strrchr (sp, c)
4219 register char *sp, c;
4221 register char *r;
4223 r = NULL;
4226 if (*sp == c)
4227 r = sp;
4228 } while (*sp++);
4229 return r;
4234 * Return the ptr in sp at which the character c first
4235 * appears; NULL if not found
4237 * Identical to System V strchr, included for portability.
4239 char *
4240 etags_strchr (sp, c)
4241 register char *sp, c;
4245 if (*sp == c)
4246 return sp;
4247 } while (*sp++);
4248 return NULL;
4251 /* Print error message and exit. */
4252 void
4253 fatal (s1, s2)
4254 char *s1, *s2;
4256 error (s1, s2);
4257 exit (BAD);
4260 void
4261 pfatal (s1)
4262 char *s1;
4264 perror (s1);
4265 exit (BAD);
4268 void
4269 suggest_asking_for_help ()
4271 fprintf (stderr, "\tTry `%s --help' for a complete list of options.\n",
4272 progname);
4273 exit (BAD);
4276 /* Print error message. `s1' is printf control string, `s2' is arg for it. */
4277 void
4278 error (s1, s2)
4279 char *s1, *s2;
4281 fprintf (stderr, "%s: ", progname);
4282 fprintf (stderr, s1, s2);
4283 fprintf (stderr, "\n");
4286 /* Return a newly-allocated string whose contents
4287 concatenate those of s1, s2, s3. */
4288 char *
4289 concat (s1, s2, s3)
4290 char *s1, *s2, *s3;
4292 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
4293 char *result = xnew (len1 + len2 + len3 + 1, char);
4295 strcpy (result, s1);
4296 strcpy (result + len1, s2);
4297 strcpy (result + len1 + len2, s3);
4298 result[len1 + len2 + len3] = '\0';
4300 return result;
4303 /* Does the same work as the system V getcwd, but does not need to
4304 guess the buffer size in advance. */
4305 char *
4306 etags_getcwd ()
4308 #ifdef MSDOS
4309 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
4311 getwd (path);
4312 for (p = path; *p != '\0'; p++)
4313 if (*p == '\\')
4314 *p = '/';
4315 else
4316 *p = lowcase (*p);
4318 return strdup (path);
4319 #else /* not MSDOS */
4320 #if HAVE_GETCWD
4321 int bufsize = 200;
4322 char *path = xnew (bufsize, char);
4324 while (getcwd (path, bufsize) == NULL)
4326 if (errno != ERANGE)
4327 pfatal ("getcwd");
4328 bufsize *= 2;
4329 path = xnew (bufsize, char);
4332 return path;
4333 #else /* not MSDOS and not HAVE_GETCWD */
4334 struct linebuffer path;
4335 FILE *pipe;
4337 initbuffer (&path);
4338 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
4339 if (pipe == NULL || readline_internal (&path, pipe) == 0)
4340 pfatal ("pwd");
4341 pclose (pipe);
4343 return path.buffer;
4344 #endif /* not HAVE_GETCWD */
4345 #endif /* not MSDOS */
4348 /* Return a newly allocated string containing the filename
4349 of FILE relative to the absolute directory DIR (which
4350 should end with a slash). */
4351 char *
4352 relative_filename (file, dir)
4353 char *file, *dir;
4355 char *fp, *dp, *abs, *res;
4357 /* Find the common root of file and dir. */
4358 abs = absolute_filename (file, cwd);
4359 fp = abs;
4360 dp = dir;
4361 while (*fp++ == *dp++)
4362 continue;
4365 fp--;
4366 dp--;
4368 while (*fp != '/');
4370 /* Build a sequence of "../" strings for the resulting relative filename. */
4371 for (dp = etags_strchr (dp + 1, '/'), res = "";
4372 dp != NULL;
4373 dp = etags_strchr (dp + 1, '/'))
4375 res = concat (res, "../", "");
4378 /* Add the filename relative to the common root of file and dir. */
4379 res = concat (res, fp + 1, "");
4380 free (abs);
4382 return res;
4385 /* Return a newly allocated string containing the
4386 absolute filename of FILE given CWD (which should
4387 end with a slash). */
4388 char *
4389 absolute_filename (file, cwd)
4390 char *file, *cwd;
4392 char *slashp, *cp, *res;
4394 if (absolutefn (file))
4395 res = concat (file, "", "");
4396 #ifdef DOS_NT
4397 /* We don't support non-absolute filenames with a drive
4398 letter, like `d:NAME' (it's too much hassle). */
4399 else if (file[1] == ':')
4400 fatal ("%s: relative filenames with drive letters not supported", file);
4401 #endif
4402 else
4403 res = concat (cwd, file, "");
4405 /* Delete the "/dirname/.." and "/." substrings. */
4406 slashp = etags_strchr (res, '/');
4407 while (slashp != NULL && slashp[0] != '\0')
4409 if (slashp[1] == '.')
4411 if (slashp[2] == '.'
4412 && (slashp[3] == '/' || slashp[3] == '\0'))
4414 cp = slashp;
4416 cp--;
4417 while (cp >= res && !absolutefn (cp));
4418 if (*cp == '/')
4420 strcpy (cp, slashp + 3);
4422 #ifdef DOS_NT
4423 /* Under MSDOS and NT we get `d:/NAME' as absolute
4424 filename, so the luser could say `d:/../NAME'.
4425 We silently treat this as `d:/NAME'. */
4426 else if (cp[1] == ':')
4427 strcpy (cp + 3, slashp + 4);
4428 #endif
4429 else /* else (cp == res) */
4431 if (slashp[3] != '\0')
4432 strcpy (cp, slashp + 4);
4433 else
4434 return ".";
4436 slashp = cp;
4437 continue;
4439 else if (slashp[2] == '/' || slashp[2] == '\0')
4441 strcpy (slashp, slashp + 2);
4442 continue;
4446 slashp = etags_strchr (slashp + 1, '/');
4449 return res;
4452 /* Return a newly allocated string containing the absolute
4453 filename of dir where FILE resides given CWD (which should
4454 end with a slash). */
4455 char *
4456 absolute_dirname (file, cwd)
4457 char *file, *cwd;
4459 char *slashp, *res;
4460 char save;
4461 #ifdef DOS_NT
4462 char *p;
4464 for (p = file; *p != '\0'; p++)
4465 if (*p == '\\')
4466 *p = '/';
4467 #endif
4469 slashp = etags_strrchr (file, '/');
4470 if (slashp == NULL)
4471 return cwd;
4472 save = slashp[1];
4473 slashp[1] = '\0';
4474 res = absolute_filename (file, cwd);
4475 slashp[1] = save;
4477 return res;
4480 /* Like malloc but get fatal error if memory is exhausted. */
4481 long *
4482 xmalloc (size)
4483 unsigned int size;
4485 long *result = (long *) malloc (size);
4486 if (result == NULL)
4487 fatal ("virtual memory exhausted", 0);
4488 return result;
4491 long *
4492 xrealloc (ptr, size)
4493 char *ptr;
4494 unsigned int size;
4496 long *result = (long *) realloc (ptr, size);
4497 if (result == NULL)
4498 fatal ("virtual memory exhausted");
4499 return result;