1 /* Bison Grammar Scanner -*- C -*-
3 Copyright (C) 2002, 2003, 2004, 2005, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA
23 %option debug nodefault nounput noyywrap never-interactive
24 %option prefix="gram_" outfile="lex.yy.c"
27 /* Work around a bug in flex 2.5.31. See Debian bug 333231
28 <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
32 #define FLEX_PREFIX(Id) gram_ ## Id
33 #include "flex-scanner.h"
37 #include "getargs.h" /* yacc_flag */
46 #include "scan-gram.h"
48 #define YY_DECL GRAM_LEX_DECL
50 #define YY_USER_INIT \
51 code_start = scanner_cursor = loc->start; \
53 /* Location of scanner cursor. */
54 boundary scanner_cursor;
56 #define YY_USER_ACTION location_compute (loc, &scanner_cursor, yytext, yyleng);
58 static size_t no_cr_read (FILE *, char *, size_t);
59 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
61 /* A string representing the most recently saved token. */
65 gram_scanner_last_string_free (void)
70 /* The location of the most recently saved token, if it was a
71 BRACED_CODE token; otherwise, this has an unspecified value. */
72 location gram_last_braced_code_loc;
74 static void handle_syncline (char *, location);
75 static unsigned long int scan_integer (char const *p, int base, location loc);
76 static int convert_ucn_to_byte (char const *hex_text);
77 static void unexpected_eof (boundary, char const *);
78 static void unexpected_newline (boundary, char const *);
81 /* A C-like comment in directives/rules. */
83 /* Strings and characters in directives/rules. */
84 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
85 /* A identifier was just read in directives/rules. Special state
86 to capture the sequence `identifier :'. */
87 %x SC_AFTER_IDENTIFIER
88 /* A keyword that should be followed by some code was read (e.g.
92 /* Three types of user code:
93 - prologue (code between `%{' `%}' in the first section, before %%);
94 - actions, printers, union, etc, (between braced in the middle section);
95 - epilogue (everything after the second %%). */
96 %x SC_PROLOGUE SC_BRACED_CODE SC_EPILOGUE
97 /* C and C++ comments in code. */
98 %x SC_COMMENT SC_LINE_COMMENT
99 /* Strings and characters in code. */
100 %x SC_STRING SC_CHARACTER
102 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
103 id {letter}({letter}|[0-9])*
104 directive %{letter}({letter}|[0-9]|-)*
107 /* POSIX says that a tag must be both an id and a C union member, but
108 historically almost any character is allowed in a tag. We disallow
109 NUL and newline, as this simplifies our implementation. */
112 /* Zero or more instances of backslash-newline. Following GCC, allow
113 white space between the backslash and the newline. */
114 splice (\\[ \f\t\v]*\n)*
118 /* Nesting level of the current code in braces. */
119 int braces_level IF_LINT (= 0);
121 /* Parent context state, when applicable. */
122 int context_state IF_LINT (= 0);
124 /* Token type to return, when applicable. */
125 int token_type IF_LINT (= 0);
127 /* Location of most recent identifier, when applicable. */
128 location id_loc IF_LINT (= empty_location);
130 /* Where containing code started, when applicable. Its initial
131 value is relevant only when yylex is invoked in the SC_EPILOGUE
133 boundary code_start = scanner_cursor;
135 /* Where containing comment or string or character literal started,
137 boundary token_start IF_LINT (= scanner_cursor);
141 /*-----------------------.
142 | Scanning white space. |
143 `-----------------------*/
145 <INITIAL,SC_AFTER_IDENTIFIER,SC_PRE_CODE>
147 /* Comments and white space. */
148 "," warn_at (*loc, _("stray `,' treated as white space"));
152 token_start = loc->start;
153 context_state = YY_START;
154 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, *loc);
165 /*----------------------------.
166 | Scanning Bison directives. |
167 `----------------------------*/
170 "%binary" return PERCENT_NONASSOC;
171 "%debug" return PERCENT_DEBUG;
172 "%default"[-_]"prec" return PERCENT_DEFAULT_PREC;
173 "%define" return PERCENT_DEFINE;
174 "%defines" return PERCENT_DEFINES;
175 "%destructor" /* FIXME: Remove once %union handled differently. */ token_type = BRACED_CODE; return PERCENT_DESTRUCTOR;
176 "%dprec" return PERCENT_DPREC;
177 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
178 "%expect" return PERCENT_EXPECT;
179 "%expect"[-_]"rr" return PERCENT_EXPECT_RR;
180 "%file-prefix" return PERCENT_FILE_PREFIX;
181 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
182 "%initial-action" /* FIXME: Remove once %union handled differently. */ token_type = BRACED_CODE; return PERCENT_INITIAL_ACTION;
183 "%glr-parser" return PERCENT_GLR_PARSER;
184 "%left" return PERCENT_LEFT;
185 "%lex-param" /* FIXME: Remove once %union handled differently. */ token_type = BRACED_CODE; return PERCENT_LEX_PARAM;
186 "%locations" return PERCENT_LOCATIONS;
187 "%merge" return PERCENT_MERGE;
188 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
189 "%no"[-_]"default"[-_]"prec" return PERCENT_NO_DEFAULT_PREC;
190 "%no"[-_]"lines" return PERCENT_NO_LINES;
191 "%nonassoc" return PERCENT_NONASSOC;
192 "%nondeterministic-parser" return PERCENT_NONDETERMINISTIC_PARSER;
193 "%nterm" return PERCENT_NTERM;
194 "%output" return PERCENT_OUTPUT;
195 "%parse-param" /* FIXME: Remove once %union handled differently. */ token_type = BRACED_CODE; return PERCENT_PARSE_PARAM;
196 "%prec" return PERCENT_PREC;
197 "%printer" /* FIXME: Remove once %union handled differently. */ token_type = BRACED_CODE; return PERCENT_PRINTER;
198 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
199 "%require" return PERCENT_REQUIRE;
200 "%right" return PERCENT_RIGHT;
201 "%skeleton" return PERCENT_SKELETON;
202 "%start" return PERCENT_START;
203 "%term" return PERCENT_TOKEN;
204 "%token" return PERCENT_TOKEN;
205 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
206 "%type" return PERCENT_TYPE;
207 "%union" token_type = PERCENT_UNION; BEGIN SC_PRE_CODE;
208 "%verbose" return PERCENT_VERBOSE;
209 "%yacc" return PERCENT_YACC;
212 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
217 ";" return SEMICOLON;
220 val->symbol = symbol_get (yytext, *loc);
222 BEGIN SC_AFTER_IDENTIFIER;
226 val->integer = scan_integer (yytext, 10, *loc);
229 0[xX][0-9abcdefABCDEF]+ {
230 val->integer = scan_integer (yytext, 16, *loc);
234 /* Characters. We don't check there is only one. */
235 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
238 "\"" token_start = loc->start; BEGIN SC_ESCAPED_STRING;
241 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
243 /* Code in between braces. */
245 if (current_rule && current_rule->action)
246 grammar_midrule_action ();
248 token_type = BRACED_CODE;
250 code_start = loc->start;
251 BEGIN SC_BRACED_CODE;
256 obstack_grow (&obstack_for_string, yytext + 1, yyleng - 2);
258 val->uniqstr = uniqstr_new (last_string);
264 static int percent_percent_count;
265 if (++percent_percent_count == 2)
267 return PERCENT_PERCENT;
271 complain_at (*loc, _("invalid character: %s"), quote (yytext));
275 loc->start = loc->end = scanner_cursor;
281 /*-----------------------------------------------------------------.
282 | Scanning after an identifier, checking whether a colon is next. |
283 `-----------------------------------------------------------------*/
285 <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_eof (token_start, "*/"); BEGIN context_state;
319 /*------------------------------------------------------------.
320 | Scanning a C comment. The initial `/ *' is already eaten. |
321 `------------------------------------------------------------*/
325 "*"{splice}"/" STRING_GROW; BEGIN context_state;
326 <<EOF>> unexpected_eof (token_start, "*/"); BEGIN context_state;
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 Bison string, including its escapes. |
344 | The initial quote is already eaten. |
345 `------------------------------------------------*/
351 loc->start = token_start;
352 val->chars = last_string;
356 \n unexpected_newline (token_start, "\""); BEGIN INITIAL;
357 <<EOF>> unexpected_eof (token_start, "\""); BEGIN INITIAL;
360 /*----------------------------------------------------------.
361 | Scanning a Bison character literal, decoding its escapes. |
362 | The initial quote is already eaten. |
363 `----------------------------------------------------------*/
365 <SC_ESCAPED_CHARACTER>
368 unsigned char last_string_1;
371 loc->start = token_start;
372 val->symbol = symbol_get (quotearg_style (escape_quoting_style,
375 symbol_class_set (val->symbol, token_sym, *loc, false);
376 last_string_1 = last_string[1];
377 symbol_user_token_number_set (val->symbol, last_string_1, *loc);
382 \n unexpected_newline (token_start, "'"); BEGIN INITIAL;
383 <<EOF>> unexpected_eof (token_start, "'"); BEGIN INITIAL;
386 <SC_ESCAPED_CHARACTER,SC_ESCAPED_STRING>
388 \0 complain_at (*loc, _("invalid null character"));
392 /*----------------------------.
393 | Decode escaped characters. |
394 `----------------------------*/
396 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
399 unsigned long int c = strtoul (yytext + 1, NULL, 8);
401 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
403 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
405 obstack_1grow (&obstack_for_string, c);
408 \\x[0-9abcdefABCDEF]+ {
409 verify (UCHAR_MAX < ULONG_MAX);
410 unsigned long int c = strtoul (yytext + 2, NULL, 16);
412 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
414 complain_at (*loc, _("invalid null character: %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 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
437 obstack_1grow (&obstack_for_string, c);
440 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
445 /*--------------------------------------------.
446 | Scanning user-code characters and strings. |
447 `--------------------------------------------*/
449 <SC_CHARACTER,SC_STRING>
451 {splice}|\\{splice}[^\n\[\]] STRING_GROW;
456 "'" STRING_GROW; BEGIN context_state;
457 \n unexpected_newline (token_start, "'"); BEGIN context_state;
458 <<EOF>> unexpected_eof (token_start, "'"); BEGIN context_state;
463 "\"" STRING_GROW; BEGIN context_state;
464 \n unexpected_newline (token_start, "\""); BEGIN context_state;
465 <<EOF>> unexpected_eof (token_start, "\""); BEGIN context_state;
469 /*---------------------------------------------------.
470 | Strings, comments etc. can be found in user code. |
471 `---------------------------------------------------*/
473 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
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 token_start = loc->start;
495 context_state = YY_START;
496 BEGIN SC_LINE_COMMENT;
501 /*---------------------------------------------------------------.
502 | Scanning after %union etc., possibly followed by white space. |
503 | For %union only, allow arbitrary C code to appear before the |
504 | following brace, as an extension to POSIX. |
505 `---------------------------------------------------------------*/
510 bool valid = yytext[0] == '{' || token_type == PERCENT_UNION;
511 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
517 code_start = loc->start;
518 BEGIN SC_BRACED_CODE;
522 complain_at (*loc, _("missing `{' in %s"),
523 token_name (token_type));
524 obstack_sgrow (&obstack_for_string, "{}");
526 val->chars = last_string;
532 <<EOF>> unexpected_eof (scanner_cursor, "{}"); BEGIN INITIAL;
536 /*---------------------------------------------------------------.
537 | Scanning some code in braces (%union and actions). The initial |
538 | "{" is already eaten. |
539 `---------------------------------------------------------------*/
543 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
544 "%"{splice}">" STRING_GROW; braces_level--;
546 bool outer_brace = --braces_level < 0;
548 /* As an undocumented Bison extension, append `;' before the last
549 brace in braced code, so that the user code can omit trailing
550 `;'. But do not append `;' if emulating Yacc, since Yacc does
553 FIXME: Bison should warn if a semicolon seems to be necessary
554 here, and should omit the semicolon if it seems unnecessary
555 (e.g., after ';', '{', or '}', each followed by comments or
556 white space). Such a warning shouldn't depend on --yacc; it
557 should depend on a new --pedantic option, which would cause
558 Bison to warn if it detects an extension to POSIX. --pedantic
559 should also diagnose other Bison extensions like %yacc.
560 Perhaps there should also be a GCC-style --pedantic-errors
561 option, so that such warnings are diagnosed as errors. */
562 if (outer_brace && token_type == BRACED_CODE && ! yacc_flag)
563 obstack_1grow (&obstack_for_string, ';');
565 obstack_1grow (&obstack_for_string, '}');
570 loc->start = code_start;
571 val->chars = last_string;
572 gram_last_braced_code_loc = *loc;
578 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
580 "<"{splice}"<" STRING_GROW;
582 <<EOF>> unexpected_eof (code_start, "}"); BEGIN INITIAL;
586 /*--------------------------------------------------------------.
587 | Scanning some prologue: from "%{" (already scanned) to "%}". |
588 `--------------------------------------------------------------*/
594 loc->start = code_start;
595 val->chars = last_string;
600 <<EOF>> unexpected_eof (code_start, "%}"); BEGIN INITIAL;
604 /*---------------------------------------------------------------.
605 | Scanning the epilogue (everything after the second "%%", which |
606 | has already been eaten). |
607 `---------------------------------------------------------------*/
613 loc->start = code_start;
614 val->chars = last_string;
621 /*-----------------------------------------------------.
622 | By default, grow the string obstack with the input. |
623 `-----------------------------------------------------*/
625 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE,SC_STRING,SC_CHARACTER,SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>. |
626 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>\n STRING_GROW;
630 /* Read bytes from FP into buffer BUF of size SIZE. Return the
631 number of bytes read. Remove '\r' from input, treating \r\n
632 and isolated \r as \n. */
635 no_cr_read (FILE *fp, char *buf, size_t size)
637 size_t bytes_read = fread (buf, 1, size, fp);
640 char *w = memchr (buf, '\r', bytes_read);
644 char const *lim = buf + bytes_read;
648 /* Found an '\r'. Treat it like '\n', but ignore any
649 '\n' that immediately follows. */
654 if (ch != '\n' && ungetc (ch, fp) != ch)
660 /* Copy until the next '\r'. */
666 while ((*w++ = *r++) != '\r');
678 /*------------------------------------------------------.
679 | Scan NUMBER for a base-BASE integer at location LOC. |
680 `------------------------------------------------------*/
682 static unsigned long int
683 scan_integer (char const *number, int base, location loc)
685 verify (INT_MAX < ULONG_MAX);
686 unsigned long int num = strtoul (number, NULL, base);
690 complain_at (loc, _("integer out of range: %s"), quote (number));
698 /*------------------------------------------------------------------.
699 | Convert universal character name UCN to a single-byte character, |
700 | and return that character. Return -1 if UCN does not correspond |
701 | to a single-byte character. |
702 `------------------------------------------------------------------*/
705 convert_ucn_to_byte (char const *ucn)
707 verify (UCHAR_MAX <= INT_MAX);
708 unsigned long int code = strtoul (ucn + 2, NULL, 16);
710 /* FIXME: Currently we assume Unicode-compatible unibyte characters
711 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
712 non-ASCII hosts we support only the portable C character set.
713 These limitations should be removed once we add support for
714 multibyte characters. */
716 if (UCHAR_MAX < code)
719 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
721 /* A non-ASCII host. Use CODE to index into a table of the C
722 basic execution character set, which is guaranteed to exist on
723 all Standard C platforms. This table also includes '$', '@',
724 and '`', which are not in the basic execution character set but
725 which are unibyte characters on all the platforms that we know
727 static signed char const table[] =
729 '\0', -1, -1, -1, -1, -1, -1, '\a',
730 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
731 -1, -1, -1, -1, -1, -1, -1, -1,
732 -1, -1, -1, -1, -1, -1, -1, -1,
733 ' ', '!', '"', '#', '$', '%', '&', '\'',
734 '(', ')', '*', '+', ',', '-', '.', '/',
735 '0', '1', '2', '3', '4', '5', '6', '7',
736 '8', '9', ':', ';', '<', '=', '>', '?',
737 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
738 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
739 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
740 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
741 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
742 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
743 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
744 'x', 'y', 'z', '{', '|', '}', '~'
747 code = code < sizeof table ? table[code] : -1;
755 /*----------------------------------------------------------------.
756 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
757 `----------------------------------------------------------------*/
760 handle_syncline (char *args, location loc)
763 unsigned long int lineno = strtoul (args, &after_num, 10);
764 char *file = strchr (after_num, '"') + 1;
765 *strchr (file, '"') = '\0';
766 if (INT_MAX <= lineno)
768 warn_at (loc, _("line number overflow"));
771 current_file = uniqstr_new (file);
772 boundary_set, (&scanner_cursor, current_file, lineno, 1);
776 /*----------------------------------------------------------------.
777 | For a token or comment starting at START, report message MSGID, |
778 | which should say that an end marker was found before |
779 | the expected TOKEN_END. |
780 `----------------------------------------------------------------*/
783 unexpected_end (boundary start, char const *msgid, char const *token_end)
787 loc.end = scanner_cursor;
788 complain_at (loc, _(msgid), token_end);
792 /*------------------------------------------------------------------------.
793 | Report an unexpected EOF in a token or comment starting at START. |
794 | An end of file was encountered and the expected TOKEN_END was missing. |
795 `------------------------------------------------------------------------*/
798 unexpected_eof (boundary start, char const *token_end)
800 unexpected_end (start, N_("missing `%s' at end of file"), token_end);
804 /*----------------------------------------.
805 | Likewise, but for unexpected newlines. |
806 `----------------------------------------*/
809 unexpected_newline (boundary start, char const *token_end)
811 unexpected_end (start, N_("missing `%s' at end of line"), token_end);
815 /*-------------------------.
816 | Initialize the scanner. |
817 `-------------------------*/
820 gram_scanner_initialize (void)
822 obstack_init (&obstack_for_string);
826 /*-----------------------------------------------.
827 | Free all the memory allocated to the scanner. |
828 `-----------------------------------------------*/
831 gram_scanner_free (void)
833 obstack_free (&obstack_for_string, 0);
834 /* Reclaim Flex's buffers. */
835 yy_delete_buffer (YY_CURRENT_BUFFER);