Update MSDOS info.
[bpt/emacs.git] / lib-src / etags.c
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
4
5 This file is not considered part of GNU Emacs.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
20
21 /*
22 * Authors:
23 * Ctags originally by Ken Arnold.
24 * Fortran added by Jim Kleckner.
25 * Ed Pelegri-Llopart added C typedefs.
26 * Gnu Emacs TAGS format and modifications by RMS?
27 * Sam Kendall added C++.
28 * Francesco Potorti` reorganised C and C++ based on work by Joe Wells.
29 * Regexp tags by Tom Tromey.
30 *
31 * Francesco Potorti` (F.Potorti@cnuce.cnr.it) is the current maintainer.
32 */
33
34 char pot_etags_version[] = "@(#) pot revision number is 11.59";
35
36 #define TRUE 1
37 #define FALSE 0
38
39 #ifndef DEBUG
40 # define DEBUG FALSE
41 #endif
42
43 #ifdef MSDOS
44 # include <fcntl.h>
45 # include <sys/param.h>
46 #endif /* MSDOS */
47
48 #ifdef WINDOWSNT
49 # include <stdlib.h>
50 # include <fcntl.h>
51 # include <string.h>
52 # define MAXPATHLEN _MAX_PATH
53 #endif
54
55 #ifdef HAVE_CONFIG_H
56 # include <config.h>
57 /* On some systems, Emacs defines static as nothing for the sake
58 of unexec. We don't want that here since we don't use unexec. */
59 # undef static
60 #endif
61
62 #include <stdio.h>
63 #include <ctype.h>
64 #include <errno.h>
65 #ifndef errno
66 extern int errno;
67 #endif
68 #include <sys/types.h>
69 #include <sys/stat.h>
70
71 #if !defined (S_ISREG) && defined (S_IFREG)
72 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
73 #endif
74
75 #include <getopt.h>
76
77 #ifdef ETAGS_REGEXPS
78 # include <regex.h>
79 #endif /* ETAGS_REGEXPS */
80
81 /* Define CTAGS to make the program "ctags" compatible with the usual one.
82 Let it undefined to make the program "etags", which makes emacs-style
83 tag tables and tags typedefs, #defines and struct/union/enum by default. */
84 #ifdef CTAGS
85 # undef CTAGS
86 # define CTAGS TRUE
87 #else
88 # define CTAGS FALSE
89 #endif
90
91 /* Exit codes for success and failure. */
92 #ifdef VMS
93 # define GOOD 1
94 # define BAD 0
95 #else
96 # define GOOD 0
97 # define BAD 1
98 #endif
99
100 /* C extensions. */
101 #define C_PLPL 0x00001 /* C++ */
102 #define C_STAR 0x00003 /* C* */
103 #define YACC 0x10000 /* yacc file */
104
105 #define streq(s,t) ((DEBUG &&!(s)&&!(t)&&(abort(),1)) || !strcmp(s,t))
106 #define strneq(s,t,n) ((DEBUG &&!(s)&&!(t)&&(abort(),1)) || !strncmp(s,t,n))
107
108 #define lowcase(c) tolower ((unsigned char)c)
109
110 #define iswhite(arg) (_wht[arg]) /* T if char is white */
111 #define begtoken(arg) (_btk[arg]) /* T if char can start token */
112 #define intoken(arg) (_itk[arg]) /* T if char can be in token */
113 #define endtoken(arg) (_etk[arg]) /* T if char ends tokens */
114
115 #ifdef DOS_NT
116 # define absolutefn(fn) (fn[0] == '/' \
117 || (isalpha (fn[0]) && fn[1] == ':' && fn[2] == '/'))
118 #else
119 # define absolutefn(fn) (fn[0] == '/')
120 #endif
121
122
123 /*
124 * xnew -- allocate storage
125 *
126 * SYNOPSIS: Type *xnew (int n, Type);
127 */
128 #define xnew(n,Type) ((Type *) xmalloc ((n) * sizeof (Type)))
129
130 typedef int logical;
131
132 typedef struct nd_st
133 { /* sorting structure */
134 char *name; /* function or type name */
135 char *file; /* file name */
136 logical is_func; /* use pattern or line no */
137 logical been_warned; /* set if noticed dup */
138 int lno; /* line number tag is on */
139 long cno; /* character number line starts on */
140 char *pat; /* search pattern */
141 struct nd_st *left, *right; /* left and right sons */
142 } NODE;
143
144 extern char *getenv ();
145
146 char *concat ();
147 char *savenstr (), *savestr ();
148 char *etags_strchr (), *etags_strrchr ();
149 char *etags_getcwd ();
150 char *relative_filename (), *absolute_filename (), *absolute_dirname ();
151 long *xmalloc (), *xrealloc ();
152
153 typedef void Lang_function ();
154 #if FALSE /* many compilers barf on this */
155 Lang_function Asm_labels;
156 Lang_function default_C_entries;
157 Lang_function C_entries;
158 Lang_function Cplusplus_entries;
159 Lang_function Cstar_entries;
160 Lang_function Erlang_functions;
161 Lang_function Fortran_functions;
162 Lang_function Yacc_entries;
163 Lang_function Lisp_functions;
164 Lang_function Pascal_functions;
165 Lang_function Perl_functions;
166 Lang_function Prolog_functions;
167 Lang_function Scheme_functions;
168 Lang_function TeX_functions;
169 Lang_function just_read_file;
170 #else /* so let's write it this way */
171 void Asm_labels ();
172 void C_entries ();
173 void default_C_entries ();
174 void plain_C_entries ();
175 void Cplusplus_entries ();
176 void Cstar_entries ();
177 void Erlang_functions ();
178 void Fortran_functions ();
179 void Yacc_entries ();
180 void Lisp_functions ();
181 void Pascal_functions ();
182 void Perl_functions ();
183 void Prolog_functions ();
184 void Scheme_functions ();
185 void TeX_functions ();
186 void just_read_file ();
187 #endif
188
189 Lang_function *get_language_from_name ();
190 Lang_function *get_language_from_interpreter ();
191 Lang_function *get_language_from_suffix ();
192 int total_size_of_entries ();
193 long readline ();
194 long readline_internal ();
195 #ifdef ETAGS_REGEXPS
196 void add_regex ();
197 #endif
198 void add_node ();
199 void error ();
200 void suggest_asking_for_help ();
201 void fatal (), pfatal ();
202 void find_entries ();
203 void free_tree ();
204 void getit ();
205 void init ();
206 void initbuffer ();
207 void pfnote ();
208 void process_file ();
209 void put_entries ();
210 void takeprec ();
211
212 \f
213 char searchar = '/'; /* use /.../ searches */
214
215 int lineno; /* line number of current line */
216 long charno; /* current character number */
217
218 long linecharno; /* charno of start of line; not used by C,
219 but by every other language. */
220
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 */
226
227 FILE *tagf; /* ioptr for tags file */
228 NODE *head; /* the head of the binary tree of tags */
229
230 /*
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.
234 */
235 #define GROW_LINEBUFFER(buf,toksize) \
236 while (buf.size < toksize) \
237 buf.buffer = (char *) xrealloc (buf.buffer, buf.size *= 2)
238 struct linebuffer
239 {
240 long size;
241 char *buffer;
242 };
243
244 struct linebuffer lb; /* the current line */
245 struct linebuffer token_name; /* used by C_entries as a temporary area */
246 struct
247 {
248 long linepos;
249 struct linebuffer lb; /* used by C_entries instead of lb */
250 } lbs[2];
251
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";
263
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 */
279
280 struct option longopts[] =
281 {
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 }
303 };
304
305 #ifdef ETAGS_REGEXPS
306 /* Structure defining a regular expression. Elements are
307 the compiled pattern, and the name string. */
308 struct pattern
309 {
310 struct re_pattern_buffer *pattern;
311 struct re_registers regs;
312 char *name_pattern;
313 logical error_signaled;
314 };
315
316 /* Number of regexps found. */
317 int num_patterns = 0;
318
319 /* Array of all regexps. */
320 struct pattern *patterns = NULL;
321 #endif /* ETAGS_REGEXPS */
322
323 /*
324 * Language stuff.
325 */
326
327 /* Non-NULL if language fixed. */
328 Lang_function *lang_func = NULL;
329
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
339 };
340
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 };
345
346 /* .M is for Objective C++ files. */
347 char *Cplusplus_suffixes [] =
348 { "C", "H", "c++", "cc", "cpp", "cxx", "h++", "hh", "hpp", "hxx", "M", NULL};
349
350 char *Cstar_suffixes [] =
351 { "cs", "hs", NULL };
352
353 char *Erlang_suffixes [] =
354 { "erl", "hrl", NULL };
355
356 char *Fortran_suffixes [] =
357 { "F", "f", "f90", "for", NULL };
358
359 char *Lisp_suffixes [] =
360 { "cl", "clisp", "el", "l", "lisp", "lsp", "ml", NULL };
361
362 char *Pascal_suffixes [] =
363 { "p", "pas", NULL };
364
365 char *Perl_suffixes [] =
366 { "pl", "pm", NULL };
367 char *Perl_interpreters [] =
368 { "perl", "@PERL@", NULL };
369
370 char *plain_C_suffixes [] =
371 { "pc", /* Pro*C file */
372 "m", /* Objective C file */
373 "lm", /* Objective lex file */
374 NULL };
375
376 char *Prolog_suffixes [] =
377 { "prolog", NULL };
378
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 };
382
383 char *TeX_suffixes [] =
384 { "TeX", "bib", "clo", "cls", "ltx", "sty", "tex", NULL };
385
386 char *Yacc_suffixes [] =
387 { "y", "ym", NULL }; /* .ym is Objective yacc file */
388
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
394 {
395 char *name;
396 Lang_function *function;
397 char **suffixes;
398 char **interpreters;
399 };
400
401 struct lang_entry lang_names [] =
402 {
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 */
420 };
421
422 \f
423 void
424 print_language_names ()
425 {
426 struct lang_entry *lang;
427 char **ext;
428
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++)
432 {
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 ("");
438 }
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.");
445 }
446
447 #ifndef VERSION
448 # define VERSION "19"
449 #endif
450 void
451 print_version ()
452 {
453 printf ("%s for Emacs version %s\n", (CTAGS) ? "ctags" : "etags", VERSION);
454
455 exit (GOOD);
456 }
457
458 void
459 print_help ()
460 {
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");
468
469 puts ("-a, --append\n\
470 Append tag entries to existing tags file.");
471
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.");
476
477 puts ("-C, --c++\n\
478 Treat files whose name suffix defaults to C language as C++ files.");
479
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.");
487
488 if (!CTAGS)
489 {
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.");
497 }
498
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++.");
516
517 if (CTAGS)
518 {
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.");
543 }
544
545 puts ("-V, --version\n\
546 Print the version of the program.\n\
547 -h, --help\n\
548 Print this help message.");
549
550 print_language_names ();
551
552 exit (GOOD);
553 }
554
555 \f
556 enum argument_type
557 {
558 at_language,
559 at_regexp,
560 at_filename
561 };
562
563 /* This structure helps us allow mixing of --lang and filenames. */
564 typedef struct
565 {
566 enum argument_type arg_type;
567 char *what;
568 Lang_function *function;
569 } argument;
570
571 #ifdef VMS /* VMS specific functions */
572
573 #define EOS '\0'
574
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;
582
583 /*
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.
593
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.
598 */
599
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;
607 {
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;
614
615 if (pass1)
616 {
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;
626 }
627 if ((status = lib$find_file(&i, &o, &context, 0, 0)) == RMS$_NORMAL)
628 {
629 out->body[out->curlen] = EOS;
630 return 1;
631 }
632 else if (status == RMS$_NMF)
633 retval = 0;
634 else
635 {
636 strcpy(out->body, in);
637 retval = -1;
638 }
639 lib$find_file_end(&context);
640 pass1 = TRUE;
641 return retval;
642 }
643
644 /*
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.
647 */
648 char *
649 gfnames (arg, p_error)
650 char *arg;
651 logical *p_error;
652 {
653 static vspec filename = {MAX_FILE_SPEC_LEN, "\0"};
654
655 switch (fn_exp (&filename, arg))
656 {
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;
666 }
667 }
668
669 #ifndef OLD /* Newer versions of VMS do provide `system'. */
670 system (cmd)
671 char *cmd;
672 {
673 fprintf (stderr, "system() function not implemented under VMS\n");
674 }
675 #endif
676
677 #define VERSION_DELIM ';'
678 char *massage_name (s)
679 char *s;
680 {
681 char *start = s;
682
683 for ( ; *s; s++)
684 if (*s == VERSION_DELIM)
685 {
686 *s = EOS;
687 break;
688 }
689 else
690 *s = lowcase (*s);
691 return start;
692 }
693 #endif /* VMS */
694
695 \f
696 void
697 main (argc, argv)
698 int argc;
699 char *argv[];
700 {
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
711
712 #ifdef DOS_NT
713 _fmode = O_BINARY; /* all of files are treated as binary files */
714 #endif /* DOS_NT */
715
716 progname = argv[0];
717
718 /* Allocate enough no matter what happens. Overkill, but each one
719 is small. */
720 argbuffer = xnew (argc, argument);
721
722 #ifdef ETAGS_REGEXPS
723 /* Set syntax for regular expression routines. */
724 re_set_syntax (RE_SYNTAX_EMACS);
725 #endif /* ETAGS_REGEXPS */
726
727 /*
728 * If etags, always find typedefs and structure tags. Why not?
729 * Also default is to find macro constants.
730 */
731 if (!CTAGS)
732 typedefs = typedefs_and_cplusplus = constantypedefs = TRUE;
733
734 while (1)
735 {
736 int opt = getopt_long (argc, argv,
737 "-aCdDf:Il:o:r:RStTi:BuvxwVhH", longopts, 0);
738
739 if (opt == EOF)
740 break;
741
742 switch (opt)
743 {
744 case 0:
745 /* If getopt returns 0, then it has already processed a
746 long-named option. We should do nothing. */
747 break;
748
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;
756
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)
773 {
774 fprintf (stderr, "%s: -%c option may only be given once.\n",
775 progname, opt);
776 suggest_asking_for_help ();
777 }
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 ();
839 }
840 }
841
842 for (; optind < argc; ++optind)
843 {
844 argbuffer[current_arg].arg_type = at_filename;
845 argbuffer[current_arg].what = argv[optind];
846 ++current_arg;
847 ++file_count;
848 }
849
850 if (nincluded_files == 0 && file_count == 0)
851 {
852 fprintf (stderr, "%s: No input files specified.\n", progname);
853 suggest_asking_for_help ();
854 }
855
856 if (tagfile == NULL)
857 tagfile = CTAGS ? "tags" : "TAGS";
858 cwd = etags_getcwd (); /* the current working directory */
859 if (cwd[strlen(cwd)-1] != '/')
860 strcat (cwd, "/");
861 if (streq (tagfile, "-"))
862 tagfiledir = cwd;
863 else
864 tagfiledir = absolute_dirname (tagfile, cwd);
865
866 init (); /* set up boolean "functions" */
867
868 initbuffer (&lb);
869 initbuffer (&token_name);
870 initbuffer (&lbs[0].lb);
871 initbuffer (&lbs[1].lb);
872 initbuffer (&filename_lb);
873
874 if (!CTAGS)
875 {
876 if (streq (tagfile, "-"))
877 tagf = stdout;
878 else
879 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
880 if (tagf == NULL)
881 pfatal (tagfile);
882 }
883
884 /*
885 * Loop through files finding functions.
886 */
887 for (i = 0; i < current_arg; ++i)
888 {
889 switch (argbuffer[i].arg_type)
890 {
891 case at_language:
892 lang_func = argbuffer[i].function;
893 break;
894 #ifdef ETAGS_REGEXPS
895 case at_regexp:
896 add_regex (argbuffer[i].what);
897 break;
898 #endif
899 case at_filename:
900 #ifdef VMS
901 while ((this_file = gfnames (argbuffer[i].what, &got_err)) != NULL)
902 {
903 if (got_err)
904 {
905 error ("Can't find file %s\n", this_file);
906 argc--, argv++;
907 }
908 else
909 {
910 this_file = massage_name (this_file);
911 }
912 #else
913 this_file = argbuffer[i].what;
914 #endif
915 /* Input file named "-" means read file names from stdin
916 and use them. */
917 if (streq (this_file, "-"))
918 while (readline_internal (&filename_lb, stdin) > 0)
919 process_file (filename_lb.buffer);
920 else
921 process_file (this_file);
922 #ifdef VMS
923 }
924 #endif
925 break;
926 }
927 }
928
929 if (!CTAGS)
930 {
931 while (nincluded_files-- > 0)
932 fprintf (tagf, "\f\n%s,include\n", *included_files++);
933
934 fclose (tagf);
935 exit (GOOD);
936 }
937
938 /* If CTAGS, we are here. process_file did not write the tags yet,
939 because we want them ordered. Let's do it now. */
940 if (cxref_style)
941 {
942 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
943 if (tagf == NULL)
944 pfatal (tagfile);
945 put_entries (head);
946 exit (GOOD);
947 }
948
949 if (update)
950 {
951 char cmd[BUFSIZ];
952 for (i = 0; i < current_arg; ++i)
953 {
954 if (argbuffer[i].arg_type != at_filename)
955 continue;
956 sprintf (cmd,
957 "mv %s OTAGS;fgrep -v '\t%s\t' OTAGS >%s;rm OTAGS",
958 tagfile, argbuffer[i].what, tagfile);
959 if (system (cmd) != GOOD)
960 fatal ("failed to execute shell command");
961 }
962 append_to_tagfile = TRUE;
963 }
964
965 tagf = fopen (tagfile, append_to_tagfile ? "a" : "w");
966 if (tagf == NULL)
967 pfatal (tagfile);
968 put_entries (head);
969 fclose (tagf);
970
971 if (update)
972 {
973 char cmd[BUFSIZ];
974 sprintf (cmd, "sort %s -o %s", tagfile, tagfile);
975 exit (system (cmd));
976 }
977 exit (GOOD);
978 }
979
980
981 /*
982 * Return a Lang_function given the name.
983 */
984 Lang_function *
985 get_language_from_name (name)
986 char *name;
987 {
988 struct lang_entry *lang;
989
990 if (name != NULL)
991 for (lang = lang_names; lang->name != NULL; lang++)
992 {
993 if (streq (name, lang->name))
994 return lang->function;
995 }
996
997 fprintf (stderr, "%s: language \"%s\" not recognized.\n",
998 progname, optarg);
999 suggest_asking_for_help ();
1000
1001 /* This point should never be reached. The function should either
1002 return a function pointer or never return. Note that a NULL
1003 pointer cannot be considered as an error, as it means that the
1004 language has not been explicitely imposed by the user ("auto"). */
1005 return NULL; /* avoid warnings from compiler */
1006 }
1007
1008
1009 /*
1010 * Return a Lang_function given the interpreter name.
1011 */
1012 Lang_function *
1013 get_language_from_interpreter (interpreter)
1014 char *interpreter;
1015 {
1016 struct lang_entry *lang;
1017 char **iname;
1018
1019 if (interpreter == NULL)
1020 return NULL;
1021 for (lang = lang_names; lang->name != NULL; lang++)
1022 if (lang->interpreters != NULL)
1023 for (iname = lang->interpreters; *iname != NULL; iname++)
1024 if (streq (*iname, interpreter))
1025 return lang->function;
1026
1027 return NULL;
1028 }
1029
1030
1031
1032 /*
1033 * Return a Lang_function given the file suffix.
1034 */
1035 Lang_function *
1036 get_language_from_suffix (suffix)
1037 char *suffix;
1038 {
1039 struct lang_entry *lang;
1040 char **ext;
1041
1042 if (suffix == NULL)
1043 return NULL;
1044 for (lang = lang_names; lang->name != NULL; lang++)
1045 if (lang->suffixes != NULL)
1046 for (ext = lang->suffixes; *ext != NULL; ext++)
1047 if (streq (*ext, suffix))
1048 return lang->function;
1049
1050 return NULL;
1051 }
1052
1053
1054 /*
1055 * This routine is called on each file argument.
1056 */
1057 void
1058 process_file (file)
1059 char *file;
1060 {
1061 struct stat stat_buf;
1062 FILE *inf;
1063
1064 if (stat (file, &stat_buf) == 0 && !S_ISREG (stat_buf.st_mode))
1065 {
1066 fprintf (stderr, "Skipping %s: it is not a regular file.\n", file);
1067 return;
1068 }
1069 if (streq (file, tagfile) && !streq (tagfile, "-"))
1070 {
1071 fprintf (stderr, "Skipping inclusion of %s in self.\n", file);
1072 return;
1073 }
1074 inf = fopen (file, "r");
1075 if (inf == NULL)
1076 {
1077 perror (file);
1078 return;
1079 }
1080
1081 find_entries (file, inf);
1082
1083 if (!CTAGS)
1084 {
1085 char *filename;
1086
1087 if (absolutefn (file))
1088 {
1089 /* file is an absolute filename. Canonicalise it. */
1090 filename = absolute_filename (file, cwd);
1091 }
1092 else
1093 {
1094 /* file is a filename relative to cwd. Make it relative
1095 to the directory of the tags file. */
1096 filename = relative_filename (file, tagfiledir);
1097 }
1098 fprintf (tagf, "\f\n%s,%d\n", filename, total_size_of_entries (head));
1099 free (filename);
1100 put_entries (head);
1101 free_tree (head);
1102 head = NULL;
1103 }
1104 }
1105
1106 /*
1107 * This routine sets up the boolean pseudo-functions which work
1108 * by setting boolean flags dependent upon the corresponding character
1109 * Every char which is NOT in that string is not a white char. Therefore,
1110 * all of the array "_wht" is set to FALSE, and then the elements
1111 * subscripted by the chars in "white" are set to TRUE. Thus "_wht"
1112 * of a char is TRUE if it is the string "white", else FALSE.
1113 */
1114 void
1115 init ()
1116 {
1117 register char *sp;
1118 register int i;
1119
1120 for (i = 0; i < 0177; i++)
1121 _wht[i] = _etk[i] = _itk[i] = _btk[i] = FALSE;
1122 for (sp = white; *sp; sp++)
1123 _wht[*sp] = TRUE;
1124 for (sp = endtk; *sp; sp++)
1125 _etk[*sp] = TRUE;
1126 for (sp = intk; *sp; sp++)
1127 _itk[*sp] = TRUE;
1128 for (sp = begtk; *sp; sp++)
1129 _btk[*sp] = TRUE;
1130 _wht[0] = _wht['\n'];
1131 _etk[0] = _etk['\n'];
1132 _btk[0] = _btk['\n'];
1133 _itk[0] = _itk['\n'];
1134 }
1135
1136 /*
1137 * This routine opens the specified file and calls the function
1138 * which finds the function and type definitions.
1139 */
1140 void
1141 find_entries (file, inf)
1142 char *file;
1143 FILE *inf;
1144 {
1145 char *cp;
1146 Lang_function *function;
1147 NODE *old_last_node;
1148 extern NODE *last_node;
1149
1150
1151 /* Memory leakage here: the memory block pointed by curfile is never
1152 released. The amount of memory leaked here is the sum of the
1153 lengths of the input file names. */
1154 curfile = savestr (file);
1155
1156 /* If user specified a language, use it. */
1157 function = lang_func;
1158 if (function != NULL)
1159 {
1160 function (inf);
1161 fclose (inf);
1162 return;
1163 }
1164
1165 cp = etags_strrchr (file, '.');
1166 if (cp != NULL)
1167 {
1168 cp += 1;
1169 function = get_language_from_suffix (cp);
1170 if (function != NULL)
1171 {
1172 function (inf);
1173 fclose (inf);
1174 return;
1175 }
1176 }
1177
1178 /* Look for sharp-bang as the first two characters. */
1179 if (readline_internal (&lb, inf) > 2
1180 && lb.buffer[0] == '#'
1181 && lb.buffer[1] == '!')
1182 {
1183 char *lp;
1184
1185 /* Set lp to point at the first char after the last slash in the
1186 line or, if no slashes, at the first nonblank. Then set cp to
1187 the first successive blank and terminate the string. */
1188 lp = etags_strrchr (lb.buffer+2, '/');
1189 if (lp != NULL)
1190 lp += 1;
1191 else
1192 for (lp = lb.buffer+2; *lp != '\0' && isspace (*lp); lp++)
1193 continue;
1194 for (cp = lp; *cp != '\0' && !isspace (*cp); cp++)
1195 continue;
1196 *cp = '\0';
1197
1198 if (strlen (lp) > 0)
1199 {
1200 function = get_language_from_interpreter (lp);
1201 if (function != NULL)
1202 {
1203 function (inf);
1204 fclose (inf);
1205 return;
1206 }
1207 }
1208 }
1209 rewind (inf);
1210
1211 /* Try Fortran. */
1212 old_last_node = last_node;
1213 Fortran_functions (inf);
1214
1215 /* No Fortran entries found. Try C. */
1216 if (old_last_node == last_node)
1217 {
1218 rewind (inf);
1219 default_C_entries (inf);
1220 }
1221 fclose (inf);
1222 return;
1223 }
1224 \f
1225 /* Record a tag. */
1226 void
1227 pfnote (name, is_func, linestart, linelen, lno, cno)
1228 char *name; /* tag name, or NULL if unnamed */
1229 logical is_func; /* tag is a function */
1230 char *linestart; /* start of the line where tag is */
1231 int linelen; /* length of the line where tag is */
1232 int lno; /* line number */
1233 long cno; /* character number */
1234 {
1235 register NODE *np;
1236
1237 if (CTAGS && name == NULL)
1238 return;
1239
1240 np = xnew (1, NODE);
1241
1242 /* If ctags mode, change name "main" to M<thisfilename>. */
1243 if (CTAGS && !cxref_style && streq (name, "main"))
1244 {
1245 register char *fp = etags_strrchr (curfile, '/');
1246 np->name = concat ("M", fp == 0 ? curfile : fp + 1, "");
1247 fp = etags_strrchr (np->name, '.');
1248 if (fp && fp[1] != '\0' && fp[2] == '\0')
1249 fp[0] = 0;
1250 }
1251 else
1252 np->name = name;
1253 np->been_warned = FALSE;
1254 np->file = curfile;
1255 np->is_func = is_func;
1256 np->lno = lno;
1257 /* Our char numbers are 0-base, because of C language tradition?
1258 ctags compatibility? old versions compatibility? I don't know.
1259 Anyway, since emacs's are 1-base we expect etags.el to take care
1260 of the difference. If we wanted to have 1-based numbers, we would
1261 uncomment the +1 below. */
1262 np->cno = cno /* + 1 */ ;
1263 np->left = np->right = NULL;
1264 if (CTAGS && !cxref_style)
1265 {
1266 if (strlen (linestart) < 50)
1267 np->pat = concat (linestart, "$", "");
1268 else
1269 np->pat = savenstr (linestart, 50);
1270 }
1271 else
1272 np->pat = savenstr (linestart, linelen);
1273
1274 add_node (np, &head);
1275 }
1276
1277 /*
1278 * free_tree ()
1279 * recurse on left children, iterate on right children.
1280 */
1281 void
1282 free_tree (node)
1283 register NODE *node;
1284 {
1285 while (node)
1286 {
1287 register NODE *node_right = node->right;
1288 free_tree (node->left);
1289 if (node->name != NULL)
1290 free (node->name);
1291 free (node->pat);
1292 free ((char *) node);
1293 node = node_right;
1294 }
1295 }
1296
1297 /*
1298 * add_node ()
1299 * Adds a node to the tree of nodes. In etags mode, we don't keep
1300 * it sorted; we just keep a linear list. In ctags mode, maintain
1301 * an ordered tree, with no attempt at balancing.
1302 *
1303 * add_node is the only function allowed to add nodes, so it can
1304 * maintain state.
1305 */
1306 NODE *last_node = NULL;
1307 void
1308 add_node (node, cur_node_p)
1309 NODE *node, **cur_node_p;
1310 {
1311 register int dif;
1312 register NODE *cur_node = *cur_node_p;
1313
1314 if (cur_node == NULL)
1315 {
1316 *cur_node_p = node;
1317 last_node = node;
1318 return;
1319 }
1320
1321 if (!CTAGS)
1322 {
1323 /* Etags Mode */
1324 if (last_node == NULL)
1325 fatal ("internal error in add_node", 0);
1326 last_node->right = node;
1327 last_node = node;
1328 }
1329 else
1330 {
1331 /* Ctags Mode */
1332 dif = strcmp (node->name, cur_node->name);
1333
1334 /*
1335 * If this tag name matches an existing one, then
1336 * do not add the node, but maybe print a warning.
1337 */
1338 if (!dif)
1339 {
1340 if (streq (node->file, cur_node->file))
1341 {
1342 if (!no_warnings)
1343 {
1344 fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n",
1345 node->file, lineno, node->name);
1346 fprintf (stderr, "Second entry ignored\n");
1347 }
1348 }
1349 else if (!cur_node->been_warned && !no_warnings)
1350 {
1351 fprintf
1352 (stderr,
1353 "Duplicate entry in files %s and %s: %s (Warning only)\n",
1354 node->file, cur_node->file, node->name);
1355 cur_node->been_warned = TRUE;
1356 }
1357 return;
1358 }
1359
1360 /* Actually add the node */
1361 add_node (node, dif < 0 ? &cur_node->left : &cur_node->right);
1362 }
1363 }
1364 \f
1365 void
1366 put_entries (node)
1367 register NODE *node;
1368 {
1369 register char *sp;
1370
1371 if (node == NULL)
1372 return;
1373
1374 /* Output subentries that precede this one */
1375 put_entries (node->left);
1376
1377 /* Output this entry */
1378
1379 if (!CTAGS)
1380 {
1381 if (node->name != NULL)
1382 fprintf (tagf, "%s\177%s\001%d,%d\n",
1383 node->pat, node->name, node->lno, node->cno);
1384 else
1385 fprintf (tagf, "%s\177%d,%d\n",
1386 node->pat, node->lno, node->cno);
1387 }
1388 else
1389 {
1390 if (node->name == NULL)
1391 error ("internal error: NULL name in ctags mode.", 0);
1392
1393 if (cxref_style)
1394 {
1395 if (vgrind_style)
1396 fprintf (stdout, "%s %s %d\n",
1397 node->name, node->file, (node->lno + 63) / 64);
1398 else
1399 fprintf (stdout, "%-16s %3d %-16s %s\n",
1400 node->name, node->lno, node->file, node->pat);
1401 }
1402 else
1403 {
1404 fprintf (tagf, "%s\t%s\t", node->name, node->file);
1405
1406 if (node->is_func)
1407 { /* a function */
1408 putc (searchar, tagf);
1409 putc ('^', tagf);
1410
1411 for (sp = node->pat; *sp; sp++)
1412 {
1413 if (*sp == '\\' || *sp == searchar)
1414 putc ('\\', tagf);
1415 putc (*sp, tagf);
1416 }
1417 putc (searchar, tagf);
1418 }
1419 else
1420 { /* a typedef; text pattern inadequate */
1421 fprintf (tagf, "%d", node->lno);
1422 }
1423 putc ('\n', tagf);
1424 }
1425 }
1426
1427 /* Output subentries that follow this one */
1428 put_entries (node->right);
1429 }
1430
1431 /* Length of a number's decimal representation. */
1432 int
1433 number_len (num)
1434 long num;
1435 {
1436 int len = 0;
1437 if (!num)
1438 return 1;
1439 for (; num; num /= 10)
1440 ++len;
1441 return len;
1442 }
1443
1444 /*
1445 * Return total number of characters that put_entries will output for
1446 * the nodes in the subtree of the specified node. Works only if
1447 * we are not ctags, but called only in that case. This count
1448 * is irrelevant with the new tags.el, but is still supplied for
1449 * backward compatibility.
1450 */
1451 int
1452 total_size_of_entries (node)
1453 register NODE *node;
1454 {
1455 register int total;
1456
1457 if (node == NULL)
1458 return 0;
1459
1460 total = 0;
1461 for (; node; node = node->right)
1462 {
1463 /* Count left subentries. */
1464 total += total_size_of_entries (node->left);
1465
1466 /* Count this entry */
1467 total += strlen (node->pat) + 1;
1468 total += number_len ((long) node->lno) + 1 + number_len (node->cno) + 1;
1469 if (node->name != NULL)
1470 total += 1 + strlen (node->name); /* \001name */
1471 }
1472
1473 return total;
1474 }
1475 \f
1476 /*
1477 * The C symbol tables.
1478 */
1479 enum sym_type
1480 {
1481 st_none, st_C_objprot, st_C_objimpl, st_C_objend, st_C_gnumacro,
1482 st_C_struct, st_C_enum, st_C_define, st_C_typedef, st_C_typespec
1483 };
1484
1485 /* Feed stuff between (but not including) %[ and %] lines to:
1486 gperf -c -k1,3 -o -p -r -t
1487 %[
1488 struct C_stab_entry { char *name; int c_ext; enum sym_type type; }
1489 %%
1490 @interface, 0, st_C_objprot
1491 @protocol, 0, st_C_objprot
1492 @implementation,0, st_C_objimpl
1493 @end, 0, st_C_objend
1494 class, C_PLPL, st_C_struct
1495 domain, C_STAR, st_C_struct
1496 union, 0, st_C_struct
1497 struct, 0, st_C_struct
1498 enum, 0, st_C_enum
1499 typedef, 0, st_C_typedef
1500 define, 0, st_C_define
1501 long, 0, st_C_typespec
1502 short, 0, st_C_typespec
1503 int, 0, st_C_typespec
1504 char, 0, st_C_typespec
1505 float, 0, st_C_typespec
1506 double, 0, st_C_typespec
1507 signed, 0, st_C_typespec
1508 unsigned, 0, st_C_typespec
1509 auto, 0, st_C_typespec
1510 void, 0, st_C_typespec
1511 extern, 0, st_C_typespec
1512 static, 0, st_C_typespec
1513 const, 0, st_C_typespec
1514 volatile, 0, st_C_typespec
1515 # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach).
1516 DEFUN, 0, st_C_gnumacro
1517 SYSCALL, 0, st_C_gnumacro
1518 ENTRY, 0, st_C_gnumacro
1519 PSEUDO, 0, st_C_gnumacro
1520 # These are defined inside C functions, so currently they are not met.
1521 # EXFUN used in glibc, DEFVAR_* in emacs.
1522 #EXFUN, 0, st_C_gnumacro
1523 #DEFVAR_, 0, st_C_gnumacro
1524 %]
1525 and replace lines between %< and %> with its output. */
1526 /*%<*/
1527 /* C code produced by gperf version 1.8.1 (K&R C version) */
1528 /* Command-line: gperf -c -k1,3 -o -p -r -t */
1529
1530
1531 struct C_stab_entry { char *name; int c_ext; enum sym_type type; };
1532
1533 #define MIN_WORD_LENGTH 3
1534 #define MAX_WORD_LENGTH 15
1535 #define MIN_HASH_VALUE 7
1536 #define MAX_HASH_VALUE 63
1537 /*
1538 29 keywords
1539 57 is the maximum key range
1540 */
1541
1542 static int
1543 hash (str, len)
1544 register char *str;
1545 register int len;
1546 {
1547 static unsigned char hash_table[] =
1548 {
1549 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1550 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1551 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1552 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1553 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1554 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1555 63, 63, 63, 63, 17, 63, 63, 63, 4, 14,
1556 4, 63, 63, 63, 63, 63, 63, 63, 63, 63,
1557 8, 63, 63, 0, 23, 63, 63, 63, 63, 63,
1558 63, 63, 63, 63, 63, 63, 63, 28, 63, 28,
1559 10, 31, 27, 18, 63, 6, 63, 63, 26, 1,
1560 11, 2, 29, 63, 29, 16, 26, 13, 15, 63,
1561 63, 63, 63, 63, 63, 63, 63, 63,
1562 };
1563 return len + hash_table[str[2]] + hash_table[str[0]];
1564 }
1565
1566 struct C_stab_entry *
1567 in_word_set (str, len)
1568 register char *str;
1569 register int len;
1570 {
1571
1572 static struct C_stab_entry wordlist[] =
1573 {
1574 {"",}, {"",}, {"",}, {"",}, {"",}, {"",}, {"",},
1575 {"SYSCALL", 0, st_C_gnumacro},
1576 {"",}, {"",}, {"",}, {"",}, {"",},
1577 {"DEFUN", 0, st_C_gnumacro},
1578 {"",}, {"",}, {"",},
1579 {"domain", C_STAR, st_C_struct},
1580 {"",}, {"",}, {"",}, {"",}, {"",},
1581 {"short", 0, st_C_typespec},
1582 {"union", 0, st_C_struct},
1583 {"void", 0, st_C_typespec},
1584 {"",}, {"",},
1585 {"PSEUDO", 0, st_C_gnumacro},
1586 {"double", 0, st_C_typespec},
1587 {"",}, {"",},
1588 {"@end", 0, st_C_objend},
1589 {"@implementation", 0, st_C_objimpl},
1590 {"float", 0, st_C_typespec},
1591 {"int", 0, st_C_typespec},
1592 {"",},
1593 {"unsigned", 0, st_C_typespec},
1594 {"@interface", 0, st_C_objprot},
1595 {"",},
1596 {"signed", 0, st_C_typespec},
1597 {"long", 0, st_C_typespec},
1598 {"ENTRY", 0, st_C_gnumacro},
1599 {"define", 0, st_C_define},
1600 {"const", 0, st_C_typespec},
1601 {"",}, {"",}, {"",},
1602 {"enum", 0, st_C_enum},
1603 {"volatile", 0, st_C_typespec},
1604 {"static", 0, st_C_typespec},
1605 {"struct", 0, st_C_struct},
1606 {"",}, {"",}, {"",},
1607 {"@protocol", 0, st_C_objprot},
1608 {"",}, {"",},
1609 {"auto", 0, st_C_typespec},
1610 {"",},
1611 {"char", 0, st_C_typespec},
1612 {"class", C_PLPL, st_C_struct},
1613 {"typedef", 0, st_C_typedef},
1614 {"extern", 0, st_C_typespec},
1615 };
1616
1617 if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
1618 {
1619 register int key = hash (str, len);
1620
1621 if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)
1622 {
1623 register char *s = wordlist[key].name;
1624
1625 if (*s == *str && !strncmp (str + 1, s + 1, len - 1))
1626 return &wordlist[key];
1627 }
1628 }
1629 return 0;
1630 }
1631 /*%>*/
1632
1633 enum sym_type
1634 C_symtype(str, len, c_ext)
1635 char *str;
1636 int len;
1637 int c_ext;
1638 {
1639 register struct C_stab_entry *se = in_word_set(str, len);
1640
1641 if (se == NULL || (se->c_ext && !(c_ext & se->c_ext)))
1642 return st_none;
1643 return se->type;
1644 }
1645 \f
1646 /*
1647 * C functions are recognized using a simple finite automaton.
1648 * funcdef is its state variable.
1649 */
1650 enum
1651 {
1652 fnone, /* nothing seen */
1653 ftagseen, /* function-like tag seen */
1654 fstartlist, /* just after open parenthesis */
1655 finlist, /* in parameter list */
1656 flistseen, /* after parameter list */
1657 fignore /* before open brace */
1658 } funcdef;
1659
1660
1661 /*
1662 * typedefs are recognized using a simple finite automaton.
1663 * typdef is its state variable.
1664 */
1665 enum
1666 {
1667 tnone, /* nothing seen */
1668 ttypedseen, /* typedef keyword seen */
1669 tinbody, /* inside typedef body */
1670 tend, /* just before typedef tag */
1671 tignore /* junk after typedef tag */
1672 } typdef;
1673
1674
1675 /*
1676 * struct-like structures (enum, struct and union) are recognized
1677 * using another simple finite automaton. `structdef' is its state
1678 * variable.
1679 */
1680 enum
1681 {
1682 snone, /* nothing seen yet */
1683 skeyseen, /* struct-like keyword seen */
1684 stagseen, /* struct-like tag seen */
1685 scolonseen, /* colon seen after struct-like tag */
1686 sinbody /* in struct body: recognize member func defs*/
1687 } structdef;
1688
1689 /*
1690 * When structdef is stagseen, scolonseen, or sinbody, structtag is the
1691 * struct tag, and structtype is the type of the preceding struct-like
1692 * keyword.
1693 */
1694 char *structtag = "<uninited>";
1695 enum sym_type structtype;
1696
1697 /*
1698 * When objdef is different from onone, objtag is the name of the class.
1699 */
1700 char *objtag = "<uninited>";
1701
1702 /*
1703 * Yet another little state machine to deal with preprocessor lines.
1704 */
1705 enum
1706 {
1707 dnone, /* nothing seen */
1708 dsharpseen, /* '#' seen as first char on line */
1709 ddefineseen, /* '#' and 'define' seen */
1710 dignorerest /* ignore rest of line */
1711 } definedef;
1712
1713 /*
1714 * State machine for Objective C protocols and implementations.
1715 */
1716 enum
1717 {
1718 onone, /* nothing seen */
1719 oprotocol, /* @interface or @protocol seen */
1720 oimplementation, /* @implementations seen */
1721 otagseen, /* class name seen */
1722 oparenseen, /* parenthesis before category seen */
1723 ocatseen, /* category name seen */
1724 oinbody, /* in @implementation body */
1725 omethodsign, /* in @implementation body, after +/- */
1726 omethodtag, /* after method name */
1727 omethodcolon, /* after method colon */
1728 omethodparm, /* after method parameter */
1729 oignore /* wait for @end */
1730 } objdef;
1731
1732 /*
1733 * Set this to TRUE, and the next token considered is called a function.
1734 * Used only for GNU emacs's function-defining macros.
1735 */
1736 logical next_token_is_func;
1737
1738 /*
1739 * TRUE in the rules part of a yacc file, FALSE outside (parse as C).
1740 */
1741 logical yacc_rules;
1742
1743 /*
1744 * methodlen is the length of the method name stored in token_name.
1745 */
1746 int methodlen;
1747
1748 /*
1749 * consider_token ()
1750 * checks to see if the current token is at the start of a
1751 * function, or corresponds to a typedef, or is a struct/union/enum
1752 * tag.
1753 *
1754 * *IS_FUNC gets TRUE iff the token is a function or macro with args.
1755 * C_EXT is which language we are looking at.
1756 *
1757 * In the future we will need some way to adjust where the end of
1758 * the token is; for instance, implementing the C++ keyword
1759 * `operator' properly will adjust the end of the token to be after
1760 * whatever follows `operator'.
1761 *
1762 * Globals
1763 * funcdef IN OUT
1764 * structdef IN OUT
1765 * definedef IN OUT
1766 * typdef IN OUT
1767 * objdef IN OUT
1768 * next_token_is_func IN OUT
1769 */
1770
1771 logical
1772 consider_token (str, len, c, c_ext, cblev, parlev, is_func)
1773 register char *str; /* IN: token pointer */
1774 register int len; /* IN: token length */
1775 register char c; /* IN: first char after the token */
1776 int c_ext; /* IN: C extensions mask */
1777 int cblev; /* IN: curly brace level */
1778 int parlev; /* IN: parenthesis level */
1779 logical *is_func; /* OUT: function found */
1780 {
1781 enum sym_type toktype = C_symtype (str, len, c_ext);
1782
1783 /*
1784 * Advance the definedef state machine.
1785 */
1786 switch (definedef)
1787 {
1788 case dnone:
1789 /* We're not on a preprocessor line. */
1790 break;
1791 case dsharpseen:
1792 if (toktype == st_C_define)
1793 {
1794 definedef = ddefineseen;
1795 }
1796 else
1797 {
1798 definedef = dignorerest;
1799 }
1800 return FALSE;
1801 case ddefineseen:
1802 /*
1803 * Make a tag for any macro, unless it is a constant
1804 * and constantypedefs is FALSE.
1805 */
1806 definedef = dignorerest;
1807 *is_func = (c == '(');
1808 if (!*is_func && !constantypedefs)
1809 return FALSE;
1810 else
1811 return TRUE;
1812 case dignorerest:
1813 return FALSE;
1814 default:
1815 error ("internal error: definedef value.", 0);
1816 }
1817
1818 /*
1819 * Now typedefs
1820 */
1821 switch (typdef)
1822 {
1823 case tnone:
1824 if (toktype == st_C_typedef)
1825 {
1826 if (typedefs)
1827 typdef = ttypedseen;
1828 funcdef = fnone;
1829 return FALSE;
1830 }
1831 break;
1832 case ttypedseen:
1833 switch (toktype)
1834 {
1835 case st_none:
1836 case st_C_typespec:
1837 typdef = tend;
1838 break;
1839 case st_C_struct:
1840 case st_C_enum:
1841 break;
1842 }
1843 /* Do not return here, so the structdef stuff has a chance. */
1844 break;
1845 case tend:
1846 switch (toktype)
1847 {
1848 case st_C_typespec:
1849 case st_C_struct:
1850 case st_C_enum:
1851 return FALSE;
1852 }
1853 return TRUE;
1854 }
1855
1856 /*
1857 * This structdef business is currently only invoked when cblev==0.
1858 * It should be recursively invoked whatever the curly brace level,
1859 * and a stack of states kept, to allow for definitions of structs
1860 * within structs.
1861 *
1862 * This structdef business is NOT invoked when we are ctags and the
1863 * file is plain C. This is because a struct tag may have the same
1864 * name as another tag, and this loses with ctags.
1865 *
1866 * This if statement deals with the typdef state machine as
1867 * follows: if typdef==ttypedseen and token is struct/union/class/enum,
1868 * return FALSE. All the other code here is for the structdef
1869 * state machine.
1870 */
1871 switch (toktype)
1872 {
1873 case st_C_struct:
1874 case st_C_enum:
1875 if (typdef == ttypedseen
1876 || (typedefs_and_cplusplus && cblev == 0 && structdef == snone))
1877 {
1878 structdef = skeyseen;
1879 structtype = toktype;
1880 }
1881 return FALSE;
1882 }
1883 if (structdef == skeyseen)
1884 {
1885 /* Save the tag for struct/union/class, for functions that may be
1886 defined inside. */
1887 if (structtype == st_C_struct)
1888 structtag = savenstr (str, len);
1889 else
1890 structtag = "<enum>";
1891 structdef = stagseen;
1892 return TRUE;
1893 }
1894
1895 /* Avoid entering funcdef stuff if typdef is going on. */
1896 if (typdef != tnone)
1897 {
1898 definedef = dnone;
1899 return FALSE;
1900 }
1901
1902 /* Detect GNU macros. */
1903 if (definedef == dnone && toktype == st_C_gnumacro)
1904 {
1905 next_token_is_func = TRUE;
1906 return FALSE;
1907 }
1908 if (next_token_is_func)
1909 {
1910 next_token_is_func = FALSE;
1911 funcdef = fignore;
1912 *is_func = TRUE;
1913 return TRUE;
1914 }
1915
1916 /*
1917 * Detecting Objective C constructs.
1918 */
1919 switch (objdef)
1920 {
1921 case onone:
1922 switch (toktype)
1923 {
1924 case st_C_objprot:
1925 objdef = oprotocol;
1926 return FALSE;
1927 case st_C_objimpl:
1928 objdef = oimplementation;
1929 return FALSE;
1930 }
1931 break;
1932 case oimplementation:
1933 /* Save the class tag for functions that may be defined inside. */
1934 objtag = savenstr (str, len);
1935 objdef = oinbody;
1936 return FALSE;
1937 case oprotocol:
1938 /* Save the class tag for categories. */
1939 objtag = savenstr (str, len);
1940 objdef = otagseen;
1941 *is_func = TRUE;
1942 return TRUE;
1943 case oparenseen:
1944 objdef = ocatseen;
1945 *is_func = TRUE;
1946 return TRUE;
1947 case oinbody:
1948 break;
1949 case omethodsign:
1950 if (parlev == 0)
1951 {
1952 objdef = omethodtag;
1953 methodlen = len;
1954 GROW_LINEBUFFER (token_name, methodlen+1);
1955 strncpy (token_name.buffer, str, len);
1956 token_name.buffer[methodlen] = '\0';
1957 return TRUE;
1958 }
1959 return FALSE;
1960 case omethodcolon:
1961 if (parlev == 0)
1962 objdef = omethodparm;
1963 return FALSE;
1964 case omethodparm:
1965 if (parlev == 0)
1966 {
1967 objdef = omethodtag;
1968 methodlen += len;
1969 GROW_LINEBUFFER (token_name, methodlen+1);
1970 strncat (token_name.buffer, str, len);
1971 return TRUE;
1972 }
1973 return FALSE;
1974 case oignore:
1975 if (toktype == st_C_objend)
1976 {
1977 /* Memory leakage here: the string pointed by objtag is
1978 never released, because many tests would be needed to
1979 avoid breaking on incorrect input code. The amount of
1980 memory leaked here is the sum of the lengths of the
1981 class tags.
1982 free (objtag); */
1983 objdef = onone;
1984 }
1985 return FALSE;
1986 }
1987
1988 /* A function? */
1989 switch (toktype)
1990 {
1991 case st_C_typespec:
1992 if (funcdef != finlist && funcdef != fignore)
1993 funcdef = fnone; /* should be useless */
1994 return FALSE;
1995 default:
1996 if (funcdef == fnone)
1997 {
1998 funcdef = ftagseen;
1999 *is_func = TRUE;
2000 return TRUE;
2001 }
2002 }
2003
2004 return FALSE;
2005 }
2006
2007 /*
2008 * C_entries ()
2009 * This routine finds functions, typedefs, #define's and
2010 * struct/union/enum definitions in C syntax and adds them
2011 * to the list.
2012 */
2013 typedef struct
2014 {
2015 logical valid;
2016 char *str;
2017 logical named;
2018 int linelen;
2019 int lineno;
2020 long linepos;
2021 char *buffer;
2022 } TOKEN;
2023
2024 #define current_lb_is_new (newndx == curndx)
2025 #define switch_line_buffers() (curndx = 1 - curndx)
2026
2027 #define curlb (lbs[curndx].lb)
2028 #define othlb (lbs[1-curndx].lb)
2029 #define newlb (lbs[newndx].lb)
2030 #define curlinepos (lbs[curndx].linepos)
2031 #define othlinepos (lbs[1-curndx].linepos)
2032 #define newlinepos (lbs[newndx].linepos)
2033
2034 #define CNL_SAVE_DEFINEDEF \
2035 do { \
2036 curlinepos = charno; \
2037 lineno++; \
2038 charno += readline (&curlb, inf); \
2039 lp = curlb.buffer; \
2040 quotednl = FALSE; \
2041 newndx = curndx; \
2042 } while (0)
2043
2044 #define CNL \
2045 do { \
2046 CNL_SAVE_DEFINEDEF; \
2047 if (savetok.valid) \
2048 { \
2049 tok = savetok; \
2050 savetok.valid = FALSE; \
2051 } \
2052 definedef = dnone; \
2053 } while (0)
2054
2055 /* Ideally this macro should never be called wihen tok.valid is FALSE,
2056 but this would mean that the state machines always guess right. */
2057 #define make_tag(isfun) do \
2058 if (tok.valid) { \
2059 char *name = NULL; \
2060 if (CTAGS || tok.named) \
2061 name = savestr (token_name.buffer); \
2062 pfnote (name, isfun, tok.buffer, tok.linelen, tok.lineno, tok.linepos); \
2063 tok.valid = FALSE; \
2064 } while (0)
2065
2066 void
2067 C_entries (c_ext, inf)
2068 int c_ext; /* extension of C */
2069 FILE *inf; /* input file */
2070 {
2071 register char c; /* latest char read; '\0' for end of line */
2072 register char *lp; /* pointer one beyond the character `c' */
2073 int curndx, newndx; /* indices for current and new lb */
2074 TOKEN tok; /* latest token read */
2075 register int tokoff; /* offset in line of start of current token */
2076 register int toklen; /* length of current token */
2077 int cblev; /* current curly brace level */
2078 int parlev; /* current parenthesis level */
2079 logical incomm, inquote, inchar, quotednl, midtoken;
2080 logical cplpl;
2081 TOKEN savetok; /* token saved during preprocessor handling */
2082
2083
2084 curndx = newndx = 0;
2085 lineno = 0;
2086 charno = 0;
2087 lp = curlb.buffer;
2088 *lp = 0;
2089
2090 funcdef = fnone; typdef = tnone; structdef = snone;
2091 definedef = dnone; objdef = onone;
2092 next_token_is_func = yacc_rules = FALSE;
2093 midtoken = inquote = inchar = incomm = quotednl = FALSE;
2094 tok.valid = savetok.valid = FALSE;
2095 cblev = 0;
2096 parlev = 0;
2097 cplpl = c_ext & C_PLPL;
2098
2099 while (!feof (inf))
2100 {
2101 c = *lp++;
2102 if (c == '\\')
2103 {
2104 /* If we're at the end of the line, the next character is a
2105 '\0'; don't skip it, because it's the thing that tells us
2106 to read the next line. */
2107 if (*lp == '\0')
2108 {
2109 quotednl = TRUE;
2110 continue;
2111 }
2112 lp++;
2113 c = ' ';
2114 }
2115 else if (incomm)
2116 {
2117 switch (c)
2118 {
2119 case '*':
2120 if (*lp == '/')
2121 {
2122 c = *lp++;
2123 incomm = FALSE;
2124 }
2125 break;
2126 case '\0':
2127 /* Newlines inside comments do not end macro definitions in
2128 traditional cpp. */
2129 CNL_SAVE_DEFINEDEF;
2130 break;
2131 }
2132 continue;
2133 }
2134 else if (inquote)
2135 {
2136 switch (c)
2137 {
2138 case '"':
2139 inquote = FALSE;
2140 break;
2141 case '\0':
2142 /* Newlines inside strings do not end macro definitions
2143 in traditional cpp, even though compilers don't
2144 usually accept them. */
2145 CNL_SAVE_DEFINEDEF;
2146 break;
2147 }
2148 continue;
2149 }
2150 else if (inchar)
2151 {
2152 switch (c)
2153 {
2154 case '\0':
2155 /* Hmmm, something went wrong. */
2156 CNL;
2157 /* FALLTHRU */
2158 case '\'':
2159 inchar = FALSE;
2160 break;
2161 }
2162 continue;
2163 }
2164 else
2165 switch (c)
2166 {
2167 case '"':
2168 inquote = TRUE;
2169 if (funcdef != finlist && funcdef != fignore)
2170 funcdef = fnone;
2171 continue;
2172 case '\'':
2173 inchar = TRUE;
2174 if (funcdef != finlist && funcdef != fignore)
2175 funcdef = fnone;
2176 continue;
2177 case '/':
2178 if (*lp == '*')
2179 {
2180 lp++;
2181 incomm = TRUE;
2182 continue;
2183 }
2184 else if (/* cplpl && */ *lp == '/')
2185 {
2186 c = '\0';
2187 break;
2188 }
2189 else
2190 break;
2191 case '%':
2192 if ((c_ext & YACC) && *lp == '%')
2193 {
2194 /* entering or exiting rules section in yacc file */
2195 lp++;
2196 definedef = dnone; funcdef = fnone;
2197 typdef = tnone; structdef = snone;
2198 next_token_is_func = FALSE;
2199 midtoken = inquote = inchar = incomm = quotednl = FALSE;
2200 cblev = 0;
2201 yacc_rules = !yacc_rules;
2202 continue;
2203 }
2204 else
2205 break;
2206 case '#':
2207 if (definedef == dnone)
2208 {
2209 char *cp;
2210 logical cpptoken = TRUE;
2211
2212 /* Look back on this line. If all blanks, or nonblanks
2213 followed by an end of comment, this is a preprocessor
2214 token. */
2215 for (cp = newlb.buffer; cp < lp-1; cp++)
2216 if (!iswhite (*cp))
2217 {
2218 if (*cp == '*' && *(cp+1) == '/')
2219 {
2220 cp++;
2221 cpptoken = TRUE;
2222 }
2223 else
2224 cpptoken = FALSE;
2225 }
2226 if (cpptoken)
2227 definedef = dsharpseen;
2228 } /* if (definedef == dnone) */
2229
2230 continue;
2231 } /* switch (c) */
2232
2233
2234 /* Consider token only if some complicated conditions are satisfied. */
2235 if ((definedef != dnone
2236 || (cblev == 0 && structdef != scolonseen)
2237 || (cblev == 1 && cplpl && structdef == sinbody))
2238 && typdef != tignore
2239 && definedef != dignorerest
2240 && funcdef != finlist)
2241 {
2242 if (midtoken)
2243 {
2244 if (endtoken (c))
2245 {
2246 if (c == ':' && cplpl && *lp == ':' && begtoken(*(lp + 1)))
2247 {
2248 /*
2249 * This handles :: in the middle, but not at the
2250 * beginning of an identifier.
2251 */
2252 lp += 2;
2253 toklen += 3;
2254 }
2255 else
2256 {
2257 logical is_func = FALSE;
2258
2259 if (yacc_rules
2260 || consider_token (newlb.buffer + tokoff, toklen, c,
2261 c_ext, cblev, parlev, &is_func))
2262 {
2263 if (structdef == sinbody
2264 && definedef == dnone
2265 && is_func)
2266 /* function defined in C++ class body */
2267 {
2268 GROW_LINEBUFFER (token_name,
2269 strlen(structtag)+2+toklen+1);
2270 strcpy (token_name.buffer, structtag);
2271 strcat (token_name.buffer, "::");
2272 strncat (token_name.buffer,
2273 newlb.buffer+tokoff, toklen);
2274 tok.named = TRUE;
2275 }
2276 else if (objdef == ocatseen)
2277 /* Objective C category */
2278 {
2279 GROW_LINEBUFFER (token_name,
2280 strlen(objtag)+2+toklen+1);
2281 strcpy (token_name.buffer, objtag);
2282 strcat (token_name.buffer, "(");
2283 strncat (token_name.buffer,
2284 newlb.buffer+tokoff, toklen);
2285 strcat (token_name.buffer, ")");
2286 tok.named = TRUE;
2287 }
2288 else if (objdef == omethodtag
2289 || objdef == omethodparm)
2290 /* Objective C method */
2291 {
2292 tok.named = TRUE;
2293 }
2294 else
2295 {
2296 GROW_LINEBUFFER (token_name, toklen+1);
2297 strncpy (token_name.buffer,
2298 newlb.buffer+tokoff, toklen);
2299 token_name.buffer[toklen] = '\0';
2300 if (structdef == stagseen
2301 || typdef == tend
2302 || (is_func
2303 && definedef == dignorerest)) /* macro */
2304 tok.named = TRUE;
2305 else
2306 tok.named = FALSE;
2307 }
2308 tok.lineno = lineno;
2309 tok.linelen = tokoff + toklen + 1;
2310 tok.buffer = newlb.buffer;
2311 tok.linepos = newlinepos;
2312 tok.valid = TRUE;
2313
2314 if (definedef == dnone
2315 && (funcdef == ftagseen
2316 || structdef == stagseen
2317 || typdef == tend
2318 || objdef != onone))
2319 {
2320 if (current_lb_is_new)
2321 switch_line_buffers ();
2322 }
2323 else
2324 make_tag (is_func);
2325 }
2326 midtoken = FALSE;
2327 }
2328 } /* if (endtoken (c)) */
2329 else if (intoken (c))
2330 {
2331 toklen++;
2332 continue;
2333 }
2334 } /* if (midtoken) */
2335 else if (begtoken (c))
2336 {
2337 switch (definedef)
2338 {
2339 case dnone:
2340 switch (funcdef)
2341 {
2342 case fstartlist:
2343 funcdef = finlist;
2344 continue;
2345 case flistseen:
2346 make_tag (TRUE);
2347 funcdef = fignore;
2348 break;
2349 case ftagseen:
2350 funcdef = fnone;
2351 break;
2352 }
2353 if (structdef == stagseen)
2354 structdef = snone;
2355 break;
2356 case dsharpseen:
2357 savetok = tok;
2358 }
2359 if (!yacc_rules || lp == newlb.buffer + 1)
2360 {
2361 tokoff = lp - 1 - newlb.buffer;
2362 toklen = 1;
2363 midtoken = TRUE;
2364 }
2365 continue;
2366 } /* if (begtoken) */
2367 } /* if must look at token */
2368
2369
2370 /* Detect end of line, colon, comma, semicolon and various braces
2371 after having handled a token.*/
2372 switch (c)
2373 {
2374 case ':':
2375 if (definedef != dnone)
2376 break;
2377 switch (objdef)
2378 {
2379 case otagseen:
2380 objdef = oignore;
2381 make_tag (TRUE);
2382 break;
2383 case omethodtag:
2384 case omethodparm:
2385 objdef = omethodcolon;
2386 methodlen += 1;
2387 GROW_LINEBUFFER (token_name, methodlen+1);
2388 strcat (token_name.buffer, ":");
2389 break;
2390 }
2391 if (structdef == stagseen)
2392 structdef = scolonseen;
2393 else
2394 switch (funcdef)
2395 {
2396 case ftagseen:
2397 if (yacc_rules)
2398 {
2399 make_tag (FALSE);
2400 funcdef = fignore;
2401 }
2402 break;
2403 case fstartlist:
2404 funcdef = fnone;
2405 break;
2406 }
2407 break;
2408 case ';':
2409 if (definedef != dnone)
2410 break;
2411 if (cblev == 0)
2412 switch (typdef)
2413 {
2414 case tend:
2415 make_tag (FALSE);
2416 /* FALLTHRU */
2417 default:
2418 typdef = tnone;
2419 }
2420 if (funcdef != fignore)
2421 {
2422 funcdef = fnone;
2423 /* The following instruction invalidates the token.
2424 Probably the token should be invalidated in all
2425 other cases where some state machine is reset. */
2426 tok.valid = FALSE;
2427 }
2428 if (structdef == stagseen)
2429 structdef = snone;
2430 break;
2431 case ',':
2432 if (definedef != dnone)
2433 break;
2434 switch (objdef)
2435 {
2436 case omethodtag:
2437 case omethodparm:
2438 make_tag (TRUE);
2439 objdef = oinbody;
2440 break;
2441 }
2442 if (funcdef != finlist && funcdef != fignore)
2443 funcdef = fnone;
2444 if (structdef == stagseen)
2445 structdef = snone;
2446 break;
2447 case '[':
2448 if (definedef != dnone)
2449 break;
2450 if (cblev == 0 && typdef == tend)
2451 {
2452 typdef = tignore;
2453 make_tag (FALSE);
2454 break;
2455 }
2456 if (funcdef != finlist && funcdef != fignore)
2457 funcdef = fnone;
2458 if (structdef == stagseen)
2459 structdef = snone;
2460 break;
2461 case '(':
2462 if (definedef != dnone)
2463 break;
2464 if (objdef == otagseen && parlev == 0)
2465 objdef = oparenseen;
2466 switch (funcdef)
2467 {
2468 case fnone:
2469 switch (typdef)
2470 {
2471 case ttypedseen:
2472 case tend:
2473 /* Make sure that the next char is not a '*'.
2474 This handles constructs like:
2475 typedef void OperatorFun (int fun); */
2476 if (*lp != '*')
2477 {
2478 typdef = tignore;
2479 make_tag (FALSE);
2480 }
2481 break;
2482 } /* switch (typdef) */
2483 break;
2484 case ftagseen:
2485 funcdef = fstartlist;
2486 break;
2487 case flistseen:
2488 funcdef = finlist;
2489 break;
2490 }
2491 parlev++;
2492 break;
2493 case ')':
2494 if (definedef != dnone)
2495 break;
2496 if (objdef == ocatseen && parlev == 1)
2497 {
2498 make_tag (TRUE);
2499 objdef = oignore;
2500 }
2501 if (--parlev == 0)
2502 {
2503 switch (funcdef)
2504 {
2505 case fstartlist:
2506 case finlist:
2507 funcdef = flistseen;
2508 break;
2509 }
2510 if (cblev == 0 && typdef == tend)
2511 {
2512 typdef = tignore;
2513 make_tag (FALSE);
2514 }
2515 }
2516 else if (parlev < 0) /* can happen due to ill-conceived #if's. */
2517 parlev = 0;
2518 break;
2519 case '{':
2520 if (definedef != dnone)
2521 break;
2522 if (typdef == ttypedseen)
2523 typdef = tinbody;
2524 switch (structdef)
2525 {
2526 case skeyseen: /* unnamed struct */
2527 structtag = "_anonymous_";
2528 structdef = sinbody;
2529 break;
2530 case stagseen:
2531 case scolonseen: /* named struct */
2532 structdef = sinbody;
2533 make_tag (FALSE);
2534 break;
2535 }
2536 switch (funcdef)
2537 {
2538 case flistseen:
2539 make_tag (TRUE);
2540 /* FALLTHRU */
2541 case fignore:
2542 funcdef = fnone;
2543 break;
2544 case fnone:
2545 switch (objdef)
2546 {
2547 case otagseen:
2548 make_tag (TRUE);
2549 objdef = oignore;
2550 break;
2551 case omethodtag:
2552 case omethodparm:
2553 make_tag (TRUE);
2554 objdef = oinbody;
2555 break;
2556 default:
2557 /* Neutralize `extern "C" {' grot and look inside structs. */
2558 if (cblev == 0 && structdef == snone && typdef == tnone)
2559 cblev = -1;
2560 }
2561 }
2562 cblev++;
2563 break;
2564 case '*':
2565 if (definedef != dnone)
2566 break;
2567 if (funcdef == fstartlist)
2568 funcdef = fnone; /* avoid tagging `foo' in `foo (*bar()) ()' */
2569 break;
2570 case '}':
2571 if (definedef != dnone)
2572 break;
2573 if (!noindentypedefs && lp == newlb.buffer + 1)
2574 {
2575 cblev = 0; /* reset curly brace level if first column */
2576 parlev = 0; /* also reset paren level, just in case... */
2577 }
2578 else if (cblev > 0)
2579 cblev--;
2580 if (cblev == 0)
2581 {
2582 if (typdef == tinbody)
2583 typdef = tend;
2584 /* Memory leakage here: the string pointed by structtag is
2585 never released, because I fear to miss something and
2586 break things while freeing the area. The amount of
2587 memory leaked here is the sum of the lengths of the
2588 struct tags.
2589 if (structdef == sinbody)
2590 free (structtag); */
2591
2592 structdef = snone;
2593 structtag = "<error>";
2594 }
2595 break;
2596 case '+':
2597 case '-':
2598 if (objdef == oinbody && cblev == 0)
2599 {
2600 objdef = omethodsign;
2601 break;
2602 }
2603 /* FALLTHRU */
2604 case '=': case '#': case '~': case '&': case '%': case '/':
2605 case '|': case '^': case '!': case '<': case '>': case '.': case '?':
2606 if (definedef != dnone)
2607 break;
2608 /* These surely cannot follow a function tag. */
2609 if (funcdef != finlist && funcdef != fignore)
2610 funcdef = fnone;
2611 break;
2612 case '\0':
2613 if (objdef == otagseen)
2614 {
2615 make_tag (TRUE);
2616 objdef = oignore;
2617 }
2618 /* If a macro spans multiple lines don't reset its state. */
2619 if (quotednl)
2620 CNL_SAVE_DEFINEDEF;
2621 else
2622 CNL;
2623 break;
2624 } /* switch (c) */
2625
2626 } /* while not eof */
2627 }
2628
2629 /*
2630 * Process either a C++ file or a C file depending on the setting
2631 * of a global flag.
2632 */
2633 void
2634 default_C_entries (inf)
2635 FILE *inf;
2636 {
2637 C_entries (cplusplus ? C_PLPL : 0, inf);
2638 }
2639
2640 /* Always do plain ANSI C. */
2641 void
2642 plain_C_entries (inf)
2643 FILE *inf;
2644 {
2645 C_entries (0, inf);
2646 }
2647
2648 /* Always do C++. */
2649 void
2650 Cplusplus_entries (inf)
2651 FILE *inf;
2652 {
2653 C_entries (C_PLPL, inf);
2654 }
2655
2656 /* Always do C*. */
2657 void
2658 Cstar_entries (inf)
2659 FILE *inf;
2660 {
2661 C_entries (C_STAR, inf);
2662 }
2663
2664 /* Always do Yacc. */
2665 void
2666 Yacc_entries (inf)
2667 FILE *inf;
2668 {
2669 C_entries (YACC, inf);
2670 }
2671 \f
2672 /* Fortran parsing */
2673
2674 char *dbp;
2675
2676 logical
2677 tail (cp)
2678 char *cp;
2679 {
2680 register int len = 0;
2681
2682 while (*cp && lowcase(*cp) == lowcase(dbp[len]))
2683 cp++, len++;
2684 if (*cp == '\0' && !intoken(dbp[len]))
2685 {
2686 dbp += len;
2687 return TRUE;
2688 }
2689 return FALSE;
2690 }
2691
2692 void
2693 takeprec ()
2694 {
2695 while (isspace (*dbp))
2696 dbp++;
2697 if (*dbp != '*')
2698 return;
2699 dbp++;
2700 while (isspace (*dbp))
2701 dbp++;
2702 if (strneq (dbp, "(*)", 3))
2703 {
2704 dbp += 3;
2705 return;
2706 }
2707 if (!isdigit (*dbp))
2708 {
2709 --dbp; /* force failure */
2710 return;
2711 }
2712 do
2713 dbp++;
2714 while (isdigit (*dbp));
2715 }
2716
2717 void
2718 getit (inf)
2719 FILE *inf;
2720 {
2721 register char *cp;
2722
2723 while (isspace (*dbp))
2724 dbp++;
2725 if (*dbp == '\0')
2726 {
2727 lineno++;
2728 linecharno = charno;
2729 charno += readline (&lb, inf);
2730 dbp = lb.buffer;
2731 if (dbp[5] != '&')
2732 return;
2733 dbp += 6;
2734 while (isspace (*dbp))
2735 dbp++;
2736 }
2737 if (!isalpha (*dbp)
2738 && *dbp != '_'
2739 && *dbp != '$')
2740 return;
2741 for (cp = dbp + 1;
2742 (*cp
2743 && (isalpha (*cp) || isdigit (*cp) || (*cp == '_') || (*cp == '$')));
2744 cp++)
2745 continue;
2746 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
2747 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2748 }
2749
2750 void
2751 Fortran_functions (inf)
2752 FILE *inf;
2753 {
2754 lineno = 0;
2755 charno = 0;
2756
2757 while (!feof (inf))
2758 {
2759 lineno++;
2760 linecharno = charno;
2761 charno += readline (&lb, inf);
2762 dbp = lb.buffer;
2763 if (*dbp == '%')
2764 dbp++; /* Ratfor escape to fortran */
2765 while (isspace (*dbp))
2766 dbp++;
2767 if (*dbp == '\0')
2768 continue;
2769 switch (lowcase (*dbp))
2770 {
2771 case 'i':
2772 if (tail ("integer"))
2773 takeprec ();
2774 break;
2775 case 'r':
2776 if (tail ("real"))
2777 takeprec ();
2778 break;
2779 case 'l':
2780 if (tail ("logical"))
2781 takeprec ();
2782 break;
2783 case 'c':
2784 if (tail ("complex") || tail ("character"))
2785 takeprec ();
2786 break;
2787 case 'd':
2788 if (tail ("double"))
2789 {
2790 while (isspace (*dbp))
2791 dbp++;
2792 if (*dbp == '\0')
2793 continue;
2794 if (tail ("precision"))
2795 break;
2796 continue;
2797 }
2798 break;
2799 }
2800 while (isspace (*dbp))
2801 dbp++;
2802 if (*dbp == '\0')
2803 continue;
2804 switch (lowcase (*dbp))
2805 {
2806 case 'f':
2807 if (tail ("function"))
2808 getit (inf);
2809 continue;
2810 case 's':
2811 if (tail ("subroutine"))
2812 getit (inf);
2813 continue;
2814 case 'e':
2815 if (tail ("entry"))
2816 getit (inf);
2817 continue;
2818 case 'p':
2819 if (tail ("program"))
2820 {
2821 getit (inf);
2822 continue;
2823 }
2824 if (tail ("procedure"))
2825 getit (inf);
2826 continue;
2827 }
2828 }
2829 }
2830 \f
2831 /*
2832 * Bob Weiner, Motorola Inc., 4/3/94
2833 * Unix and microcontroller assembly tag handling
2834 * look for '^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]'
2835 */
2836 void
2837 Asm_labels (inf)
2838 FILE *inf;
2839 {
2840 register char *cp;
2841
2842 lineno = 0;
2843 charno = 0;
2844
2845 while (!feof (inf))
2846 {
2847 lineno++;
2848 linecharno = charno;
2849 charno += readline (&lb, inf);
2850 cp = lb.buffer;
2851
2852 /* If first char is alphabetic or one of [_.$], test for colon
2853 following identifier. */
2854 if (isalpha (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
2855 {
2856 /* Read past label. */
2857 cp++;
2858 while (isalnum (*cp) || *cp == '_' || *cp == '.' || *cp == '$')
2859 cp++;
2860 if (*cp == ':' || isspace (*cp))
2861 {
2862 /* Found end of label, so copy it and add it to the table. */
2863 pfnote ((CTAGS) ? savenstr(lb.buffer, cp-lb.buffer) : NULL, TRUE,
2864 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2865 }
2866 }
2867 }
2868 }
2869 \f
2870 /*
2871 * Perl support by Bart Robinson <lomew@cs.utah.edu>
2872 * Perl sub names: look for /^sub[ \t\n]+[^ \t\n{]+/
2873 */
2874 void
2875 Perl_functions (inf)
2876 FILE *inf;
2877 {
2878 register char *cp;
2879
2880 lineno = 0;
2881 charno = 0;
2882
2883 while (!feof (inf))
2884 {
2885 lineno++;
2886 linecharno = charno;
2887 charno += readline (&lb, inf);
2888 cp = lb.buffer;
2889
2890 if (*cp++ == 's' && *cp++ == 'u' && *cp++ == 'b' && isspace(*cp++))
2891 {
2892 while (*cp && isspace(*cp))
2893 cp++;
2894 while (*cp && ! isspace(*cp) && *cp != '{')
2895 cp++;
2896 pfnote ((CTAGS) ? savenstr (lb.buffer, cp-lb.buffer) : NULL, TRUE,
2897 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
2898 }
2899 }
2900 }
2901 \f
2902 /* Added by Mosur Mohan, 4/22/88 */
2903 /* Pascal parsing */
2904
2905 #define GET_NEW_LINE \
2906 { \
2907 linecharno = charno; lineno++; \
2908 charno += 1 + readline (&lb, inf); \
2909 dbp = lb.buffer; \
2910 }
2911
2912 /*
2913 * Locates tags for procedures & functions. Doesn't do any type- or
2914 * var-definitions. It does look for the keyword "extern" or
2915 * "forward" immediately following the procedure statement; if found,
2916 * the tag is skipped.
2917 */
2918 void
2919 Pascal_functions (inf)
2920 FILE *inf;
2921 {
2922 struct linebuffer tline; /* mostly copied from C_entries */
2923 long save_lcno;
2924 int save_lineno, save_len;
2925 char c, *cp, *namebuf;
2926
2927 logical /* each of these flags is TRUE iff: */
2928 incomment, /* point is inside a comment */
2929 inquote, /* point is inside '..' string */
2930 get_tagname, /* point is after PROCEDURE/FUNCTION
2931 keyword, so next item = potential tag */
2932 found_tag, /* point is after a potential tag */
2933 inparms, /* point is within parameter-list */
2934 verify_tag; /* point has passed the parm-list, so the
2935 next token will determine whether this
2936 is a FORWARD/EXTERN to be ignored, or
2937 whether it is a real tag */
2938
2939 lineno = 0;
2940 charno = 0;
2941 dbp = lb.buffer;
2942 *dbp = '\0';
2943 save_len = 0;
2944 initbuffer (&tline);
2945
2946 incomment = inquote = FALSE;
2947 found_tag = FALSE; /* have a proc name; check if extern */
2948 get_tagname = FALSE; /* have found "procedure" keyword */
2949 inparms = FALSE; /* found '(' after "proc" */
2950 verify_tag = FALSE; /* check if "extern" is ahead */
2951
2952 /* long main loop to get next char */
2953 while (!feof (inf))
2954 {
2955 c = *dbp++;
2956 if (c == '\0') /* if end of line */
2957 {
2958 GET_NEW_LINE;
2959 if (*dbp == '\0')
2960 continue;
2961 if (!((found_tag && verify_tag) ||
2962 get_tagname))
2963 c = *dbp++; /* only if don't need *dbp pointing
2964 to the beginning of the name of
2965 the procedure or function */
2966 }
2967 if (incomment)
2968 {
2969 if (c == '}') /* within { } comments */
2970 incomment = FALSE;
2971 else if (c == '*' && *dbp == ')') /* within (* *) comments */
2972 {
2973 dbp++;
2974 incomment = FALSE;
2975 }
2976 continue;
2977 }
2978 else if (inquote)
2979 {
2980 if (c == '\'')
2981 inquote = FALSE;
2982 continue;
2983 }
2984 else
2985 switch (c)
2986 {
2987 case '\'':
2988 inquote = TRUE; /* found first quote */
2989 continue;
2990 case '{': /* found open { comment */
2991 incomment = TRUE;
2992 continue;
2993 case '(':
2994 if (*dbp == '*') /* found open (* comment */
2995 {
2996 incomment = TRUE;
2997 dbp++;
2998 }
2999 else if (found_tag) /* found '(' after tag, i.e., parm-list */
3000 inparms = TRUE;
3001 continue;
3002 case ')': /* end of parms list */
3003 if (inparms)
3004 inparms = FALSE;
3005 continue;
3006 case ';':
3007 if (found_tag && !inparms) /* end of proc or fn stmt */
3008 {
3009 verify_tag = TRUE;
3010 break;
3011 }
3012 continue;
3013 }
3014 if (found_tag && verify_tag && (*dbp != ' '))
3015 {
3016 /* check if this is an "extern" declaration */
3017 if (*dbp == '\0')
3018 continue;
3019 if (lowcase (*dbp == 'e'))
3020 {
3021 if (tail ("extern")) /* superfluous, really! */
3022 {
3023 found_tag = FALSE;
3024 verify_tag = FALSE;
3025 }
3026 }
3027 else if (lowcase (*dbp) == 'f')
3028 {
3029 if (tail ("forward")) /* check for forward reference */
3030 {
3031 found_tag = FALSE;
3032 verify_tag = FALSE;
3033 }
3034 }
3035 if (found_tag && verify_tag) /* not external proc, so make tag */
3036 {
3037 found_tag = FALSE;
3038 verify_tag = FALSE;
3039 pfnote (namebuf, TRUE,
3040 tline.buffer, save_len, save_lineno, save_lcno);
3041 continue;
3042 }
3043 }
3044 if (get_tagname) /* grab name of proc or fn */
3045 {
3046 if (*dbp == '\0')
3047 continue;
3048
3049 /* save all values for later tagging */
3050 GROW_LINEBUFFER (tline, strlen (lb.buffer) + 1);
3051 strcpy (tline.buffer, lb.buffer);
3052 save_lineno = lineno;
3053 save_lcno = linecharno;
3054
3055 /* grab block name */
3056 for (cp = dbp + 1; *cp && (!endtoken (*cp)); cp++)
3057 continue;
3058 namebuf = (CTAGS) ? savenstr (dbp, cp-dbp) : NULL;
3059 dbp = cp; /* set dbp to e-o-token */
3060 save_len = dbp - lb.buffer + 1;
3061 get_tagname = FALSE;
3062 found_tag = TRUE;
3063 continue;
3064
3065 /* and proceed to check for "extern" */
3066 }
3067 else if (!incomment && !inquote && !found_tag)
3068 {
3069 /* check for proc/fn keywords */
3070 switch (lowcase (c))
3071 {
3072 case 'p':
3073 if (tail ("rocedure")) /* c = 'p', dbp has advanced */
3074 get_tagname = TRUE;
3075 continue;
3076 case 'f':
3077 if (tail ("unction"))
3078 get_tagname = TRUE;
3079 continue;
3080 }
3081 }
3082 } /* while not eof */
3083
3084 free (tline.buffer);
3085 }
3086 \f
3087 /*
3088 * lisp tag functions
3089 * look for (def or (DEF, quote or QUOTE
3090 */
3091 int
3092 L_isdef (strp)
3093 register char *strp;
3094 {
3095 return ((strp[1] == 'd' || strp[1] == 'D')
3096 && (strp[2] == 'e' || strp[2] == 'E')
3097 && (strp[3] == 'f' || strp[3] == 'F'));
3098 }
3099
3100 int
3101 L_isquote (strp)
3102 register char *strp;
3103 {
3104 return ((*(++strp) == 'q' || *strp == 'Q')
3105 && (*(++strp) == 'u' || *strp == 'U')
3106 && (*(++strp) == 'o' || *strp == 'O')
3107 && (*(++strp) == 't' || *strp == 'T')
3108 && (*(++strp) == 'e' || *strp == 'E')
3109 && isspace(*(++strp)));
3110 }
3111
3112 void
3113 L_getit ()
3114 {
3115 register char *cp;
3116
3117 if (*dbp == '\'') /* Skip prefix quote */
3118 dbp++;
3119 else if (*dbp == '(' && L_isquote (dbp)) /* Skip "(quote " */
3120 {
3121 dbp += 7;
3122 while (isspace(*dbp))
3123 dbp++;
3124 }
3125 for (cp = dbp /*+1*/;
3126 *cp && *cp != '(' && *cp != ' ' && *cp != ')';
3127 cp++)
3128 continue;
3129 if (cp == dbp)
3130 return;
3131
3132 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
3133 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
3134 }
3135
3136 void
3137 Lisp_functions (inf)
3138 FILE *inf;
3139 {
3140 lineno = 0;
3141 charno = 0;
3142
3143 while (!feof (inf))
3144 {
3145 lineno++;
3146 linecharno = charno;
3147 charno += readline (&lb, inf);
3148 dbp = lb.buffer;
3149 if (dbp[0] == '(')
3150 {
3151 if (L_isdef (dbp))
3152 {
3153 while (!isspace (*dbp))
3154 dbp++;
3155 while (isspace (*dbp))
3156 dbp++;
3157 L_getit ();
3158 }
3159 else
3160 {
3161 /* Check for (foo::defmumble name-defined ... */
3162 do
3163 dbp++;
3164 while (*dbp && !isspace (*dbp)
3165 && *dbp != ':' && *dbp != '(' && *dbp != ')');
3166 if (*dbp == ':')
3167 {
3168 do
3169 dbp++;
3170 while (*dbp == ':');
3171
3172 if (L_isdef (dbp - 1))
3173 {
3174 while (!isspace (*dbp))
3175 dbp++;
3176 while (isspace (*dbp))
3177 dbp++;
3178 L_getit ();
3179 }
3180 }
3181 }
3182 }
3183 }
3184 }
3185 \f
3186 /*
3187 * Scheme tag functions
3188 * look for (def... xyzzy
3189 * look for (def... (xyzzy
3190 * look for (def ... ((...(xyzzy ....
3191 * look for (set! xyzzy
3192 */
3193
3194 void get_scheme ();
3195
3196 void
3197 Scheme_functions (inf)
3198 FILE *inf;
3199 {
3200 lineno = 0;
3201 charno = 0;
3202
3203 while (!feof (inf))
3204 {
3205 lineno++;
3206 linecharno = charno;
3207 charno += readline (&lb, inf);
3208 dbp = lb.buffer;
3209 if (dbp[0] == '(' &&
3210 (dbp[1] == 'D' || dbp[1] == 'd') &&
3211 (dbp[2] == 'E' || dbp[2] == 'e') &&
3212 (dbp[3] == 'F' || dbp[3] == 'f'))
3213 {
3214 while (!isspace (*dbp))
3215 dbp++;
3216 /* Skip over open parens and white space */
3217 while (*dbp && (isspace (*dbp) || *dbp == '('))
3218 dbp++;
3219 get_scheme ();
3220 }
3221 if (dbp[0] == '(' &&
3222 (dbp[1] == 'S' || dbp[1] == 's') &&
3223 (dbp[2] == 'E' || dbp[2] == 'e') &&
3224 (dbp[3] == 'T' || dbp[3] == 't') &&
3225 (dbp[4] == '!' || dbp[4] == '!') &&
3226 (isspace (dbp[5])))
3227 {
3228 while (!isspace (*dbp))
3229 dbp++;
3230 /* Skip over white space */
3231 while (isspace (*dbp))
3232 dbp++;
3233 get_scheme ();
3234 }
3235 }
3236 }
3237
3238 void
3239 get_scheme ()
3240 {
3241 register char *cp;
3242
3243 if (*dbp == '\0')
3244 return;
3245 /* Go till you get to white space or a syntactic break */
3246 for (cp = dbp + 1;
3247 *cp && *cp != '(' && *cp != ')' && !isspace (*cp);
3248 cp++)
3249 continue;
3250 pfnote ((CTAGS) ? savenstr (dbp, cp-dbp) : NULL, TRUE,
3251 lb.buffer, cp - lb.buffer + 1, lineno, linecharno);
3252 }
3253 \f
3254 /* Find tags in TeX and LaTeX input files. */
3255
3256 /* TEX_toktab is a table of TeX control sequences that define tags.
3257 Each TEX_tabent records one such control sequence.
3258 CONVERT THIS TO USE THE Stab TYPE!! */
3259 struct TEX_tabent
3260 {
3261 char *name;
3262 int len;
3263 };
3264
3265 struct TEX_tabent *TEX_toktab = NULL; /* Table with tag tokens */
3266
3267 /* Default set of control sequences to put into TEX_toktab.
3268 The value of environment var TEXTAGS is prepended to this. */
3269
3270 char *TEX_defenv = "\
3271 :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\
3272 :part:appendix:entry:index";
3273
3274 void TEX_mode ();
3275 struct TEX_tabent *TEX_decode_env ();
3276 int TEX_Token ();
3277 #if TeX_named_tokens
3278 void TEX_getit ();
3279 #endif
3280
3281 char TEX_esc = '\\';
3282 char TEX_opgrp = '{';
3283 char TEX_clgrp = '}';
3284
3285 /*
3286 * TeX/LaTeX scanning loop.
3287 */
3288 void
3289 TeX_functions (inf)
3290 FILE *inf;
3291 {
3292 char *lasthit;
3293
3294 lineno = 0;
3295 charno = 0;
3296
3297 /* Select either \ or ! as escape character. */
3298 TEX_mode (inf);
3299
3300 /* Initialize token table once from environment. */
3301 if (!TEX_toktab)
3302 TEX_toktab = TEX_decode_env ("TEXTAGS", TEX_defenv);
3303
3304 while (!feof (inf))
3305 { /* Scan each line in file */
3306 lineno++;
3307 linecharno = charno;
3308 charno += readline (&lb, inf);
3309 dbp = lb.buffer;
3310 lasthit = dbp;
3311 while (dbp = etags_strchr (dbp, TEX_esc)) /* Look at each esc in line */
3312 {
3313 register int i;
3314
3315 if (!*(++dbp))
3316 break;
3317 linecharno += dbp - lasthit;
3318 lasthit = dbp;
3319 i = TEX_Token (lasthit);
3320 if (0 <= i)
3321 {
3322 pfnote (NULL, TRUE,
3323 lb.buffer, strlen (lb.buffer), lineno, linecharno);
3324 #if TeX_named_tokens
3325 TEX_getit (lasthit, TEX_toktab[i].len);
3326 #endif
3327 break; /* We only save a line once */
3328 }
3329 }
3330 }
3331 }
3332
3333 #define TEX_LESC '\\'
3334 #define TEX_SESC '!'
3335 #define TEX_cmt '%'
3336
3337 /* Figure out whether TeX's escapechar is '\\' or '!' and set grouping
3338 chars accordingly. */
3339 void
3340 TEX_mode (inf)
3341 FILE *inf;
3342 {
3343 int c;
3344
3345 while ((c = getc (inf)) != EOF)
3346 {
3347 /* Skip to next line if we hit the TeX comment char. */
3348 if (c == TEX_cmt)
3349 while (c != '\n')
3350 c = getc (inf);
3351 else if (c == TEX_LESC || c == TEX_SESC )
3352 break;
3353 }
3354
3355 if (c == TEX_LESC)
3356 {
3357 TEX_esc = TEX_LESC;
3358 TEX_opgrp = '{';
3359 TEX_clgrp = '}';
3360 }
3361 else
3362 {
3363 TEX_esc = TEX_SESC;
3364 TEX_opgrp = '<';
3365 TEX_clgrp = '>';
3366 }
3367 rewind (inf);
3368 }
3369
3370 /* Read environment and prepend it to the default string.
3371 Build token table. */
3372 struct TEX_tabent *
3373 TEX_decode_env (evarname, defenv)
3374 char *evarname;
3375 char *defenv;
3376 {
3377 register char *env, *p;
3378
3379 struct TEX_tabent *tab;
3380 int size, i;
3381
3382 /* Append default string to environment. */
3383 env = getenv (evarname);
3384 if (!env)
3385 env = defenv;
3386 else
3387 env = concat (env, defenv, "");
3388
3389 /* Allocate a token table */
3390 for (size = 1, p = env; p;)
3391 if ((p = etags_strchr (p, ':')) && *(++p))
3392 size++;
3393 /* Add 1 to leave room for null terminator. */
3394 tab = xnew (size + 1, struct TEX_tabent);
3395
3396 /* Unpack environment string into token table. Be careful about */
3397 /* zero-length strings (leading ':', "::" and trailing ':') */
3398 for (i = 0; *env;)
3399 {
3400 p = etags_strchr (env, ':');
3401 if (!p) /* End of environment string. */
3402 p = env + strlen (env);
3403 if (p - env > 0)
3404 { /* Only non-zero strings. */
3405 tab[i].name = savenstr (env, p - env);
3406 tab[i].len = strlen (tab[i].name);
3407 i++;
3408 }
3409 if (*p)
3410 env = p + 1;
3411 else
3412 {
3413 tab[i].name = NULL; /* Mark end of table. */
3414 tab[i].len = 0;
3415 break;
3416 }
3417 }
3418 return tab;
3419 }
3420
3421 #if TeX_named_tokens
3422 /* Record a tag defined by a TeX command of length LEN and starting at NAME.
3423 The name being defined actually starts at (NAME + LEN + 1).
3424 But we seem to include the TeX command in the tag name. */
3425 void
3426 TEX_getit (name, len)
3427 char *name;
3428 int len;
3429 {
3430 char *p = name + len;
3431
3432 if (*name == '\0')
3433 return;
3434
3435 /* Let tag name extend to next group close (or end of line) */
3436 while (*p && *p != TEX_clgrp)
3437 p++;
3438 pfnote (savenstr (name, p-name), TRUE,
3439 lb.buffer, strlen (lb.buffer), lineno, linecharno);
3440 }
3441 #endif
3442
3443 /* If the text at CP matches one of the tag-defining TeX command names,
3444 return the pointer to the first occurrence of that command in TEX_toktab.
3445 Otherwise return -1.
3446 Keep the capital `T' in `Token' for dumb truncating compilers
3447 (this distinguishes it from `TEX_toktab' */
3448 int
3449 TEX_Token (cp)
3450 char *cp;
3451 {
3452 int i;
3453
3454 for (i = 0; TEX_toktab[i].len > 0; i++)
3455 if (strneq (TEX_toktab[i].name, cp, TEX_toktab[i].len))
3456 return i;
3457 return -1;
3458 }
3459 \f
3460 /*
3461 * Prolog support (rewritten) by Anders Lindgren, Mar. 96
3462 *
3463 * Assumes that the predicate starts at column 0.
3464 * Only the first clause of a predicate is added.
3465 */
3466 void
3467 Prolog_functions (inf)
3468 FILE *inf;
3469 {
3470 int prolog_pred ();
3471 void prolog_skip_comment ();
3472
3473 char * last;
3474 int len;
3475 int allocated;
3476
3477 allocated = 0;
3478 len = 0;
3479 last = NULL;
3480
3481 lineno = 0;
3482 linecharno = 0;
3483 charno = 0;
3484
3485 while (!feof (inf))
3486 {
3487 lineno++;
3488 linecharno += charno;
3489 charno = readline (&lb, inf);
3490 dbp = lb.buffer;
3491 if (dbp[0] == '\0') /* Empty line */
3492 continue;
3493 else if (isspace (dbp[0])) /* Not a predicate */
3494 continue;
3495 else if (dbp[0] == '/' && dbp[1] == '*') /* comment. */
3496 prolog_skip_comment (&lb, inf, &lineno, &linecharno);
3497 else if (len = prolog_pred (dbp, last))
3498 {
3499 /* Predicate. Store the function name so that we only
3500 * generates a tag for the first clause. */
3501 if (last == NULL)
3502 last = xnew(len + 1, char);
3503 else if (len + 1 > allocated)
3504 last = (char *) xrealloc(last, len + 1);
3505 allocated = len + 1;
3506 strncpy (last, dbp, len);
3507 last[len] = '\0';
3508 }
3509 }
3510 }
3511
3512
3513 void
3514 prolog_skip_comment (plb, inf)
3515 struct linebuffer *plb;
3516 FILE *inf;
3517 {
3518 char *cp;
3519
3520 do
3521 {
3522 for (cp = plb->buffer; *cp != '\0'; cp++)
3523 if (cp[0] == '*' && cp[1] == '/')
3524 return;
3525 lineno++;
3526 linecharno += readline (plb, inf);
3527 }
3528 while (!feof(inf));
3529 }
3530
3531 /*
3532 * A predicate definition is added if it matches:
3533 * <beginning of line><Prolog Atom><whitespace>(
3534 *
3535 * It is added to the tags database if it doesn't match the
3536 * name of the previous clause header.
3537 *
3538 * Return the size of the name of the predicate, or 0 if no header
3539 * was found.
3540 */
3541 int
3542 prolog_pred (s, last)
3543 char *s;
3544 char *last; /* Name of last clause. */
3545 {
3546 int prolog_atom();
3547 int prolog_white();
3548
3549 int pos;
3550 int len;
3551
3552 pos = prolog_atom(s, 0);
3553 if (pos < 1)
3554 return 0;
3555
3556 len = pos;
3557 pos += prolog_white(s, pos);
3558
3559 if ((s[pos] == '(') || (s[pos] == '.'))
3560 {
3561 if (s[pos] == '(')
3562 pos++;
3563
3564 /* Save only the first clause. */
3565 if ((last == NULL) ||
3566 (len != strlen(last)) ||
3567 (strncmp(s, last, len) != 0))
3568 {
3569 pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
3570 s, pos, lineno, linecharno);
3571 return len;
3572 }
3573 }
3574 return 0;
3575 }
3576
3577 /*
3578 * Consume a Prolog atom.
3579 * Return the number of bytes consumed, or -1 if there was an error.
3580 *
3581 * A prolog atom, in this context, could be one of:
3582 * - An alphanumeric sequence, starting with a lower case letter.
3583 * - A quoted arbitrary string. Single quotes can escape themselves.
3584 * Backslash quotes everything.
3585 */
3586 int
3587 prolog_atom (s, pos)
3588 char *s;
3589 int pos;
3590 {
3591 int origpos;
3592
3593 origpos = pos;
3594
3595 if (islower(s[pos]) || (s[pos] == '_'))
3596 {
3597 /* The atom is unquoted. */
3598 pos++;
3599 while (isalnum(s[pos]) || (s[pos] == '_'))
3600 {
3601 pos++;
3602 }
3603 return pos - origpos;
3604 }
3605 else if (s[pos] == '\'')
3606 {
3607 pos++;
3608
3609 while (1)
3610 {
3611 if (s[pos] == '\'')
3612 {
3613 pos++;
3614 if (s[pos] != '\'')
3615 break;
3616 pos++; /* A double quote */
3617 }
3618 else if (s[pos] == '\0')
3619 /* Multiline quoted atoms are ignored. */
3620 return -1;
3621 else if (s[pos] == '\\')
3622 {
3623 if (s[pos+1] == '\0')
3624 return -1;
3625 pos += 2;
3626 }
3627 else
3628 pos++;
3629 }
3630 return pos - origpos;
3631 }
3632 else
3633 return -1;
3634 }
3635
3636 /* Consume whitespace. Return the number of bytes eaten. */
3637 int
3638 prolog_white (s, pos)
3639 char *s;
3640 int pos;
3641 {
3642 int origpos;
3643
3644 origpos = pos;
3645
3646 while (isspace(s[pos]))
3647 pos++;
3648
3649 return pos - origpos;
3650 }
3651 \f
3652 /*
3653 * Support for Erlang -- Anders Lindgren, Feb 1996.
3654 *
3655 * Generates tags for functions, defines, and records.
3656 *
3657 * Assumes that Erlang functions start at column 0.
3658 */
3659 void
3660 Erlang_functions (inf)
3661 FILE *inf;
3662 {
3663 int erlang_func ();
3664 void erlang_attribute ();
3665
3666 char * last;
3667 int len;
3668 int allocated;
3669
3670 allocated = 0;
3671 len = 0;
3672 last = NULL;
3673
3674 lineno = 0;
3675 linecharno = 0;
3676 charno = 0;
3677
3678 while (!feof (inf))
3679 {
3680 lineno++;
3681 linecharno += charno;
3682 charno = readline (&lb, inf);
3683 dbp = lb.buffer;
3684 if (dbp[0] == '\0') /* Empty line */
3685 continue;
3686 else if (isspace (dbp[0])) /* Not function nor attribute */
3687 continue;
3688 else if (dbp[0] == '%') /* comment */
3689 continue;
3690 else if (dbp[0] == '"') /* Sometimes, strings start in column one */
3691 continue;
3692 else if (dbp[0] == '-') /* attribute, e.g. "-define" */
3693 {
3694 erlang_attribute(dbp);
3695 last = NULL;
3696 }
3697 else if (len = erlang_func (dbp, last))
3698 {
3699 /*
3700 * Function. Store the function name so that we only
3701 * generates a tag for the first clause.
3702 */
3703 if (last == NULL)
3704 last = xnew(len + 1, char);
3705 else if (len + 1 > allocated)
3706 last = (char *) xrealloc(last, len + 1);
3707 allocated = len + 1;
3708 strncpy (last, dbp, len);
3709 last[len] = '\0';
3710 }
3711 }
3712 }
3713
3714
3715 /*
3716 * A function definition is added if it matches:
3717 * <beginning of line><Erlang Atom><whitespace>(
3718 *
3719 * It is added to the tags database if it doesn't match the
3720 * name of the previous clause header.
3721 *
3722 * Return the size of the name of the function, or 0 if no function
3723 * was found.
3724 */
3725 int
3726 erlang_func (s, last)
3727 char *s;
3728 char *last; /* Name of last clause. */
3729 {
3730 int erlang_atom ();
3731 int erlang_white ();
3732
3733 int pos;
3734 int len;
3735
3736 pos = erlang_atom(s, 0);
3737 if (pos < 1)
3738 return 0;
3739
3740 len = pos;
3741 pos += erlang_white(s, pos);
3742
3743 if (s[pos++] == '(')
3744 {
3745 /* Save only the first clause. */
3746 if ((last == NULL) ||
3747 (len != strlen(last)) ||
3748 (strncmp(s, last, len) != 0))
3749 {
3750 pfnote ((CTAGS) ? savenstr (s, len) : NULL, TRUE,
3751 s, pos, lineno, linecharno);
3752 return len;
3753 }
3754 }
3755 return 0;
3756 }
3757
3758
3759 /*
3760 * Handle attributes. Currently, tags are generated for defines
3761 * and records.
3762 *
3763 * They are on the form:
3764 * -define(foo, bar).
3765 * -define(Foo(M, N), M+N).
3766 * -record(graph, {vtab = notable, cyclic = true}).
3767 */
3768 void
3769 erlang_attribute (s)
3770 char *s;
3771 {
3772 int erlang_atom ();
3773 int erlang_white ();
3774
3775 int pos;
3776 int len;
3777
3778 if ((strncmp(s, "-define", 7) == 0) ||
3779 (strncmp(s, "-record", 7) == 0))
3780 {
3781 pos = 7;
3782 pos += erlang_white(s, pos);
3783
3784 if (s[pos++] == '(')
3785 {
3786 pos += erlang_white(s, pos);
3787
3788 if (len = erlang_atom(s, pos))
3789 {
3790 pfnote ((CTAGS) ? savenstr (& s[pos], len) : NULL, TRUE,
3791 s, pos + len, lineno, linecharno);
3792 }
3793 }
3794 }
3795 return;
3796 }
3797
3798
3799 /*
3800 * Consume an Erlang atom (or variable).
3801 * Return the number of bytes consumed, or -1 if there was an error.
3802 */
3803 int
3804 erlang_atom (s, pos)
3805 char *s;
3806 int pos;
3807 {
3808 int origpos;
3809
3810 origpos = pos;
3811
3812 if (isalpha (s[pos]) || s[pos] == '_')
3813 {
3814 /* The atom is unquoted. */
3815 pos++;
3816 while (isalnum (s[pos]) || s[pos] == '_')
3817 pos++;
3818 return pos - origpos;
3819 }
3820 else if (s[pos] == '\'')
3821 {
3822 pos++;
3823
3824 while (1)
3825 {
3826 if (s[pos] == '\'')
3827 {
3828 pos++;
3829 break;
3830 }
3831 else if (s[pos] == '\0')
3832 /* Multiline quoted atoms are ignored. */
3833 return -1;
3834 else if (s[pos] == '\\')
3835 {
3836 if (s[pos+1] == '\0')
3837 return -1;
3838 pos += 2;
3839 }
3840 else
3841 pos++;
3842 }
3843 return pos - origpos;
3844 }
3845 else
3846 return -1;
3847 }
3848
3849 /* Consume whitespace. Return the number of bytes eaten */
3850 int
3851 erlang_white (s, pos)
3852 char *s;
3853 int pos;
3854 {
3855 int origpos;
3856
3857 origpos = pos;
3858
3859 while (isspace (s[pos]))
3860 pos++;
3861
3862 return pos - origpos;
3863 }
3864 \f
3865 #ifdef ETAGS_REGEXPS
3866 /* Take a string like "/blah/" and turn it into "blah", making sure
3867 that the first and last characters are the same, and handling
3868 quoted separator characters. Actually, stops on the occurrence of
3869 an unquoted separator. Also turns "\t" into a Tab character.
3870 Returns pointer to terminating separator. Works in place. Null
3871 terminates name string. */
3872 char *
3873 scan_separators (name)
3874 char *name;
3875 {
3876 char sep = name[0];
3877 char *copyto = name;
3878 logical quoted = FALSE;
3879
3880 for (++name; *name != '\0'; ++name)
3881 {
3882 if (quoted)
3883 {
3884 if (*name == 't')
3885 *copyto++ = '\t';
3886 else if (*name == sep)
3887 *copyto++ = sep;
3888 else
3889 {
3890 /* Something else is quoted, so preserve the quote. */
3891 *copyto++ = '\\';
3892 *copyto++ = *name;
3893 }
3894 quoted = FALSE;
3895 }
3896 else if (*name == '\\')
3897 quoted = TRUE;
3898 else if (*name == sep)
3899 break;
3900 else
3901 *copyto++ = *name;
3902 }
3903
3904 /* Terminate copied string. */
3905 *copyto = '\0';
3906 return name;
3907 }
3908
3909 /* Turn a name, which is an ed-style (but Emacs syntax) regular
3910 expression, into a real regular expression by compiling it. */
3911 void
3912 add_regex (regexp_pattern)
3913 char *regexp_pattern;
3914 {
3915 char *name;
3916 const char *err;
3917 struct re_pattern_buffer *patbuf;
3918
3919 if (regexp_pattern == NULL)
3920 {
3921 /* Remove existing regexps. */
3922 num_patterns = 0;
3923 patterns = NULL;
3924 return;
3925 }
3926
3927 if (regexp_pattern[0] == '\0')
3928 {
3929 error ("missing regexp", 0);
3930 return;
3931 }
3932 if (regexp_pattern[strlen(regexp_pattern)-1] != regexp_pattern[0])
3933 {
3934 error ("%s: unterminated regexp", regexp_pattern);
3935 return;
3936 }
3937 name = scan_separators (regexp_pattern);
3938 if (regexp_pattern[0] == '\0')
3939 {
3940 error ("null regexp", 0);
3941 return;
3942 }
3943 (void) scan_separators (name);
3944
3945 patbuf = xnew (1, struct re_pattern_buffer);
3946 patbuf->translate = NULL;
3947 patbuf->fastmap = NULL;
3948 patbuf->buffer = NULL;
3949 patbuf->allocated = 0;
3950
3951 err = re_compile_pattern (regexp_pattern, strlen (regexp_pattern), patbuf);
3952 if (err != NULL)
3953 {
3954 error ("%s while compiling pattern", err);
3955 return;
3956 }
3957
3958 num_patterns += 1;
3959 if (num_patterns == 1)
3960 patterns = xnew (1, struct pattern);
3961 else
3962 patterns = ((struct pattern *)
3963 xrealloc (patterns,
3964 (num_patterns * sizeof (struct pattern))));
3965 patterns[num_patterns - 1].pattern = patbuf;
3966 patterns[num_patterns - 1].name_pattern = savestr (name);
3967 patterns[num_patterns - 1].error_signaled = FALSE;
3968 }
3969
3970 /*
3971 * Do the substitutions indicated by the regular expression and
3972 * arguments.
3973 */
3974 char *
3975 substitute (in, out, regs)
3976 char *in, *out;
3977 struct re_registers *regs;
3978 {
3979 char *result = NULL, *t;
3980 int size = 0;
3981
3982 /* Pass 1: figure out how much size to allocate. */
3983 for (t = out; *t; ++t)
3984 {
3985 if (*t == '\\')
3986 {
3987 ++t;
3988 if (!*t)
3989 {
3990 fprintf (stderr, "%s: pattern substitution ends prematurely\n",
3991 progname);
3992 return NULL;
3993 }
3994 if (isdigit (*t))
3995 {
3996 int dig = *t - '0';
3997 size += regs->end[dig] - regs->start[dig];
3998 }
3999 }
4000 }
4001
4002 /* Allocate space and do the substitutions. */
4003 result = xnew (size + 1, char);
4004 size = 0;
4005 for (; *out; ++out)
4006 {
4007 if (*out == '\\')
4008 {
4009 ++out;
4010 if (isdigit (*out))
4011 {
4012 /* Using "dig2" satisfies my debugger. Bleah. */
4013 int dig2 = *out - '0';
4014 strncpy (result + size, in + regs->start[dig2],
4015 regs->end[dig2] - regs->start[dig2]);
4016 size += regs->end[dig2] - regs->start[dig2];
4017 }
4018 else
4019 result[size++] = *out;
4020 }
4021 else
4022 result[size++] = *out;
4023 }
4024 result[size] = '\0';
4025
4026 return result;
4027 }
4028 \f
4029 #endif /* ETAGS_REGEXPS */
4030 /* Initialize a linebuffer for use */
4031 void
4032 initbuffer (linebuffer)
4033 struct linebuffer *linebuffer;
4034 {
4035 linebuffer->size = 200;
4036 linebuffer->buffer = xnew (200, char);
4037 }
4038
4039 /*
4040 * Read a line of text from `stream' into `linebuffer'.
4041 * Return the number of characters read from `stream',
4042 * which is the length of the line including the newline, if any.
4043 */
4044 long
4045 readline_internal (linebuffer, stream)
4046 struct linebuffer *linebuffer;
4047 register FILE *stream;
4048 {
4049 char *buffer = linebuffer->buffer;
4050 register char *p = linebuffer->buffer;
4051 register char *pend;
4052 int chars_deleted;
4053
4054 pend = p + linebuffer->size; /* Separate to avoid 386/IX compiler bug. */
4055
4056 while (1)
4057 {
4058 register int c = getc (stream);
4059 if (p == pend)
4060 {
4061 linebuffer->size *= 2;
4062 buffer = (char *) xrealloc (buffer, linebuffer->size);
4063 p += buffer - linebuffer->buffer;
4064 pend = buffer + linebuffer->size;
4065 linebuffer->buffer = buffer;
4066 }
4067 if (c == EOF)
4068 {
4069 *p = '\0';
4070 chars_deleted = 0;
4071 break;
4072 }
4073 if (c == '\n')
4074 {
4075 if (p > buffer && p[-1] == '\r')
4076 {
4077 *--p = '\0';
4078 chars_deleted = 2;
4079 }
4080 else
4081 {
4082 *p = '\0';
4083 chars_deleted = 1;
4084 }
4085 break;
4086 }
4087 *p++ = c;
4088 }
4089
4090 return p - buffer + chars_deleted;
4091 }
4092
4093 /*
4094 * Like readline_internal, above, but try to match the input
4095 * line against any existing regular expressions.
4096 */
4097 long
4098 readline (linebuffer, stream)
4099 struct linebuffer *linebuffer;
4100 FILE *stream;
4101 {
4102 /* Read new line. */
4103 long result = readline_internal (linebuffer, stream);
4104 #ifdef ETAGS_REGEXPS
4105 int i;
4106
4107 /* Match against all listed patterns. */
4108 for (i = 0; i < num_patterns; ++i)
4109 {
4110 int match = re_match (patterns[i].pattern, linebuffer->buffer,
4111 (int)result, 0, &patterns[i].regs);
4112 switch (match)
4113 {
4114 case -2:
4115 /* Some error. */
4116 if (!patterns[i].error_signaled)
4117 {
4118 error ("error while matching pattern %d", i);
4119 patterns[i].error_signaled = TRUE;
4120 }
4121 break;
4122 case -1:
4123 /* No match. */
4124 break;
4125 default:
4126 /* Match occurred. Construct a tag. */
4127 if (patterns[i].name_pattern[0] != '\0')
4128 {
4129 /* Make a named tag. */
4130 char *name = substitute (linebuffer->buffer,
4131 patterns[i].name_pattern,
4132 &patterns[i].regs);
4133 if (name != NULL)
4134 pfnote (name, TRUE,
4135 linebuffer->buffer, match, lineno, linecharno);
4136 }
4137 else
4138 {
4139 /* Make an unnamed tag. */
4140 pfnote (NULL, TRUE,
4141 linebuffer->buffer, match, lineno, linecharno);
4142 }
4143 break;
4144 }
4145 }
4146 #endif /* ETAGS_REGEXPS */
4147
4148 return result;
4149 }
4150
4151 /*
4152 * Read a file, but do no processing. This is used to do regexp
4153 * matching on files that have no language defined.
4154 */
4155 void
4156 just_read_file (inf)
4157 FILE *inf;
4158 {
4159 lineno = 0;
4160 charno = 0;
4161
4162 while (!feof (inf))
4163 {
4164 ++lineno;
4165 linecharno = charno;
4166 charno += readline (&lb, inf) + 1;
4167 }
4168 }
4169
4170 \f
4171 /*
4172 * Return a pointer to a space of size strlen(cp)+1 allocated
4173 * with xnew where the string CP has been copied.
4174 */
4175 char *
4176 savestr (cp)
4177 char *cp;
4178 {
4179 return savenstr (cp, strlen (cp));
4180 }
4181
4182 /*
4183 * Return a pointer to a space of size LEN+1 allocated with xnew where
4184 * the string CP has been copied for at most the first LEN characters.
4185 */
4186 char *
4187 savenstr (cp, len)
4188 char *cp;
4189 int len;
4190 {
4191 register char *dp;
4192
4193 dp = xnew (len + 1, char);
4194 strncpy (dp, cp, len);
4195 dp[len] = '\0';
4196 return dp;
4197 }
4198
4199 /*
4200 * Return the ptr in sp at which the character c last
4201 * appears; NULL if not found
4202 *
4203 * Identical to System V strrchr, included for portability.
4204 */
4205 char *
4206 etags_strrchr (sp, c)
4207 register char *sp, c;
4208 {
4209 register char *r;
4210
4211 r = NULL;
4212 do
4213 {
4214 if (*sp == c)
4215 r = sp;
4216 } while (*sp++);
4217 return r;
4218 }
4219
4220
4221 /*
4222 * Return the ptr in sp at which the character c first
4223 * appears; NULL if not found
4224 *
4225 * Identical to System V strchr, included for portability.
4226 */
4227 char *
4228 etags_strchr (sp, c)
4229 register char *sp, c;
4230 {
4231 do
4232 {
4233 if (*sp == c)
4234 return sp;
4235 } while (*sp++);
4236 return NULL;
4237 }
4238
4239 /* Print error message and exit. */
4240 void
4241 fatal (s1, s2)
4242 char *s1, *s2;
4243 {
4244 error (s1, s2);
4245 exit (BAD);
4246 }
4247
4248 void
4249 pfatal (s1)
4250 char *s1;
4251 {
4252 perror (s1);
4253 exit (BAD);
4254 }
4255
4256 void
4257 suggest_asking_for_help ()
4258 {
4259 fprintf (stderr, "\tTry `%s --help' for a complete list of options.\n",
4260 progname);
4261 exit (BAD);
4262 }
4263
4264 /* Print error message. `s1' is printf control string, `s2' is arg for it. */
4265 void
4266 error (s1, s2)
4267 char *s1, *s2;
4268 {
4269 fprintf (stderr, "%s: ", progname);
4270 fprintf (stderr, s1, s2);
4271 fprintf (stderr, "\n");
4272 }
4273
4274 /* Return a newly-allocated string whose contents
4275 concatenate those of s1, s2, s3. */
4276 char *
4277 concat (s1, s2, s3)
4278 char *s1, *s2, *s3;
4279 {
4280 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
4281 char *result = xnew (len1 + len2 + len3 + 1, char);
4282
4283 strcpy (result, s1);
4284 strcpy (result + len1, s2);
4285 strcpy (result + len1 + len2, s3);
4286 result[len1 + len2 + len3] = '\0';
4287
4288 return result;
4289 }
4290 \f
4291 /* Does the same work as the system V getcwd, but does not need to
4292 guess the buffer size in advance. */
4293 char *
4294 etags_getcwd ()
4295 {
4296 #ifdef DOS_NT
4297 char *p, path[MAXPATHLEN + 1]; /* Fixed size is safe on MSDOS. */
4298
4299 getwd (path);
4300 p = path;
4301 while (*p)
4302 if (*p == '\\')
4303 *p++ = '/';
4304 else
4305 *p++ = lowcase (*p);
4306
4307 return strdup (path);
4308 #else /* not DOS_NT */
4309 #if HAVE_GETCWD
4310 int bufsize = 200;
4311 char *path = xnew (bufsize, char);
4312
4313 while (getcwd (path, bufsize) == NULL)
4314 {
4315 if (errno != ERANGE)
4316 pfatal ("getcwd");
4317 bufsize *= 2;
4318 path = xnew (bufsize, char);
4319 }
4320
4321 return path;
4322 #else /* not DOS_NT and not HAVE_GETCWD */
4323 struct linebuffer path;
4324 FILE *pipe;
4325
4326 initbuffer (&path);
4327 pipe = (FILE *) popen ("pwd 2>/dev/null", "r");
4328 if (pipe == NULL || readline_internal (&path, pipe) == 0)
4329 pfatal ("pwd");
4330 pclose (pipe);
4331
4332 return path.buffer;
4333 #endif /* not HAVE_GETCWD */
4334 #endif /* not DOS_NT */
4335 }
4336
4337 /* Return a newly allocated string containing the filename
4338 of FILE relative to the absolute directory DIR (which
4339 should end with a slash). */
4340 char *
4341 relative_filename (file, dir)
4342 char *file, *dir;
4343 {
4344 char *fp, *dp, *abs, *res;
4345
4346 /* Find the common root of file and dir. */
4347 abs = absolute_filename (file, cwd);
4348 fp = abs;
4349 dp = dir;
4350 while (*fp++ == *dp++)
4351 continue;
4352 do
4353 {
4354 fp--;
4355 dp--;
4356 }
4357 while (*fp != '/');
4358
4359 /* Build a sequence of "../" strings for the resulting relative filename. */
4360 for (dp = etags_strchr (dp + 1, '/'), res = "";
4361 dp != NULL;
4362 dp = etags_strchr (dp + 1, '/'))
4363 {
4364 res = concat (res, "../", "");
4365 }
4366
4367 /* Add the filename relative to the common root of file and dir. */
4368 res = concat (res, fp + 1, "");
4369 free (abs);
4370
4371 return res;
4372 }
4373
4374 /* Return a newly allocated string containing the
4375 absolute filename of FILE given CWD (which should
4376 end with a slash). */
4377 char *
4378 absolute_filename (file, cwd)
4379 char *file, *cwd;
4380 {
4381 char *slashp, *cp, *res;
4382
4383 if (absolutefn (file))
4384 res = concat (file, "", "");
4385 else
4386 res = concat (cwd, file, "");
4387
4388 /* Delete the "/dirname/.." and "/." substrings. */
4389 slashp = etags_strchr (res, '/');
4390 while (slashp != NULL && slashp[0] != '\0')
4391 {
4392 if (slashp[1] == '.')
4393 {
4394 if (slashp[2] == '.'
4395 && (slashp[3] == '/' || slashp[3] == '\0'))
4396 {
4397 cp = slashp;
4398 do
4399 cp--;
4400 while (cp >= res && *cp != '/');
4401 if (*cp == '/')
4402 {
4403 strcpy (cp, slashp + 3);
4404 }
4405 else /* else (cp == res) */
4406 {
4407 if (slashp[3] != '\0')
4408 strcpy (cp, slashp + 4);
4409 else
4410 return ".";
4411 }
4412 slashp = cp;
4413 continue;
4414 }
4415 else if (slashp[2] == '/' || slashp[2] == '\0')
4416 {
4417 strcpy (slashp, slashp + 2);
4418 continue;
4419 }
4420 }
4421
4422 slashp = etags_strchr (slashp + 1, '/');
4423 }
4424
4425 return res;
4426 }
4427
4428 /* Return a newly allocated string containing the absolute
4429 filename of dir where FILE resides given CWD (which should
4430 end with a slash). */
4431 char *
4432 absolute_dirname (file, cwd)
4433 char *file, *cwd;
4434 {
4435 char *slashp, *res;
4436 char save;
4437
4438 slashp = etags_strrchr (file, '/');
4439 if (slashp == NULL)
4440 return cwd;
4441 save = slashp[1];
4442 slashp[1] = '\0';
4443 res = absolute_filename (file, cwd);
4444 slashp[1] = save;
4445
4446 return res;
4447 }
4448
4449 /* Like malloc but get fatal error if memory is exhausted. */
4450 long *
4451 xmalloc (size)
4452 unsigned int size;
4453 {
4454 long *result = (long *) malloc (size);
4455 if (result == NULL)
4456 fatal ("virtual memory exhausted", 0);
4457 return result;
4458 }
4459
4460 long *
4461 xrealloc (ptr, size)
4462 char *ptr;
4463 unsigned int size;
4464 {
4465 long *result = (long *) realloc (ptr, size);
4466 if (result == NULL)
4467 fatal ("virtual memory exhausted");
4468 return result;
4469 }