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 (int token_type, char *cp, location loc);
101 static void handle_at (int token_type, 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_PRE_CODE 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 /* Token type to return, when applicable. */
136 int token_type IF_LINT (= 0);
138 /* Location of most recent identifier, when applicable. */
139 location id_loc IF_LINT (= *loc);
141 /* Where containing code started, when applicable. */
142 boundary code_start IF_LINT (= loc->start);
144 /* Where containing comment or string or character literal started,
146 boundary token_start IF_LINT (= loc->start);
150 /*-----------------------.
151 | Scanning white space. |
152 `-----------------------*/
154 <INITIAL,SC_AFTER_IDENTIFIER,SC_PRE_CODE>
159 "/*" token_start = loc->start; context_state = YY_START; BEGIN SC_YACC_COMMENT;
162 /* #line directives are not documented, and may be withdrawn or
163 modified in future versions of Bison. */
164 ^"#line "{int}" \"".*"\"\n" {
165 handle_syncline (yytext + sizeof "#line " - 1);
170 /*----------------------------.
171 | Scanning Bison directives. |
172 `----------------------------*/
175 "%binary" return PERCENT_NONASSOC;
176 "%debug" return PERCENT_DEBUG;
177 "%define" return PERCENT_DEFINE;
178 "%defines" return PERCENT_DEFINES;
179 "%destructor" token_type = PERCENT_DESTRUCTOR; BEGIN SC_PRE_CODE;
180 "%dprec" return PERCENT_DPREC;
181 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
182 "%expect" return PERCENT_EXPECT;
183 "%file-prefix" return PERCENT_FILE_PREFIX;
184 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
185 "%glr-parser" return PERCENT_GLR_PARSER;
186 "%left" return PERCENT_LEFT;
187 "%lex-param" token_type = PERCENT_LEX_PARAM; BEGIN SC_PRE_CODE;
188 "%locations" return PERCENT_LOCATIONS;
189 "%merge" return PERCENT_MERGE;
190 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
191 "%no"[-_]"lines" return PERCENT_NO_LINES;
192 "%nonassoc" return PERCENT_NONASSOC;
193 "%nterm" return PERCENT_NTERM;
194 "%output" return PERCENT_OUTPUT;
195 "%parse-param" token_type = PERCENT_PARSE_PARAM; BEGIN SC_PRE_CODE;
196 "%prec" rule_length--; return PERCENT_PREC;
197 "%printer" token_type = PERCENT_PRINTER; BEGIN SC_PRE_CODE;
198 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
199 "%right" return PERCENT_RIGHT;
200 "%skeleton" return PERCENT_SKELETON;
201 "%start" return PERCENT_START;
202 "%term" return PERCENT_TOKEN;
203 "%token" return PERCENT_TOKEN;
204 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
205 "%type" return PERCENT_TYPE;
206 "%union" token_type = PERCENT_UNION; BEGIN SC_PRE_CODE;
207 "%verbose" return PERCENT_VERBOSE;
208 "%yacc" return PERCENT_YACC;
211 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
215 "|" rule_length = 0; return PIPE;
216 ";" return SEMICOLON;
219 warn_at (*loc, _("stray `,' treated as white space"));
223 val->symbol = symbol_get (yytext, *loc);
226 BEGIN SC_AFTER_IDENTIFIER;
232 num = strtoul (yytext, 0, 10);
233 if (INT_MAX < num || get_errno ())
235 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
242 /* Characters. We don't check there is only one. */
243 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
246 "\"" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_STRING;
249 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
251 /* Code in between braces. */
254 token_type = BRACED_CODE;
256 code_start = loc->start;
257 BEGIN SC_BRACED_CODE;
262 obstack_grow (&obstack_for_string, yytext + 1, yyleng - 2);
264 val->uniqstr = uniqstr_new (last_string);
270 static int percent_percent_count;
271 if (++percent_percent_count == 2)
273 code_start = loc->start;
276 return PERCENT_PERCENT;
280 complain_at (*loc, _("invalid character: %s"), quote (yytext));
285 /*-----------------------------------------------------------------.
286 | Scanning after an identifier, checking whether a colon is next. |
287 `-----------------------------------------------------------------*/
289 <SC_AFTER_IDENTIFIER>
298 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
312 /*---------------------------------------------------------------.
313 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
314 `---------------------------------------------------------------*/
318 "*/" BEGIN context_state;
320 <<EOF>> unexpected_end_of_file (token_start, "*/");
324 /*------------------------------------------------------------.
325 | Scanning a C comment. The initial `/ *' is already eaten. |
326 `------------------------------------------------------------*/
330 "*"{splice}"/" STRING_GROW; BEGIN context_state;
331 <<EOF>> unexpected_end_of_file (token_start, "*/");
335 /*--------------------------------------------------------------.
336 | Scanning a line comment. The initial `//' is already eaten. |
337 `--------------------------------------------------------------*/
341 "\n" STRING_GROW; BEGIN context_state;
342 {splice} STRING_GROW;
343 <<EOF>> BEGIN context_state;
347 /*----------------------------------------------------------------.
348 | Scanning a C string, including its escapes. The initial `"' is |
350 `----------------------------------------------------------------*/
357 loc->start = token_start;
358 val->chars = last_string;
365 <<EOF>> unexpected_end_of_file (token_start, "\"");
368 /*---------------------------------------------------------------.
369 | Scanning a C character, decoding its escapes. The initial "'" |
370 | is already eaten. |
371 `---------------------------------------------------------------*/
373 <SC_ESCAPED_CHARACTER>
376 unsigned char last_string_1;
379 loc->start = token_start;
380 val->symbol = symbol_get (last_string, *loc);
381 symbol_class_set (val->symbol, token_sym, *loc);
382 last_string_1 = last_string[1];
383 symbol_user_token_number_set (val->symbol, last_string_1, *loc);
391 <<EOF>> unexpected_end_of_file (token_start, "'");
395 /*----------------------------.
396 | Decode escaped characters. |
397 `----------------------------*/
399 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
402 unsigned long c = strtoul (yytext + 1, 0, 8);
404 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
406 obstack_1grow (&obstack_for_string, c);
409 \\x[0-9abcdefABCDEF]+ {
412 c = strtoul (yytext + 2, 0, 16);
413 if (UCHAR_MAX < c || get_errno ())
414 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
416 obstack_1grow (&obstack_for_string, c);
419 \\a obstack_1grow (&obstack_for_string, '\a');
420 \\b obstack_1grow (&obstack_for_string, '\b');
421 \\f obstack_1grow (&obstack_for_string, '\f');
422 \\n obstack_1grow (&obstack_for_string, '\n');
423 \\r obstack_1grow (&obstack_for_string, '\r');
424 \\t obstack_1grow (&obstack_for_string, '\t');
425 \\v obstack_1grow (&obstack_for_string, '\v');
427 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
428 \\("\""|"'"|"?"|"\\") obstack_1grow (&obstack_for_string, yytext[1]);
430 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
431 int c = convert_ucn_to_byte (yytext);
433 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
435 obstack_1grow (&obstack_for_string, c);
438 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
444 /*----------------------------------------------------------.
445 | Scanning a C character without decoding its escapes. The |
446 | initial "'" is already eaten. |
447 `----------------------------------------------------------*/
451 "'" STRING_GROW; BEGIN context_state;
452 \\{splice}[^$@\[\]] STRING_GROW;
453 <<EOF>> unexpected_end_of_file (token_start, "'");
457 /*----------------------------------------------------------------.
458 | Scanning a C string, without decoding its escapes. The initial |
459 | `"' is already eaten. |
460 `----------------------------------------------------------------*/
464 "\"" STRING_GROW; BEGIN context_state;
465 \\{splice}[^$@\[\]] STRING_GROW;
466 <<EOF>> unexpected_end_of_file (token_start, "\"");
470 /*---------------------------------------------------.
471 | Strings, comments etc. can be found in user code. |
472 `---------------------------------------------------*/
474 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
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 token_start = loc->start;
496 context_state = YY_START;
497 BEGIN SC_LINE_COMMENT;
502 /*---------------------------------------------------------------.
503 | Scanning after %union etc., possibly followed by white space. |
504 | For %union only, allow arbitrary C code to appear before the |
505 | following brace, as an extension to POSIX. |
506 `---------------------------------------------------------------*/
511 bool valid = yytext[0] == '{' || token_type == PERCENT_UNION;
512 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
518 code_start = loc->start;
519 BEGIN SC_BRACED_CODE;
523 complain_at (*loc, _("missing `{' in `%s'"),
524 token_name (token_type));
525 obstack_sgrow (&obstack_for_string, "{}");
527 val->chars = last_string;
535 /*---------------------------------------------------------------.
536 | Scanning some code in braces (%union and actions). The initial |
537 | "{" is already eaten. |
538 `---------------------------------------------------------------*/
542 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
543 "%"{splice}">" STRING_GROW; braces_level--;
547 if (braces_level < 0)
551 loc->start = code_start;
552 val->chars = last_string;
558 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
560 "<"{splice}"<" STRING_GROW;
562 "$"("<"{tag}">")?(-?[0-9]+|"$") handle_dollar (token_type, yytext, *loc);
563 "@"(-?[0-9]+|"$") handle_at (token_type, yytext, *loc);
565 <<EOF>> unexpected_end_of_file (code_start, "}");
569 /*--------------------------------------------------------------.
570 | Scanning some prologue: from "%{" (already scanned) to "%}". |
571 `--------------------------------------------------------------*/
577 loc->start = code_start;
578 val->chars = last_string;
583 <<EOF>> unexpected_end_of_file (code_start, "%}");
587 /*---------------------------------------------------------------.
588 | Scanning the epilogue (everything after the second "%%", which |
589 | has already been eaten). |
590 `---------------------------------------------------------------*/
596 loc->start = code_start;
597 val->chars = last_string;
604 /*----------------------------------------------------------------.
605 | By default, grow the string obstack with the input, escaping M4 |
606 | quoting characters. |
607 `----------------------------------------------------------------*/
609 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
611 \$ obstack_sgrow (&obstack_for_string, "$][");
612 \@ obstack_sgrow (&obstack_for_string, "@@");
613 \[ obstack_sgrow (&obstack_for_string, "@{");
614 \] obstack_sgrow (&obstack_for_string, "@}");
621 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
625 adjust_location (location *loc, char const *token, size_t size)
627 int line = scanner_cursor.line;
628 int column = scanner_cursor.column;
629 char const *p0 = token;
630 char const *p = token;
631 char const *lim = token + size;
633 loc->start = scanner_cursor;
635 for (p = token; p < lim; p++)
645 column += mbsnwidth (p0, p - p0, 0);
646 column += 8 - ((column - 1) & 7);
651 scanner_cursor.line = line;
652 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
654 loc->end = scanner_cursor;
658 /* Read bytes from FP into buffer BUF of size SIZE. Return the
659 number of bytes read. Remove '\r' from input, treating \r\n
660 and isolated \r as \n. */
663 no_cr_read (FILE *fp, char *buf, size_t size)
665 size_t s = fread (buf, 1, size, fp);
668 char *w = memchr (buf, '\r', s);
672 char const *lim = buf + s;
676 /* Found an '\r'. Treat it like '\n', but ignore any
677 '\n' that immediately follows. */
682 if (ch != '\n' && ungetc (ch, fp) != ch)
688 /* Copy until the next '\r'. */
694 while ((*w++ = *r++) != '\r');
705 /*------------------------------------------------------------------.
706 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
708 | Possible inputs: $[<TYPENAME>]($|integer) |
710 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
711 `------------------------------------------------------------------*/
714 handle_action_dollar (char *text, location loc)
716 const char *type_name = NULL;
722 /* Get the type name if explicit. */
735 type_name = symbol_list_n_type_name_get (current_rule, loc, 0);
736 if (!type_name && typed)
737 complain_at (loc, _("$$ of `%s' has no declared type"),
738 current_rule->sym->tag);
741 obstack_fgrow1 (&obstack_for_string,
742 "]b4_lhs_value([%s])[", type_name);
748 num = strtol (cp, 0, 10);
750 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
753 if (!type_name && n > 0)
754 type_name = symbol_list_n_type_name_get (current_rule, loc, n);
755 if (!type_name && typed)
756 complain_at (loc, _("$%d of `%s' has no declared type"),
757 n, current_rule->sym->tag);
760 obstack_fgrow3 (&obstack_for_string,
761 "]b4_rhs_value([%d], [%d], [%s])[",
762 rule_length, n, type_name);
765 complain_at (loc, _("integer out of range: %s"), quote (text));
772 /*-----------------------------------------------------------------.
773 | Dispatch onto handle_action_dollar, or handle_destructor_dollar, |
774 | depending upon TOKEN_TYPE. |
775 `-----------------------------------------------------------------*/
778 handle_dollar (int token_type, char *text, location loc)
783 if (handle_action_dollar (text, loc))
787 case PERCENT_DESTRUCTOR:
788 case PERCENT_PRINTER:
791 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar[");
800 complain_at (loc, _("invalid value: %s"), quote (text));
804 /*------------------------------------------------------.
805 | TEXT is a location token (i.e., a `@...'). Output to |
806 | OBSTACK_FOR_STRING a reference to this location. |
807 `------------------------------------------------------*/
810 handle_action_at (char *text, location loc)
819 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
824 num = strtol (cp, 0, 10);
826 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
829 obstack_fgrow2 (&obstack_for_string, "]b4_rhs_location([%d], [%d])[",
833 complain_at (loc, _("integer out of range: %s"), quote (text));
840 /*-------------------------------------------------------------------.
841 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
843 `-------------------------------------------------------------------*/
846 handle_at (int token_type, char *text, location loc)
851 handle_action_at (text, loc);
854 case PERCENT_DESTRUCTOR:
855 case PERCENT_PRINTER:
858 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
867 complain_at (loc, _("invalid value: %s"), quote (text));
871 /*------------------------------------------------------------------.
872 | Convert universal character name UCN to a single-byte character, |
873 | and return that character. Return -1 if UCN does not correspond |
874 | to a single-byte character. |
875 `------------------------------------------------------------------*/
878 convert_ucn_to_byte (char const *ucn)
880 unsigned long code = strtoul (ucn + 2, 0, 16);
882 /* FIXME: Currently we assume Unicode-compatible unibyte characters
883 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
884 non-ASCII hosts we support only the portable C character set.
885 These limitations should be removed once we add support for
886 multibyte characters. */
888 if (UCHAR_MAX < code)
891 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
893 /* A non-ASCII host. Use CODE to index into a table of the C
894 basic execution character set, which is guaranteed to exist on
895 all Standard C platforms. This table also includes '$', '@',
896 and '`', which are not in the basic execution character set but
897 which are unibyte characters on all the platforms that we know
899 static signed char const table[] =
901 '\0', -1, -1, -1, -1, -1, -1, '\a',
902 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
903 -1, -1, -1, -1, -1, -1, -1, -1,
904 -1, -1, -1, -1, -1, -1, -1, -1,
905 ' ', '!', '"', '#', '$', '%', '&', '\'',
906 '(', ')', '*', '+', ',', '-', '.', '/',
907 '0', '1', '2', '3', '4', '5', '6', '7',
908 '8', '9', ':', ';', '<', '=', '>', '?',
909 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
910 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
911 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
912 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
913 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
914 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
915 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
916 'x', 'y', 'z', '{', '|', '}', '~'
919 code = code < sizeof table ? table[code] : -1;
927 /*----------------------------------------------------------------.
928 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
929 `----------------------------------------------------------------*/
932 handle_syncline (char *args)
934 int lineno = strtol (args, &args, 10);
935 const char *file = NULL;
936 file = strchr (args, '"') + 1;
937 *strchr (file, '"') = 0;
938 scanner_cursor.file = current_file = xstrdup (file);
939 scanner_cursor.line = lineno;
940 scanner_cursor.column = 1;
944 /*------------------------------------------------------------------------.
945 | Report an unexpected EOF in a token or comment starting at START. |
946 | An end of file was encountered and the expected TOKEN_END was missing. |
947 | After reporting the problem, pretend that TOKEN_END was found. |
948 `------------------------------------------------------------------------*/
951 unexpected_end_of_file (boundary start, char const *token_end)
953 size_t i = strlen (token_end);
957 loc.end = scanner_cursor;
958 complain_at (loc, _("missing `%s' at end of file"), token_end);
960 /* Adjust scanner cursor so that any later message does not count
961 the characters about to be inserted. */
962 scanner_cursor.column -= i;
965 unput (token_end[--i]);
969 /*-------------------------.
970 | Initialize the scanner. |
971 `-------------------------*/
974 scanner_initialize (void)
976 obstack_init (&obstack_for_string);
980 /*-----------------------------------------------.
981 | Free all the memory allocated to the scanner. |
982 `-----------------------------------------------*/
987 obstack_free (&obstack_for_string, 0);
988 /* Reclaim Flex's buffers. */
989 yy_delete_buffer (YY_CURRENT_BUFFER);