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"
36 #define YY_USER_INIT \
39 scanner_cursor.file = current_file; \
40 scanner_cursor.line = 1; \
41 scanner_cursor.column = 1; \
45 /* Location of scanner cursor. */
46 boundary scanner_cursor;
48 static void adjust_location (location_t *, char const *, size_t);
49 #define YY_USER_ACTION adjust_location (loc, yytext, yyleng);
51 static size_t no_cr_read (FILE *, char *, size_t);
52 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
55 /* STRING_OBSTACK -- Used to store all the characters that we need to
56 keep (to construct ID, STRINGS etc.). Use the following macros to
59 Use STRING_GROW to append what has just been matched, and
60 STRING_FINISH to end the string (it puts the ending 0).
61 STRING_FINISH also stores this string in LAST_STRING, which can be
62 used, and which is used by STRING_FREE to free the last string. */
64 static struct obstack string_obstack;
66 /* A string representing the most recently saved token. */
67 static char *last_string;
71 obstack_grow (&string_obstack, yytext, yyleng)
73 #define STRING_FINISH \
75 obstack_1grow (&string_obstack, '\0'); \
76 last_string = obstack_finish (&string_obstack); \
80 obstack_free (&string_obstack, last_string)
83 scanner_last_string_free (void)
88 /* Within well-formed rules, RULE_LENGTH is the number of values in
89 the current rule so far, which says where to find `$0' with respect
90 to the top of the stack. It is not the same as the rule->length in
91 the case of mid rule actions.
93 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
94 static int rule_length;
96 static void handle_dollar (braced_code_t code_kind,
97 char *cp, location_t location);
98 static void handle_at (braced_code_t code_kind,
99 char *cp, location_t location);
100 static void handle_syncline (char *args);
101 static int convert_ucn_to_byte (char const *hex_text);
102 static void unexpected_end_of_file (boundary, char const *);
105 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
106 %x SC_STRING SC_CHARACTER
107 %x SC_AFTER_IDENTIFIER
108 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
109 %x SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
111 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
112 id {letter}({letter}|[0-9])*
113 directive %{letter}({letter}|[0-9]|-)*
116 /* POSIX says that a tag must be both an id and a C union member, but
117 historically almost any character is allowed in a tag. We disallow
118 NUL and newline, as this simplifies our implementation. */
121 /* Zero or more instances of backslash-newline. Following GCC, allow
122 white space between the backslash and the newline. */
123 splice (\\[ \f\t\v]*\n)*
127 /* Nesting level of the current code in braces. */
128 int braces_level IF_LINT (= 0);
130 /* Parent context state, when applicable. */
131 int context_state IF_LINT (= 0);
133 /* Location of most recent identifier, when applicable. */
134 location_t id_loc IF_LINT (= *loc);
136 /* Location where containing code started, when applicable. */
137 boundary code_start IF_LINT (= loc->start);
139 /* Location where containing comment or string or character literal
140 started, when applicable. */
141 boundary token_start IF_LINT (= loc->start);
145 /*-----------------------.
146 | Scanning white space. |
147 `-----------------------*/
149 <INITIAL,SC_AFTER_IDENTIFIER>
154 "/*" token_start = loc->start; context_state = YY_START; BEGIN SC_YACC_COMMENT;
157 /* #line directives are not documented, and may be withdrawn or
158 modified in future versions of Bison. */
159 ^"#line "{int}" \"".*"\"\n" {
160 handle_syncline (yytext + sizeof "#line " - 1);
165 /*----------------------------.
166 | Scanning Bison directives. |
167 `----------------------------*/
170 "%binary" return PERCENT_NONASSOC;
171 "%debug" return PERCENT_DEBUG;
172 "%define" return PERCENT_DEFINE;
173 "%defines" return PERCENT_DEFINES;
174 "%destructor" return PERCENT_DESTRUCTOR;
175 "%dprec" return PERCENT_DPREC;
176 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
177 "%expect" return PERCENT_EXPECT;
178 "%file-prefix" return PERCENT_FILE_PREFIX;
179 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
180 "%glr-parser" return PERCENT_GLR_PARSER;
181 "%left" return PERCENT_LEFT;
182 "%locations" return PERCENT_LOCATIONS;
183 "%merge" return PERCENT_MERGE;
184 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
185 "%no"[-_]"lines" return PERCENT_NO_LINES;
186 "%nonassoc" return PERCENT_NONASSOC;
187 "%nterm" return PERCENT_NTERM;
188 "%output" return PERCENT_OUTPUT;
189 "%parse-param" return PERCENT_PARSE_PARAM;
190 "%prec" rule_length--; return PERCENT_PREC;
191 "%printer" return PERCENT_PRINTER;
192 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
193 "%right" return PERCENT_RIGHT;
194 "%lex-param" return PERCENT_LEX_PARAM;
195 "%skeleton" return PERCENT_SKELETON;
196 "%start" return PERCENT_START;
197 "%term" return PERCENT_TOKEN;
198 "%token" return PERCENT_TOKEN;
199 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
200 "%type" return PERCENT_TYPE;
201 "%union" return PERCENT_UNION;
202 "%verbose" return PERCENT_VERBOSE;
203 "%yacc" return PERCENT_YACC;
206 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
210 "|" rule_length = 0; return PIPE;
211 ";" return SEMICOLON;
214 warn_at (*loc, _("stray `,' treated as white space"));
218 val->symbol = symbol_get (yytext, *loc);
221 BEGIN SC_AFTER_IDENTIFIER;
227 num = strtoul (yytext, 0, 10);
228 if (INT_MAX < num || errno)
230 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
237 /* Characters. We don't check there is only one. */
238 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
241 "\"" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_STRING;
244 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
246 /* Code in between braces. */
250 code_start = loc->start;
251 BEGIN SC_BRACED_CODE;
256 obstack_grow (&string_obstack, yytext + 1, yyleng - 2);
258 val->struniq = struniq_new (last_string);
264 static int percent_percent_count;
265 if (++percent_percent_count == 2)
267 code_start = loc->start;
270 return PERCENT_PERCENT;
274 complain_at (*loc, _("invalid character: %s"), quote (yytext));
279 /*-----------------------------------------------------------------.
280 | Scanning after an identifier, checking whether a colon is next. |
281 `-----------------------------------------------------------------*/
283 <SC_AFTER_IDENTIFIER>
292 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
306 /*---------------------------------------------------------------.
307 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
308 `---------------------------------------------------------------*/
312 "*/" BEGIN context_state;
314 <<EOF>> unexpected_end_of_file (token_start, "*/");
318 /*------------------------------------------------------------.
319 | Scanning a C comment. The initial `/ *' is already eaten. |
320 `------------------------------------------------------------*/
324 "*"{splice}"/" STRING_GROW; BEGIN context_state;
325 <<EOF>> unexpected_end_of_file (token_start, "*/");
329 /*--------------------------------------------------------------.
330 | Scanning a line comment. The initial `//' is already eaten. |
331 `--------------------------------------------------------------*/
335 "\n" STRING_GROW; BEGIN context_state;
336 {splice} STRING_GROW;
337 <<EOF>> BEGIN context_state;
341 /*----------------------------------------------------------------.
342 | Scanning a C string, including its escapes. The initial `"' is |
344 `----------------------------------------------------------------*/
351 loc->start = token_start;
352 val->string = last_string;
359 <<EOF>> unexpected_end_of_file (token_start, "\"");
362 /*---------------------------------------------------------------.
363 | Scanning a C character, decoding its escapes. The initial "'" |
364 | is already eaten. |
365 `---------------------------------------------------------------*/
367 <SC_ESCAPED_CHARACTER>
372 loc->start = token_start;
373 val->symbol = symbol_get (last_string, *loc);
374 symbol_class_set (val->symbol, token_sym, *loc);
375 symbol_user_token_number_set (val->symbol,
376 (unsigned char) last_string[1], *loc);
384 <<EOF>> unexpected_end_of_file (token_start, "'");
388 /*----------------------------.
389 | Decode escaped characters. |
390 `----------------------------*/
392 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
395 unsigned long c = strtoul (yytext + 1, 0, 8);
397 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
399 obstack_1grow (&string_obstack, c);
402 \\x[0-9abcdefABCDEF]+ {
405 c = strtoul (yytext + 2, 0, 16);
406 if (UCHAR_MAX < c || errno)
407 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
409 obstack_1grow (&string_obstack, c);
412 \\a obstack_1grow (&string_obstack, '\a');
413 \\b obstack_1grow (&string_obstack, '\b');
414 \\f obstack_1grow (&string_obstack, '\f');
415 \\n obstack_1grow (&string_obstack, '\n');
416 \\r obstack_1grow (&string_obstack, '\r');
417 \\t obstack_1grow (&string_obstack, '\t');
418 \\v obstack_1grow (&string_obstack, '\v');
420 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
421 \\("\""|"'"|"?"|"\\") obstack_1grow (&string_obstack, yytext[1]);
423 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
424 int c = convert_ucn_to_byte (yytext);
426 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
428 obstack_1grow (&string_obstack, c);
431 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
437 /*----------------------------------------------------------.
438 | Scanning a C character without decoding its escapes. The |
439 | initial "'" is already eaten. |
440 `----------------------------------------------------------*/
444 "'" STRING_GROW; BEGIN context_state;
445 \\{splice}[^$@\[\]] STRING_GROW;
446 <<EOF>> unexpected_end_of_file (token_start, "'");
450 /*----------------------------------------------------------------.
451 | Scanning a C string, without decoding its escapes. The initial |
452 | `"' is already eaten. |
453 `----------------------------------------------------------------*/
457 "\"" STRING_GROW; BEGIN context_state;
458 \\{splice}[^$@\[\]] STRING_GROW;
459 <<EOF>> unexpected_end_of_file (token_start, "\"");
463 /*---------------------------------------------------.
464 | Strings, comments etc. can be found in user code. |
465 `---------------------------------------------------*/
467 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
471 context_state = YY_START;
472 token_start = loc->start;
477 context_state = YY_START;
478 token_start = loc->start;
483 context_state = YY_START;
484 token_start = loc->start;
489 context_state = YY_START;
490 BEGIN SC_LINE_COMMENT;
495 /*---------------------------------------------------------------.
496 | Scanning some code in braces (%union and actions). The initial |
497 | "{" is already eaten. |
498 `---------------------------------------------------------------*/
502 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
503 "%"{splice}">" STRING_GROW; braces_level--;
507 if (braces_level < 0)
510 loc->start = code_start;
511 val->string = last_string;
518 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
520 "<"{splice}"<" STRING_GROW;
522 "$"("<"{tag}">")?(-?[0-9]+|"$") { handle_dollar (current_braced_code,
524 "@"(-?[0-9]+|"$") { handle_at (current_braced_code,
527 <<EOF>> unexpected_end_of_file (code_start, "}");
531 /*--------------------------------------------------------------.
532 | Scanning some prologue: from "%{" (already scanned) to "%}". |
533 `--------------------------------------------------------------*/
539 loc->start = code_start;
540 val->string = last_string;
545 <<EOF>> unexpected_end_of_file (code_start, "%}");
549 /*---------------------------------------------------------------.
550 | Scanning the epilogue (everything after the second "%%", which |
551 | has already been eaten). |
552 `---------------------------------------------------------------*/
558 loc->start = code_start;
559 val->string = last_string;
566 /*----------------------------------------------------------------.
567 | By default, grow the string obstack with the input, escaping M4 |
568 | quoting characters. |
569 `----------------------------------------------------------------*/
571 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
573 \$ obstack_sgrow (&string_obstack, "$][");
574 \@ obstack_sgrow (&string_obstack, "@@");
575 \[ obstack_sgrow (&string_obstack, "@{");
576 \] obstack_sgrow (&string_obstack, "@}");
583 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
587 adjust_location (location_t *loc, char const *token, size_t size)
589 int line = scanner_cursor.line;
590 int column = scanner_cursor.column;
591 char const *p0 = token;
592 char const *p = token;
593 char const *lim = token + size;
595 loc->start = scanner_cursor;
597 for (p = token; p < lim; p++)
607 column += mbsnwidth (p0, p - p0, 0);
608 column += 8 - ((column - 1) & 7);
613 scanner_cursor.line = line;
614 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
616 loc->end = scanner_cursor;
620 /* Read bytes from FP into buffer BUF of size SIZE. Return the
621 number of bytes read. Remove '\r' from input, treating \r\n
622 and isolated \r as \n. */
625 no_cr_read (FILE *fp, char *buf, size_t size)
627 size_t s = fread (buf, 1, size, fp);
630 char *w = memchr (buf, '\r', s);
634 char const *lim = buf + s;
638 /* Found an '\r'. Treat it like '\n', but ignore any
639 '\n' that immediately follows. */
644 if (ch != '\n' && ungetc (ch, fp) != ch)
650 /* Copy until the next '\r'. */
656 while ((*w++ = *r++) != '\r');
667 /*------------------------------------------------------------------.
668 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
670 | Possible inputs: $[<TYPENAME>]($|integer) |
672 | Output to the STRING_OBSTACK a reference to this semantic value. |
673 `------------------------------------------------------------------*/
676 handle_action_dollar (char *text, location_t location)
678 const char *type_name = NULL;
681 /* Get the type name if explicit. */
694 type_name = symbol_list_n_type_name_get (current_rule, location, 0);
695 if (!type_name && typed)
696 complain_at (location, _("$$ of `%s' has no declared type"),
697 current_rule->sym->tag);
700 obstack_fgrow1 (&string_obstack,
701 "]b4_lhs_value([%s])[", type_name);
707 num = strtol (cp, 0, 10);
709 if (INT_MIN <= num && num <= rule_length && ! errno)
712 if (!type_name && n > 0)
713 type_name = symbol_list_n_type_name_get (current_rule, location,
715 if (!type_name && typed)
716 complain_at (location, _("$%d of `%s' has no declared type"),
717 n, current_rule->sym->tag);
720 obstack_fgrow3 (&string_obstack,
721 "]b4_rhs_value([%d], [%d], [%s])[",
722 rule_length, n, type_name);
725 complain_at (location, _("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_t location)
740 obstack_sgrow (&string_obstack, "]b4_dollar_dollar[");
742 complain_at (location, _("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_t braced_code_kind,
753 char *text, location_t location)
755 switch (braced_code_kind)
757 case action_braced_code:
758 handle_action_dollar (text, location);
761 case destructor_braced_code:
762 case printer_braced_code:
763 handle_symbol_code_dollar (text, location);
769 /*------------------------------------------------------.
770 | TEXT is a location token (i.e., a `@...'). Output to |
771 | STRING_OBSTACK a reference to this location. |
772 `------------------------------------------------------*/
775 handle_action_at (char *text, location_t location)
782 obstack_sgrow (&string_obstack, "]b4_lhs_location[");
788 num = strtol (cp, 0, 10);
790 if (INT_MIN <= num && num <= rule_length && ! errno)
793 obstack_fgrow2 (&string_obstack, "]b4_rhs_location([%d], [%d])[",
797 complain_at (location, _("integer out of range: %s"), quote (text));
802 /*---------------------------------------------------------------.
803 | TEXT is expected to be @$ in some code associated to a symbol: |
804 | destructor or printer. |
805 `---------------------------------------------------------------*/
808 handle_symbol_code_at (char *text, location_t location)
812 obstack_sgrow (&string_obstack, "]b4_at_dollar[");
814 complain_at (location, _("invalid value: %s"), quote (text));
818 /*-------------------------------------------------------------------.
819 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
821 `-------------------------------------------------------------------*/
824 handle_at (braced_code_t braced_code_kind,
825 char *text, location_t location)
827 switch (braced_code_kind)
829 case action_braced_code:
830 handle_action_at (text, location);
833 case destructor_braced_code:
834 case printer_braced_code:
835 handle_symbol_code_at (text, location);
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);
926 location.start = start;
927 location.end = scanner_cursor;
928 complain_at (location, _("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 (&string_obstack);
950 /*-----------------------------------------------.
951 | Free all the memory allocated to the scanner. |
952 `-----------------------------------------------*/
957 obstack_free (&string_obstack, 0);
958 /* Reclaim Flex's buffers. */
959 yy_delete_buffer (YY_CURRENT_BUFFER);