1 /* Bison Grammar Scanner -*- C -*-
2 Copyright (C) 2002 Free Software Foundation, Inc.
4 This file is part of Bison, the GNU Compiler Compiler.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 %option debug nodefault noyywrap never-interactive
23 %option prefix="gram_" outfile="lex.yy.c"
29 #include <get-errno.h>
39 #define YY_USER_INIT \
42 scanner_cursor.file = current_file; \
43 scanner_cursor.line = 1; \
44 scanner_cursor.column = 1; \
48 /* Location of scanner cursor. */
49 boundary scanner_cursor;
51 static void adjust_location (location *, char const *, size_t);
52 #define YY_USER_ACTION adjust_location (loc, yytext, yyleng);
54 static size_t no_cr_read (FILE *, char *, size_t);
55 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
58 /* OBSTACK_FOR_STRING -- Used to store all the characters that we need to
59 keep (to construct ID, STRINGS etc.). Use the following macros to
62 Use STRING_GROW to append what has just been matched, and
63 STRING_FINISH to end the string (it puts the ending 0).
64 STRING_FINISH also stores this string in LAST_STRING, which can be
65 used, and which is used by STRING_FREE to free the last string. */
67 static struct obstack obstack_for_string;
69 /* A string representing the most recently saved token. */
70 static char *last_string;
74 obstack_grow (&obstack_for_string, yytext, yyleng)
76 #define STRING_FINISH \
78 obstack_1grow (&obstack_for_string, '\0'); \
79 last_string = obstack_finish (&obstack_for_string); \
83 obstack_free (&obstack_for_string, last_string)
86 scanner_last_string_free (void)
91 /* Within well-formed rules, RULE_LENGTH is the number of values in
92 the current rule so far, which says where to find `$0' with respect
93 to the top of the stack. It is not the same as the rule->length in
94 the case of mid rule actions.
96 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
97 static int rule_length;
99 static void handle_dollar (braced_code code_kind, char *cp, location loc);
100 static void handle_at (braced_code code_kind, char *cp, location loc);
101 static void handle_syncline (char *args);
102 static int convert_ucn_to_byte (char const *hex_text);
103 static void unexpected_end_of_file (boundary, char const *);
106 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
107 %x SC_STRING SC_CHARACTER
108 %x SC_AFTER_IDENTIFIER
109 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
110 %x SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
112 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
113 id {letter}({letter}|[0-9])*
114 directive %{letter}({letter}|[0-9]|-)*
117 /* POSIX says that a tag must be both an id and a C union member, but
118 historically almost any character is allowed in a tag. We disallow
119 NUL and newline, as this simplifies our implementation. */
122 /* Zero or more instances of backslash-newline. Following GCC, allow
123 white space between the backslash and the newline. */
124 splice (\\[ \f\t\v]*\n)*
128 /* Nesting level of the current code in braces. */
129 int braces_level IF_LINT (= 0);
131 /* Parent context state, when applicable. */
132 int context_state IF_LINT (= 0);
134 /* Location of most recent identifier, when applicable. */
135 location id_loc IF_LINT (= *loc);
137 /* Where containing code started, when applicable. */
138 boundary code_start IF_LINT (= loc->start);
140 /* Where containing comment or string or character literal started,
142 boundary token_start IF_LINT (= loc->start);
146 /*-----------------------.
147 | Scanning white space. |
148 `-----------------------*/
150 <INITIAL,SC_AFTER_IDENTIFIER>
155 "/*" token_start = loc->start; context_state = YY_START; BEGIN SC_YACC_COMMENT;
158 /* #line directives are not documented, and may be withdrawn or
159 modified in future versions of Bison. */
160 ^"#line "{int}" \"".*"\"\n" {
161 handle_syncline (yytext + sizeof "#line " - 1);
166 /*----------------------------.
167 | Scanning Bison directives. |
168 `----------------------------*/
171 "%binary" return PERCENT_NONASSOC;
172 "%debug" return PERCENT_DEBUG;
173 "%define" return PERCENT_DEFINE;
174 "%defines" return PERCENT_DEFINES;
175 "%destructor" return PERCENT_DESTRUCTOR;
176 "%dprec" return PERCENT_DPREC;
177 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
178 "%expect" return PERCENT_EXPECT;
179 "%file-prefix" return PERCENT_FILE_PREFIX;
180 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
181 "%glr-parser" return PERCENT_GLR_PARSER;
182 "%left" return PERCENT_LEFT;
183 "%locations" return PERCENT_LOCATIONS;
184 "%merge" return PERCENT_MERGE;
185 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
186 "%no"[-_]"lines" return PERCENT_NO_LINES;
187 "%nonassoc" return PERCENT_NONASSOC;
188 "%nterm" return PERCENT_NTERM;
189 "%output" return PERCENT_OUTPUT;
190 "%parse-param" return PERCENT_PARSE_PARAM;
191 "%prec" rule_length--; return PERCENT_PREC;
192 "%printer" return PERCENT_PRINTER;
193 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
194 "%right" return PERCENT_RIGHT;
195 "%lex-param" return PERCENT_LEX_PARAM;
196 "%skeleton" return PERCENT_SKELETON;
197 "%start" return PERCENT_START;
198 "%term" return PERCENT_TOKEN;
199 "%token" return PERCENT_TOKEN;
200 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
201 "%type" return PERCENT_TYPE;
202 "%union" return PERCENT_UNION;
203 "%verbose" return PERCENT_VERBOSE;
204 "%yacc" return PERCENT_YACC;
207 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
211 "|" rule_length = 0; return PIPE;
212 ";" return SEMICOLON;
215 warn_at (*loc, _("stray `,' treated as white space"));
219 val->symbol = symbol_get (yytext, *loc);
222 BEGIN SC_AFTER_IDENTIFIER;
228 num = strtoul (yytext, 0, 10);
229 if (INT_MAX < num || get_errno ())
231 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
238 /* Characters. We don't check there is only one. */
239 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
242 "\"" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_STRING;
245 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
247 /* Code in between braces. */
251 code_start = loc->start;
252 BEGIN SC_BRACED_CODE;
257 obstack_grow (&obstack_for_string, yytext + 1, yyleng - 2);
259 val->uniqstr = uniqstr_new (last_string);
265 static int percent_percent_count;
266 if (++percent_percent_count == 2)
268 code_start = loc->start;
271 return PERCENT_PERCENT;
275 complain_at (*loc, _("invalid character: %s"), quote (yytext));
280 /*-----------------------------------------------------------------.
281 | Scanning after an identifier, checking whether a colon is next. |
282 `-----------------------------------------------------------------*/
284 <SC_AFTER_IDENTIFIER>
293 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
307 /*---------------------------------------------------------------.
308 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
309 `---------------------------------------------------------------*/
313 "*/" BEGIN context_state;
315 <<EOF>> unexpected_end_of_file (token_start, "*/");
319 /*------------------------------------------------------------.
320 | Scanning a C comment. The initial `/ *' is already eaten. |
321 `------------------------------------------------------------*/
325 "*"{splice}"/" STRING_GROW; BEGIN context_state;
326 <<EOF>> unexpected_end_of_file (token_start, "*/");
330 /*--------------------------------------------------------------.
331 | Scanning a line comment. The initial `//' is already eaten. |
332 `--------------------------------------------------------------*/
336 "\n" STRING_GROW; BEGIN context_state;
337 {splice} STRING_GROW;
338 <<EOF>> BEGIN context_state;
342 /*----------------------------------------------------------------.
343 | Scanning a C string, including its escapes. The initial `"' is |
345 `----------------------------------------------------------------*/
352 loc->start = token_start;
353 val->chars = last_string;
360 <<EOF>> unexpected_end_of_file (token_start, "\"");
363 /*---------------------------------------------------------------.
364 | Scanning a C character, decoding its escapes. The initial "'" |
365 | is already eaten. |
366 `---------------------------------------------------------------*/
368 <SC_ESCAPED_CHARACTER>
373 loc->start = token_start;
374 val->symbol = symbol_get (last_string, *loc);
375 symbol_class_set (val->symbol, token_sym, *loc);
376 symbol_user_token_number_set (val->symbol,
377 (unsigned char) last_string[1], *loc);
385 <<EOF>> unexpected_end_of_file (token_start, "'");
389 /*----------------------------.
390 | Decode escaped characters. |
391 `----------------------------*/
393 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
396 unsigned long c = strtoul (yytext + 1, 0, 8);
398 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
400 obstack_1grow (&obstack_for_string, c);
403 \\x[0-9abcdefABCDEF]+ {
406 c = strtoul (yytext + 2, 0, 16);
407 if (UCHAR_MAX < c || get_errno ())
408 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
410 obstack_1grow (&obstack_for_string, c);
413 \\a obstack_1grow (&obstack_for_string, '\a');
414 \\b obstack_1grow (&obstack_for_string, '\b');
415 \\f obstack_1grow (&obstack_for_string, '\f');
416 \\n obstack_1grow (&obstack_for_string, '\n');
417 \\r obstack_1grow (&obstack_for_string, '\r');
418 \\t obstack_1grow (&obstack_for_string, '\t');
419 \\v obstack_1grow (&obstack_for_string, '\v');
421 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
422 \\("\""|"'"|"?"|"\\") obstack_1grow (&obstack_for_string, yytext[1]);
424 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
425 int c = convert_ucn_to_byte (yytext);
427 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
429 obstack_1grow (&obstack_for_string, c);
432 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
438 /*----------------------------------------------------------.
439 | Scanning a C character without decoding its escapes. The |
440 | initial "'" is already eaten. |
441 `----------------------------------------------------------*/
445 "'" STRING_GROW; BEGIN context_state;
446 \\{splice}[^$@\[\]] STRING_GROW;
447 <<EOF>> unexpected_end_of_file (token_start, "'");
451 /*----------------------------------------------------------------.
452 | Scanning a C string, without decoding its escapes. The initial |
453 | `"' is already eaten. |
454 `----------------------------------------------------------------*/
458 "\"" STRING_GROW; BEGIN context_state;
459 \\{splice}[^$@\[\]] STRING_GROW;
460 <<EOF>> unexpected_end_of_file (token_start, "\"");
464 /*---------------------------------------------------.
465 | Strings, comments etc. can be found in user code. |
466 `---------------------------------------------------*/
468 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
472 context_state = YY_START;
473 token_start = loc->start;
478 context_state = YY_START;
479 token_start = loc->start;
484 context_state = YY_START;
485 token_start = loc->start;
490 context_state = YY_START;
491 BEGIN SC_LINE_COMMENT;
496 /*---------------------------------------------------------------.
497 | Scanning some code in braces (%union and actions). The initial |
498 | "{" is already eaten. |
499 `---------------------------------------------------------------*/
503 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
504 "%"{splice}">" STRING_GROW; braces_level--;
508 if (braces_level < 0)
511 loc->start = code_start;
512 val->chars = last_string;
519 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
521 "<"{splice}"<" STRING_GROW;
523 "$"("<"{tag}">")?(-?[0-9]+|"$") { handle_dollar (current_braced_code,
525 "@"(-?[0-9]+|"$") { handle_at (current_braced_code,
528 <<EOF>> unexpected_end_of_file (code_start, "}");
532 /*--------------------------------------------------------------.
533 | Scanning some prologue: from "%{" (already scanned) to "%}". |
534 `--------------------------------------------------------------*/
540 loc->start = code_start;
541 val->chars = last_string;
546 <<EOF>> unexpected_end_of_file (code_start, "%}");
550 /*---------------------------------------------------------------.
551 | Scanning the epilogue (everything after the second "%%", which |
552 | has already been eaten). |
553 `---------------------------------------------------------------*/
559 loc->start = code_start;
560 val->chars = last_string;
567 /*----------------------------------------------------------------.
568 | By default, grow the string obstack with the input, escaping M4 |
569 | quoting characters. |
570 `----------------------------------------------------------------*/
572 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
574 \$ obstack_sgrow (&obstack_for_string, "$][");
575 \@ obstack_sgrow (&obstack_for_string, "@@");
576 \[ obstack_sgrow (&obstack_for_string, "@{");
577 \] obstack_sgrow (&obstack_for_string, "@}");
584 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
588 adjust_location (location *loc, char const *token, size_t size)
590 int line = scanner_cursor.line;
591 int column = scanner_cursor.column;
592 char const *p0 = token;
593 char const *p = token;
594 char const *lim = token + size;
596 loc->start = scanner_cursor;
598 for (p = token; p < lim; p++)
608 column += mbsnwidth (p0, p - p0, 0);
609 column += 8 - ((column - 1) & 7);
614 scanner_cursor.line = line;
615 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
617 loc->end = scanner_cursor;
621 /* Read bytes from FP into buffer BUF of size SIZE. Return the
622 number of bytes read. Remove '\r' from input, treating \r\n
623 and isolated \r as \n. */
626 no_cr_read (FILE *fp, char *buf, size_t size)
628 size_t s = fread (buf, 1, size, fp);
631 char *w = memchr (buf, '\r', s);
635 char const *lim = buf + s;
639 /* Found an '\r'. Treat it like '\n', but ignore any
640 '\n' that immediately follows. */
645 if (ch != '\n' && ungetc (ch, fp) != ch)
651 /* Copy until the next '\r'. */
657 while ((*w++ = *r++) != '\r');
668 /*------------------------------------------------------------------.
669 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
671 | Possible inputs: $[<TYPENAME>]($|integer) |
673 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
674 `------------------------------------------------------------------*/
677 handle_action_dollar (char *text, location loc)
679 const char *type_name = NULL;
682 /* Get the type name if explicit. */
695 type_name = symbol_list_n_type_name_get (current_rule, loc, 0);
696 if (!type_name && typed)
697 complain_at (loc, _("$$ of `%s' has no declared type"),
698 current_rule->sym->tag);
701 obstack_fgrow1 (&obstack_for_string,
702 "]b4_lhs_value([%s])[", type_name);
708 num = strtol (cp, 0, 10);
710 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
713 if (!type_name && n > 0)
714 type_name = symbol_list_n_type_name_get (current_rule, loc, n);
715 if (!type_name && typed)
716 complain_at (loc, _("$%d of `%s' has no declared type"),
717 n, current_rule->sym->tag);
720 obstack_fgrow3 (&obstack_for_string,
721 "]b4_rhs_value([%d], [%d], [%s])[",
722 rule_length, n, type_name);
725 complain_at (loc, _("integer out of range: %s"), quote (text));
730 /*---------------------------------------------------------------.
731 | TEXT is expected to be $$ in some code associated to a symbol: |
732 | destructor or printer. |
733 `---------------------------------------------------------------*/
736 handle_symbol_code_dollar (char *text, location loc)
740 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar[");
742 complain_at (loc, _("invalid value: %s"), quote (text));
746 /*-----------------------------------------------------------------.
747 | Dispatch onto handle_action_dollar, or handle_destructor_dollar, |
748 | depending upon CODE_KIND. |
749 `-----------------------------------------------------------------*/
752 handle_dollar (braced_code braced_code_kind, char *text, location loc)
754 switch (braced_code_kind)
756 case action_braced_code:
757 handle_action_dollar (text, loc);
760 case destructor_braced_code:
761 case printer_braced_code:
762 handle_symbol_code_dollar (text, loc);
768 /*------------------------------------------------------.
769 | TEXT is a location token (i.e., a `@...'). Output to |
770 | OBSTACK_FOR_STRING a reference to this location. |
771 `------------------------------------------------------*/
774 handle_action_at (char *text, location loc)
781 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
787 num = strtol (cp, 0, 10);
789 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
792 obstack_fgrow2 (&obstack_for_string, "]b4_rhs_location([%d], [%d])[",
796 complain_at (loc, _("integer out of range: %s"), quote (text));
801 /*---------------------------------------------------------------.
802 | TEXT is expected to be @$ in some code associated to a symbol: |
803 | destructor or printer. |
804 `---------------------------------------------------------------*/
807 handle_symbol_code_at (char *text, location loc)
811 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
813 complain_at (loc, _("invalid value: %s"), quote (text));
817 /*-------------------------------------------------------------------.
818 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
820 `-------------------------------------------------------------------*/
823 handle_at (braced_code braced_code_kind, char *text, location loc)
825 switch (braced_code_kind)
827 case action_braced_code:
828 handle_action_at (text, loc);
831 case destructor_braced_code:
832 case printer_braced_code:
833 handle_symbol_code_at (text, loc);
839 /*------------------------------------------------------------------.
840 | Convert universal character name UCN to a single-byte character, |
841 | and return that character. Return -1 if UCN does not correspond |
842 | to a single-byte character. |
843 `------------------------------------------------------------------*/
846 convert_ucn_to_byte (char const *ucn)
848 unsigned long code = strtoul (ucn + 2, 0, 16);
850 /* FIXME: Currently we assume Unicode-compatible unibyte characters
851 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
852 non-ASCII hosts we support only the portable C character set.
853 These limitations should be removed once we add support for
854 multibyte characters. */
856 if (UCHAR_MAX < code)
859 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
861 /* A non-ASCII host. Use CODE to index into a table of the C
862 basic execution character set, which is guaranteed to exist on
863 all Standard C platforms. This table also includes '$', '@',
864 and '`', which are not in the basic execution character set but
865 which are unibyte characters on all the platforms that we know
867 static signed char const table[] =
869 '\0', -1, -1, -1, -1, -1, -1, '\a',
870 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
871 -1, -1, -1, -1, -1, -1, -1, -1,
872 -1, -1, -1, -1, -1, -1, -1, -1,
873 ' ', '!', '"', '#', '$', '%', '&', '\'',
874 '(', ')', '*', '+', ',', '-', '.', '/',
875 '0', '1', '2', '3', '4', '5', '6', '7',
876 '8', '9', ':', ';', '<', '=', '>', '?',
877 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
878 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
879 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
880 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
881 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
882 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
883 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
884 'x', 'y', 'z', '{', '|', '}', '~'
887 code = code < sizeof table ? table[code] : -1;
895 /*----------------------------------------------------------------.
896 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
897 `----------------------------------------------------------------*/
900 handle_syncline (char *args)
902 int lineno = strtol (args, &args, 10);
903 const char *file = NULL;
904 file = strchr (args, '"') + 1;
905 *strchr (file, '"') = 0;
906 scanner_cursor.file = current_file = xstrdup (file);
907 scanner_cursor.line = lineno;
908 scanner_cursor.column = 1;
912 /*------------------------------------------------------------------------.
913 | Report an unexpected EOF in a token or comment starting at START. |
914 | An end of file was encountered and the expected TOKEN_END was missing. |
915 | After reporting the problem, pretend that TOKEN_END was found. |
916 `------------------------------------------------------------------------*/
919 unexpected_end_of_file (boundary start, char const *token_end)
921 size_t i = strlen (token_end);
925 loc.end = scanner_cursor;
926 complain_at (loc, _("missing `%s' at end of file"), token_end);
928 /* Adjust scanner cursor so that any later message does not count
929 the characters about to be inserted. */
930 scanner_cursor.column -= i;
933 unput (token_end[--i]);
937 /*-------------------------.
938 | Initialize the scanner. |
939 `-------------------------*/
942 scanner_initialize (void)
944 obstack_init (&obstack_for_string);
948 /*-----------------------------------------------.
949 | Free all the memory allocated to the scanner. |
950 `-----------------------------------------------*/
955 obstack_free (&obstack_for_string, 0);
956 /* Reclaim Flex's buffers. */
957 yy_delete_buffer (YY_CURRENT_BUFFER);