1 /* Bison Grammar Scanner -*- C -*-
3 Copyright (C) 2002 Free Software Foundation, Inc.
5 This file is part of Bison, the GNU Compiler Compiler.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
23 %option debug nodefault noyywrap never-interactive
24 %option prefix="gram_" outfile="lex.yy.c"
30 #include <get-errno.h>
40 #define YY_USER_INIT \
43 scanner_cursor.file = current_file; \
44 scanner_cursor.line = 1; \
45 scanner_cursor.column = 1; \
49 /* Location of scanner cursor. */
50 boundary scanner_cursor;
52 static void adjust_location (location *, char const *, size_t);
53 #define YY_USER_ACTION adjust_location (loc, yytext, yyleng);
55 static size_t no_cr_read (FILE *, char *, size_t);
56 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
59 /* OBSTACK_FOR_STRING -- Used to store all the characters that we need to
60 keep (to construct ID, STRINGS etc.). Use the following macros to
63 Use STRING_GROW to append what has just been matched, and
64 STRING_FINISH to end the string (it puts the ending 0).
65 STRING_FINISH also stores this string in LAST_STRING, which can be
66 used, and which is used by STRING_FREE to free the last string. */
68 static struct obstack obstack_for_string;
70 /* A string representing the most recently saved token. */
71 static char *last_string;
75 obstack_grow (&obstack_for_string, yytext, yyleng)
77 #define STRING_FINISH \
79 obstack_1grow (&obstack_for_string, '\0'); \
80 last_string = obstack_finish (&obstack_for_string); \
84 obstack_free (&obstack_for_string, last_string)
87 scanner_last_string_free (void)
92 /* Within well-formed rules, RULE_LENGTH is the number of values in
93 the current rule so far, which says where to find `$0' with respect
94 to the top of the stack. It is not the same as the rule->length in
95 the case of mid rule actions.
97 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
98 static int rule_length;
100 static void handle_dollar (braced_code code_kind, char *cp, location loc);
101 static void handle_at (braced_code code_kind, char *cp, location loc);
102 static void handle_syncline (char *args);
103 static int convert_ucn_to_byte (char const *hex_text);
104 static void unexpected_end_of_file (boundary, char const *);
107 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
108 %x SC_STRING SC_CHARACTER
109 %x SC_AFTER_IDENTIFIER
110 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
111 %x SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
113 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
114 id {letter}({letter}|[0-9])*
115 directive %{letter}({letter}|[0-9]|-)*
118 /* POSIX says that a tag must be both an id and a C union member, but
119 historically almost any character is allowed in a tag. We disallow
120 NUL and newline, as this simplifies our implementation. */
123 /* Zero or more instances of backslash-newline. Following GCC, allow
124 white space between the backslash and the newline. */
125 splice (\\[ \f\t\v]*\n)*
129 /* Nesting level of the current code in braces. */
130 int braces_level IF_LINT (= 0);
132 /* Parent context state, when applicable. */
133 int context_state IF_LINT (= 0);
135 /* Location of most recent identifier, when applicable. */
136 location id_loc IF_LINT (= *loc);
138 /* Where containing code started, when applicable. */
139 boundary code_start IF_LINT (= loc->start);
141 /* Where containing comment or string or character literal started,
143 boundary token_start IF_LINT (= loc->start);
147 /*-----------------------.
148 | Scanning white space. |
149 `-----------------------*/
151 <INITIAL,SC_AFTER_IDENTIFIER>
156 "/*" token_start = loc->start; context_state = YY_START; BEGIN SC_YACC_COMMENT;
159 /* #line directives are not documented, and may be withdrawn or
160 modified in future versions of Bison. */
161 ^"#line "{int}" \"".*"\"\n" {
162 handle_syncline (yytext + sizeof "#line " - 1);
167 /*----------------------------.
168 | Scanning Bison directives. |
169 `----------------------------*/
172 "%binary" return PERCENT_NONASSOC;
173 "%debug" return PERCENT_DEBUG;
174 "%define" return PERCENT_DEFINE;
175 "%defines" return PERCENT_DEFINES;
176 "%destructor" return PERCENT_DESTRUCTOR;
177 "%dprec" return PERCENT_DPREC;
178 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
179 "%expect" return PERCENT_EXPECT;
180 "%file-prefix" return PERCENT_FILE_PREFIX;
181 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
182 "%glr-parser" return PERCENT_GLR_PARSER;
183 "%left" return PERCENT_LEFT;
184 "%locations" return PERCENT_LOCATIONS;
185 "%merge" return PERCENT_MERGE;
186 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
187 "%no"[-_]"lines" return PERCENT_NO_LINES;
188 "%nonassoc" return PERCENT_NONASSOC;
189 "%nterm" return PERCENT_NTERM;
190 "%output" return PERCENT_OUTPUT;
191 "%parse-param" return PERCENT_PARSE_PARAM;
192 "%prec" rule_length--; return PERCENT_PREC;
193 "%printer" return PERCENT_PRINTER;
194 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
195 "%right" return PERCENT_RIGHT;
196 "%lex-param" return PERCENT_LEX_PARAM;
197 "%skeleton" return PERCENT_SKELETON;
198 "%start" return PERCENT_START;
199 "%term" return PERCENT_TOKEN;
200 "%token" return PERCENT_TOKEN;
201 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
202 "%type" return PERCENT_TYPE;
203 "%union" return PERCENT_UNION;
204 "%verbose" return PERCENT_VERBOSE;
205 "%yacc" return PERCENT_YACC;
208 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
212 "|" rule_length = 0; return PIPE;
213 ";" return SEMICOLON;
216 warn_at (*loc, _("stray `,' treated as white space"));
220 val->symbol = symbol_get (yytext, *loc);
223 BEGIN SC_AFTER_IDENTIFIER;
229 num = strtoul (yytext, 0, 10);
230 if (INT_MAX < num || get_errno ())
232 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
239 /* Characters. We don't check there is only one. */
240 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
243 "\"" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_STRING;
246 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
248 /* Code in between braces. */
252 code_start = loc->start;
253 BEGIN SC_BRACED_CODE;
258 obstack_grow (&obstack_for_string, yytext + 1, yyleng - 2);
260 val->uniqstr = uniqstr_new (last_string);
266 static int percent_percent_count;
267 if (++percent_percent_count == 2)
269 code_start = loc->start;
272 return PERCENT_PERCENT;
276 complain_at (*loc, _("invalid character: %s"), quote (yytext));
281 /*-----------------------------------------------------------------.
282 | Scanning after an identifier, checking whether a colon is next. |
283 `-----------------------------------------------------------------*/
285 <SC_AFTER_IDENTIFIER>
294 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
308 /*---------------------------------------------------------------.
309 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
310 `---------------------------------------------------------------*/
314 "*/" BEGIN context_state;
316 <<EOF>> unexpected_end_of_file (token_start, "*/");
320 /*------------------------------------------------------------.
321 | Scanning a C comment. The initial `/ *' is already eaten. |
322 `------------------------------------------------------------*/
326 "*"{splice}"/" STRING_GROW; BEGIN context_state;
327 <<EOF>> unexpected_end_of_file (token_start, "*/");
331 /*--------------------------------------------------------------.
332 | Scanning a line comment. The initial `//' is already eaten. |
333 `--------------------------------------------------------------*/
337 "\n" STRING_GROW; BEGIN context_state;
338 {splice} STRING_GROW;
339 <<EOF>> BEGIN context_state;
343 /*----------------------------------------------------------------.
344 | Scanning a C string, including its escapes. The initial `"' is |
346 `----------------------------------------------------------------*/
353 loc->start = token_start;
354 val->chars = last_string;
361 <<EOF>> unexpected_end_of_file (token_start, "\"");
364 /*---------------------------------------------------------------.
365 | Scanning a C character, decoding its escapes. The initial "'" |
366 | is already eaten. |
367 `---------------------------------------------------------------*/
369 <SC_ESCAPED_CHARACTER>
372 unsigned char last_string_1;
375 loc->start = token_start;
376 val->symbol = symbol_get (last_string, *loc);
377 symbol_class_set (val->symbol, token_sym, *loc);
378 last_string_1 = last_string[1];
379 symbol_user_token_number_set (val->symbol, last_string_1, *loc);
387 <<EOF>> unexpected_end_of_file (token_start, "'");
391 /*----------------------------.
392 | Decode escaped characters. |
393 `----------------------------*/
395 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
398 unsigned long c = strtoul (yytext + 1, 0, 8);
400 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
402 obstack_1grow (&obstack_for_string, c);
405 \\x[0-9abcdefABCDEF]+ {
408 c = strtoul (yytext + 2, 0, 16);
409 if (UCHAR_MAX < c || get_errno ())
410 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
412 obstack_1grow (&obstack_for_string, c);
415 \\a obstack_1grow (&obstack_for_string, '\a');
416 \\b obstack_1grow (&obstack_for_string, '\b');
417 \\f obstack_1grow (&obstack_for_string, '\f');
418 \\n obstack_1grow (&obstack_for_string, '\n');
419 \\r obstack_1grow (&obstack_for_string, '\r');
420 \\t obstack_1grow (&obstack_for_string, '\t');
421 \\v obstack_1grow (&obstack_for_string, '\v');
423 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
424 \\("\""|"'"|"?"|"\\") obstack_1grow (&obstack_for_string, yytext[1]);
426 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
427 int c = convert_ucn_to_byte (yytext);
429 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
431 obstack_1grow (&obstack_for_string, c);
434 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
440 /*----------------------------------------------------------.
441 | Scanning a C character without decoding its escapes. The |
442 | initial "'" is already eaten. |
443 `----------------------------------------------------------*/
447 "'" STRING_GROW; BEGIN context_state;
448 \\{splice}[^$@\[\]] STRING_GROW;
449 <<EOF>> unexpected_end_of_file (token_start, "'");
453 /*----------------------------------------------------------------.
454 | Scanning a C string, without decoding its escapes. The initial |
455 | `"' is already eaten. |
456 `----------------------------------------------------------------*/
460 "\"" STRING_GROW; BEGIN context_state;
461 \\{splice}[^$@\[\]] STRING_GROW;
462 <<EOF>> unexpected_end_of_file (token_start, "\"");
466 /*---------------------------------------------------.
467 | Strings, comments etc. can be found in user code. |
468 `---------------------------------------------------*/
470 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
474 context_state = YY_START;
475 token_start = loc->start;
480 context_state = YY_START;
481 token_start = loc->start;
486 context_state = YY_START;
487 token_start = loc->start;
492 context_state = YY_START;
493 BEGIN SC_LINE_COMMENT;
498 /*---------------------------------------------------------------.
499 | Scanning some code in braces (%union and actions). The initial |
500 | "{" is already eaten. |
501 `---------------------------------------------------------------*/
505 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
506 "%"{splice}">" STRING_GROW; braces_level--;
510 if (braces_level < 0)
513 loc->start = code_start;
514 val->chars = last_string;
521 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
523 "<"{splice}"<" STRING_GROW;
525 "$"("<"{tag}">")?(-?[0-9]+|"$") { handle_dollar (current_braced_code,
527 "@"(-?[0-9]+|"$") { handle_at (current_braced_code,
530 <<EOF>> unexpected_end_of_file (code_start, "}");
534 /*--------------------------------------------------------------.
535 | Scanning some prologue: from "%{" (already scanned) to "%}". |
536 `--------------------------------------------------------------*/
542 loc->start = code_start;
543 val->chars = last_string;
548 <<EOF>> unexpected_end_of_file (code_start, "%}");
552 /*---------------------------------------------------------------.
553 | Scanning the epilogue (everything after the second "%%", which |
554 | has already been eaten). |
555 `---------------------------------------------------------------*/
561 loc->start = code_start;
562 val->chars = last_string;
569 /*----------------------------------------------------------------.
570 | By default, grow the string obstack with the input, escaping M4 |
571 | quoting characters. |
572 `----------------------------------------------------------------*/
574 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
576 \$ obstack_sgrow (&obstack_for_string, "$][");
577 \@ obstack_sgrow (&obstack_for_string, "@@");
578 \[ obstack_sgrow (&obstack_for_string, "@{");
579 \] obstack_sgrow (&obstack_for_string, "@}");
586 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
590 adjust_location (location *loc, char const *token, size_t size)
592 int line = scanner_cursor.line;
593 int column = scanner_cursor.column;
594 char const *p0 = token;
595 char const *p = token;
596 char const *lim = token + size;
598 loc->start = scanner_cursor;
600 for (p = token; p < lim; p++)
610 column += mbsnwidth (p0, p - p0, 0);
611 column += 8 - ((column - 1) & 7);
616 scanner_cursor.line = line;
617 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
619 loc->end = scanner_cursor;
623 /* Read bytes from FP into buffer BUF of size SIZE. Return the
624 number of bytes read. Remove '\r' from input, treating \r\n
625 and isolated \r as \n. */
628 no_cr_read (FILE *fp, char *buf, size_t size)
630 size_t s = fread (buf, 1, size, fp);
633 char *w = memchr (buf, '\r', s);
637 char const *lim = buf + s;
641 /* Found an '\r'. Treat it like '\n', but ignore any
642 '\n' that immediately follows. */
647 if (ch != '\n' && ungetc (ch, fp) != ch)
653 /* Copy until the next '\r'. */
659 while ((*w++ = *r++) != '\r');
670 /*------------------------------------------------------------------.
671 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
673 | Possible inputs: $[<TYPENAME>]($|integer) |
675 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
676 `------------------------------------------------------------------*/
679 handle_action_dollar (char *text, location loc)
681 const char *type_name = NULL;
684 /* Get the type name if explicit. */
697 type_name = symbol_list_n_type_name_get (current_rule, loc, 0);
698 if (!type_name && typed)
699 complain_at (loc, _("$$ of `%s' has no declared type"),
700 current_rule->sym->tag);
703 obstack_fgrow1 (&obstack_for_string,
704 "]b4_lhs_value([%s])[", type_name);
710 num = strtol (cp, 0, 10);
712 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
715 if (!type_name && n > 0)
716 type_name = symbol_list_n_type_name_get (current_rule, loc, n);
717 if (!type_name && typed)
718 complain_at (loc, _("$%d of `%s' has no declared type"),
719 n, current_rule->sym->tag);
722 obstack_fgrow3 (&obstack_for_string,
723 "]b4_rhs_value([%d], [%d], [%s])[",
724 rule_length, n, type_name);
727 complain_at (loc, _("integer out of range: %s"), quote (text));
732 /*---------------------------------------------------------------.
733 | TEXT is expected to be $$ in some code associated to a symbol: |
734 | destructor or printer. |
735 `---------------------------------------------------------------*/
738 handle_symbol_code_dollar (char *text, location loc)
742 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar[");
744 complain_at (loc, _("invalid value: %s"), quote (text));
748 /*-----------------------------------------------------------------.
749 | Dispatch onto handle_action_dollar, or handle_destructor_dollar, |
750 | depending upon CODE_KIND. |
751 `-----------------------------------------------------------------*/
754 handle_dollar (braced_code braced_code_kind, char *text, location loc)
756 switch (braced_code_kind)
758 case action_braced_code:
759 handle_action_dollar (text, loc);
762 case destructor_braced_code:
763 case printer_braced_code:
764 handle_symbol_code_dollar (text, loc);
770 /*------------------------------------------------------.
771 | TEXT is a location token (i.e., a `@...'). Output to |
772 | OBSTACK_FOR_STRING a reference to this location. |
773 `------------------------------------------------------*/
776 handle_action_at (char *text, location loc)
783 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
789 num = strtol (cp, 0, 10);
791 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
794 obstack_fgrow2 (&obstack_for_string, "]b4_rhs_location([%d], [%d])[",
798 complain_at (loc, _("integer out of range: %s"), quote (text));
803 /*---------------------------------------------------------------.
804 | TEXT is expected to be @$ in some code associated to a symbol: |
805 | destructor or printer. |
806 `---------------------------------------------------------------*/
809 handle_symbol_code_at (char *text, location loc)
813 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
815 complain_at (loc, _("invalid value: %s"), quote (text));
819 /*-------------------------------------------------------------------.
820 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
822 `-------------------------------------------------------------------*/
825 handle_at (braced_code braced_code_kind, char *text, location loc)
827 switch (braced_code_kind)
829 case action_braced_code:
830 handle_action_at (text, loc);
833 case destructor_braced_code:
834 case printer_braced_code:
835 handle_symbol_code_at (text, loc);
841 /*------------------------------------------------------------------.
842 | Convert universal character name UCN to a single-byte character, |
843 | and return that character. Return -1 if UCN does not correspond |
844 | to a single-byte character. |
845 `------------------------------------------------------------------*/
848 convert_ucn_to_byte (char const *ucn)
850 unsigned long code = strtoul (ucn + 2, 0, 16);
852 /* FIXME: Currently we assume Unicode-compatible unibyte characters
853 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
854 non-ASCII hosts we support only the portable C character set.
855 These limitations should be removed once we add support for
856 multibyte characters. */
858 if (UCHAR_MAX < code)
861 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
863 /* A non-ASCII host. Use CODE to index into a table of the C
864 basic execution character set, which is guaranteed to exist on
865 all Standard C platforms. This table also includes '$', '@',
866 and '`', which are not in the basic execution character set but
867 which are unibyte characters on all the platforms that we know
869 static signed char const table[] =
871 '\0', -1, -1, -1, -1, -1, -1, '\a',
872 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
873 -1, -1, -1, -1, -1, -1, -1, -1,
874 -1, -1, -1, -1, -1, -1, -1, -1,
875 ' ', '!', '"', '#', '$', '%', '&', '\'',
876 '(', ')', '*', '+', ',', '-', '.', '/',
877 '0', '1', '2', '3', '4', '5', '6', '7',
878 '8', '9', ':', ';', '<', '=', '>', '?',
879 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
880 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
881 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
882 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
883 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
884 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
885 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
886 'x', 'y', 'z', '{', '|', '}', '~'
889 code = code < sizeof table ? table[code] : -1;
897 /*----------------------------------------------------------------.
898 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
899 `----------------------------------------------------------------*/
902 handle_syncline (char *args)
904 int lineno = strtol (args, &args, 10);
905 const char *file = NULL;
906 file = strchr (args, '"') + 1;
907 *strchr (file, '"') = 0;
908 scanner_cursor.file = current_file = xstrdup (file);
909 scanner_cursor.line = lineno;
910 scanner_cursor.column = 1;
914 /*------------------------------------------------------------------------.
915 | Report an unexpected EOF in a token or comment starting at START. |
916 | An end of file was encountered and the expected TOKEN_END was missing. |
917 | After reporting the problem, pretend that TOKEN_END was found. |
918 `------------------------------------------------------------------------*/
921 unexpected_end_of_file (boundary start, char const *token_end)
923 size_t i = strlen (token_end);
927 loc.end = scanner_cursor;
928 complain_at (loc, _("missing `%s' at end of file"), token_end);
930 /* Adjust scanner cursor so that any later message does not count
931 the characters about to be inserted. */
932 scanner_cursor.column -= i;
935 unput (token_end[--i]);
939 /*-------------------------.
940 | Initialize the scanner. |
941 `-------------------------*/
944 scanner_initialize (void)
946 obstack_init (&obstack_for_string);
950 /*-----------------------------------------------.
951 | Free all the memory allocated to the scanner. |
952 `-----------------------------------------------*/
957 obstack_free (&obstack_for_string, 0);
958 /* Reclaim Flex's buffers. */
959 yy_delete_buffer (YY_CURRENT_BUFFER);