1 /* Bison Grammar Scanner -*- C -*-
3 Copyright (C) 2002, 2003, 2004, 2005 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"
30 #include <get-errno.h>
41 #define YY_USER_INIT \
44 scanner_cursor.file = current_file; \
45 scanner_cursor.line = 1; \
46 scanner_cursor.column = 1; \
47 code_start = scanner_cursor; \
51 /* Location of scanner cursor. */
52 boundary scanner_cursor;
54 static void adjust_location (location *, char const *, size_t);
55 #define YY_USER_ACTION adjust_location (loc, yytext, yyleng);
57 static size_t no_cr_read (FILE *, char *, size_t);
58 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
60 /* Within well-formed rules, RULE_LENGTH is the number of values in
61 the current rule so far, which says where to find `$0' with respect
62 to the top of the stack. It is not the same as the rule->length in
63 the case of mid rule actions.
65 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
68 static void handle_dollar (int token_type, char *cp, location loc);
69 static void handle_at (int token_type, char *cp, location loc);
70 static void handle_syncline (char *args);
71 static unsigned long int scan_integer (char const *p, int base, location loc);
72 static int convert_ucn_to_byte (char const *hex_text);
73 static void unexpected_eof (boundary, char const *);
74 static void unexpected_newline (boundary, char const *);
77 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
78 %x SC_STRING SC_CHARACTER
79 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
80 %x SC_PRE_CODE SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
82 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
83 id {letter}({letter}|[0-9])*
84 directive %{letter}({letter}|[0-9]|-)*
87 /* POSIX says that a tag must be both an id and a C union member, but
88 historically almost any character is allowed in a tag. We disallow
89 NUL and newline, as this simplifies our implementation. */
92 /* Zero or more instances of backslash-newline. Following GCC, allow
93 white space between the backslash and the newline. */
94 splice (\\[ \f\t\v]*\n)*
98 /* Nesting level of the current code in braces. */
99 int braces_level IF_LINT (= 0);
101 /* Parent context state, when applicable. */
102 int context_state IF_LINT (= 0);
104 /* Token type to return, when applicable. */
105 int token_type IF_LINT (= 0);
107 /* Where containing code started, when applicable. Its initial
108 value is relevant only when yylex is invoked in the SC_EPILOGUE
110 boundary code_start = scanner_cursor;
112 /* Where containing comment or string or character literal started,
114 boundary token_start IF_LINT (= scanner_cursor);
118 /*-----------------------.
119 | Scanning white space. |
120 `-----------------------*/
124 /* Comments and white space. */
125 "," warn_at (*loc, _("stray `,' treated as white space"));
129 token_start = loc->start;
130 context_state = YY_START;
131 BEGIN SC_YACC_COMMENT;
134 /* #line directives are not documented, and may be withdrawn or
135 modified in future versions of Bison. */
136 ^"#line "{int}" \"".*"\"\n" {
137 handle_syncline (yytext + sizeof "#line " - 1);
142 /*----------------------------.
143 | Scanning Bison directives. |
144 `----------------------------*/
148 /* Code in between braces. */
151 token_type = BRACED_CODE;
153 code_start = loc->start;
154 BEGIN SC_BRACED_CODE;
160 /*------------------------------------------------------------.
161 | Scanning a C comment. The initial `/ *' is already eaten. |
162 `------------------------------------------------------------*/
166 "*"{splice}"/" STRING_GROW; BEGIN context_state;
167 <<EOF>> unexpected_eof (token_start, "*/"); BEGIN context_state;
171 /*--------------------------------------------------------------.
172 | Scanning a line comment. The initial `//' is already eaten. |
173 `--------------------------------------------------------------*/
177 "\n" STRING_GROW; BEGIN context_state;
178 {splice} STRING_GROW;
179 <<EOF>> BEGIN context_state;
183 /*------------------------------------------------.
184 | Scanning a Bison string, including its escapes. |
185 | The initial quote is already eaten. |
186 `------------------------------------------------*/
192 loc->start = token_start;
193 val->chars = last_string;
198 \n unexpected_newline (token_start, "\""); BEGIN INITIAL;
199 <<EOF>> unexpected_eof (token_start, "\""); BEGIN INITIAL;
202 /*----------------------------------------------------------.
203 | Scanning a Bison character literal, decoding its escapes. |
204 | The initial quote is already eaten. |
205 `----------------------------------------------------------*/
207 <SC_ESCAPED_CHARACTER>
210 unsigned char last_string_1;
213 loc->start = token_start;
214 val->symbol = symbol_get (quotearg_style (escape_quoting_style,
217 symbol_class_set (val->symbol, token_sym, *loc);
218 last_string_1 = last_string[1];
219 symbol_user_token_number_set (val->symbol, last_string_1, *loc);
225 \n unexpected_newline (token_start, "'"); BEGIN INITIAL;
226 <<EOF>> unexpected_eof (token_start, "'"); BEGIN INITIAL;
229 <SC_ESCAPED_CHARACTER,SC_ESCAPED_STRING>
231 \0 complain_at (*loc, _("invalid null character"));
235 /*----------------------------.
236 | Decode escaped characters. |
237 `----------------------------*/
239 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
242 unsigned long int c = strtoul (yytext + 1, 0, 8);
244 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
246 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
248 obstack_1grow (&obstack_for_string, c);
251 \\x[0-9abcdefABCDEF]+ {
254 c = strtoul (yytext + 2, 0, 16);
255 if (UCHAR_MAX < c || get_errno ())
256 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
258 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
260 obstack_1grow (&obstack_for_string, c);
263 \\a obstack_1grow (&obstack_for_string, '\a');
264 \\b obstack_1grow (&obstack_for_string, '\b');
265 \\f obstack_1grow (&obstack_for_string, '\f');
266 \\n obstack_1grow (&obstack_for_string, '\n');
267 \\r obstack_1grow (&obstack_for_string, '\r');
268 \\t obstack_1grow (&obstack_for_string, '\t');
269 \\v obstack_1grow (&obstack_for_string, '\v');
271 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
272 \\("\""|"'"|"?"|"\\") obstack_1grow (&obstack_for_string, yytext[1]);
274 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
275 int c = convert_ucn_to_byte (yytext);
277 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
279 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
281 obstack_1grow (&obstack_for_string, c);
284 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
289 /*--------------------------------------------.
290 | Scanning user-code characters and strings. |
291 `--------------------------------------------*/
293 <SC_CHARACTER,SC_STRING>
295 {splice}|\\{splice}[^\n$@\[\]] STRING_GROW;
300 "'" STRING_GROW; BEGIN context_state;
301 \n unexpected_newline (token_start, "'"); BEGIN context_state;
302 <<EOF>> unexpected_eof (token_start, "'"); BEGIN context_state;
307 "\"" STRING_GROW; BEGIN context_state;
308 \n unexpected_newline (token_start, "\""); BEGIN context_state;
309 <<EOF>> unexpected_eof (token_start, "\""); BEGIN context_state;
313 /*---------------------------------------------------.
314 | Strings, comments etc. can be found in user code. |
315 `---------------------------------------------------*/
321 context_state = YY_START;
322 token_start = loc->start;
327 context_state = YY_START;
328 token_start = loc->start;
333 context_state = YY_START;
334 token_start = loc->start;
339 context_state = YY_START;
340 BEGIN SC_LINE_COMMENT;
345 /*---------------------------------------------------------------.
346 | Scanning some code in braces (%union and actions). The initial |
347 | "{" is already eaten. |
348 `---------------------------------------------------------------*/
352 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
353 "%"{splice}">" STRING_GROW; braces_level--;
355 bool outer_brace = --braces_level < 0;
357 /* As an undocumented Bison extension, append `;' before the last
358 brace in braced code, so that the user code can omit trailing
359 `;'. But do not append `;' if emulating Yacc, since Yacc does
362 FIXME: Bison should warn if a semicolon seems to be necessary
363 here, and should omit the semicolon if it seems unnecessary
364 (e.g., after ';', '{', or '}', each followed by comments or
365 white space). Such a warning shouldn't depend on --yacc; it
366 should depend on a new --pedantic option, which would cause
367 Bison to warn if it detects an extension to POSIX. --pedantic
368 should also diagnose other Bison extensions like %yacc.
369 Perhaps there should also be a GCC-style --pedantic-errors
370 option, so that such warnings are diagnosed as errors. */
371 if (outer_brace && token_type == BRACED_CODE && ! yacc_flag)
372 obstack_1grow (&obstack_for_string, ';');
374 obstack_1grow (&obstack_for_string, '}');
380 loc->start = code_start;
381 val->chars = last_string;
387 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
389 "<"{splice}"<" STRING_GROW;
391 "$"("<"{tag}">")?(-?[0-9]+|"$") handle_dollar (token_type, yytext, *loc);
392 "@"(-?[0-9]+|"$") handle_at (token_type, yytext, *loc);
394 <<EOF>> unexpected_eof (code_start, "}"); BEGIN INITIAL;
398 /*--------------------------------------------------------------.
399 | Scanning some prologue: from "%{" (already scanned) to "%}". |
400 `--------------------------------------------------------------*/
406 loc->start = code_start;
407 val->chars = last_string;
412 <<EOF>> unexpected_eof (code_start, "%}"); BEGIN INITIAL;
416 /*---------------------------------------------------------------.
417 | Scanning the epilogue (everything after the second "%%", which |
418 | has already been eaten). |
419 `---------------------------------------------------------------*/
425 loc->start = code_start;
426 val->chars = last_string;
433 /*-----------------------------------------.
434 | Escape M4 quoting characters in C code. |
435 `-----------------------------------------*/
437 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
439 \$ obstack_sgrow (&obstack_for_string, "$][");
440 \@ obstack_sgrow (&obstack_for_string, "@@");
441 \[ obstack_sgrow (&obstack_for_string, "@{");
442 \] obstack_sgrow (&obstack_for_string, "@}");
446 /*-----------------------------------------------------.
447 | By default, grow the string obstack with the input. |
448 `-----------------------------------------------------*/
450 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE,SC_STRING,SC_CHARACTER,SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>. |
451 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>\n STRING_GROW;
455 /* Keeps track of the maximum number of semantic values to the left of
456 a handle (those referenced by $0, $-1, etc.) are required by the
457 semantic actions of this grammar. */
458 int max_left_semantic_context = 0;
460 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
464 adjust_location (location *loc, char const *token, size_t size)
466 int line = scanner_cursor.line;
467 int column = scanner_cursor.column;
468 char const *p0 = token;
469 char const *p = token;
470 char const *lim = token + size;
472 loc->start = scanner_cursor;
474 for (p = token; p < lim; p++)
484 column += mbsnwidth (p0, p - p0, 0);
485 column += 8 - ((column - 1) & 7);
490 scanner_cursor.line = line;
491 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
493 loc->end = scanner_cursor;
497 /* Read bytes from FP into buffer BUF of size SIZE. Return the
498 number of bytes read. Remove '\r' from input, treating \r\n
499 and isolated \r as \n. */
502 no_cr_read (FILE *fp, char *buf, size_t size)
504 size_t bytes_read = fread (buf, 1, size, fp);
507 char *w = memchr (buf, '\r', bytes_read);
511 char const *lim = buf + bytes_read;
515 /* Found an '\r'. Treat it like '\n', but ignore any
516 '\n' that immediately follows. */
521 if (ch != '\n' && ungetc (ch, fp) != ch)
527 /* Copy until the next '\r'. */
533 while ((*w++ = *r++) != '\r');
544 /*------------------------------------------------------------------.
545 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
547 | Possible inputs: $[<TYPENAME>]($|integer) |
549 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
550 `------------------------------------------------------------------*/
553 handle_action_dollar (char *text, location loc)
555 const char *type_name = NULL;
561 /* Get the type name if explicit. */
574 type_name = symbol_list_n_type_name_get (current_rule, loc, 0);
575 if (!type_name && typed)
576 complain_at (loc, _("$$ of `%s' has no declared type"),
577 current_rule->sym->tag);
580 obstack_fgrow1 (&obstack_for_string,
581 "]b4_lhs_value([%s])[", type_name);
587 num = strtol (cp, 0, 10);
589 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
592 if (1-n > max_left_semantic_context)
593 max_left_semantic_context = 1-n;
594 if (!type_name && n > 0)
595 type_name = symbol_list_n_type_name_get (current_rule, loc, n);
596 if (!type_name && typed)
597 complain_at (loc, _("$%d of `%s' has no declared type"),
598 n, current_rule->sym->tag);
601 obstack_fgrow3 (&obstack_for_string,
602 "]b4_rhs_value(%d, %d, [%s])[",
603 rule_length, n, type_name);
606 complain_at (loc, _("integer out of range: %s"), quote (text));
613 /*----------------------------------------------------------------.
614 | Map `$?' onto the proper M4 symbol, depending on its TOKEN_TYPE |
615 | (are we in an action?). |
616 `----------------------------------------------------------------*/
619 handle_dollar (int token_type, char *text, location loc)
624 if (handle_action_dollar (text, loc))
628 case PERCENT_DESTRUCTOR:
629 case PERCENT_INITIAL_ACTION:
630 case PERCENT_PRINTER:
633 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar[");
642 complain_at (loc, _("invalid value: %s"), quote (text));
646 /*------------------------------------------------------.
647 | TEXT is a location token (i.e., a `@...'). Output to |
648 | OBSTACK_FOR_STRING a reference to this location. |
649 `------------------------------------------------------*/
652 handle_action_at (char *text, location loc)
655 locations_flag = true;
661 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
666 num = strtol (cp, 0, 10);
668 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
671 obstack_fgrow2 (&obstack_for_string, "]b4_rhs_location(%d, %d)[",
675 complain_at (loc, _("integer out of range: %s"), quote (text));
682 /*----------------------------------------------------------------.
683 | Map `@?' onto the proper M4 symbol, depending on its TOKEN_TYPE |
684 | (are we in an action?). |
685 `----------------------------------------------------------------*/
688 handle_at (int token_type, char *text, location loc)
693 handle_action_at (text, loc);
696 case PERCENT_INITIAL_ACTION:
697 case PERCENT_DESTRUCTOR:
698 case PERCENT_PRINTER:
701 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
710 complain_at (loc, _("invalid value: %s"), quote (text));
714 /*------------------------------------------------------.
715 | Scan NUMBER for a base-BASE integer at location LOC. |
716 `------------------------------------------------------*/
718 static unsigned long int
719 scan_integer (char const *number, int base, location loc)
721 unsigned long int num;
723 num = strtoul (number, 0, base);
724 if (INT_MAX < num || get_errno ())
726 complain_at (loc, _("integer out of range: %s"), quote (number));
733 /*------------------------------------------------------------------.
734 | Convert universal character name UCN to a single-byte character, |
735 | and return that character. Return -1 if UCN does not correspond |
736 | to a single-byte character. |
737 `------------------------------------------------------------------*/
740 convert_ucn_to_byte (char const *ucn)
742 unsigned long int code = strtoul (ucn + 2, 0, 16);
744 /* FIXME: Currently we assume Unicode-compatible unibyte characters
745 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
746 non-ASCII hosts we support only the portable C character set.
747 These limitations should be removed once we add support for
748 multibyte characters. */
750 if (UCHAR_MAX < code)
753 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
755 /* A non-ASCII host. Use CODE to index into a table of the C
756 basic execution character set, which is guaranteed to exist on
757 all Standard C platforms. This table also includes '$', '@',
758 and '`', which are not in the basic execution character set but
759 which are unibyte characters on all the platforms that we know
761 static signed char const table[] =
763 '\0', -1, -1, -1, -1, -1, -1, '\a',
764 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
765 -1, -1, -1, -1, -1, -1, -1, -1,
766 -1, -1, -1, -1, -1, -1, -1, -1,
767 ' ', '!', '"', '#', '$', '%', '&', '\'',
768 '(', ')', '*', '+', ',', '-', '.', '/',
769 '0', '1', '2', '3', '4', '5', '6', '7',
770 '8', '9', ':', ';', '<', '=', '>', '?',
771 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
772 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
773 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
774 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
775 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
776 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
777 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
778 'x', 'y', 'z', '{', '|', '}', '~'
781 code = code < sizeof table ? table[code] : -1;
789 /*----------------------------------------------------------------.
790 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
791 `----------------------------------------------------------------*/
794 handle_syncline (char *args)
796 int lineno = strtol (args, &args, 10);
797 const char *file = NULL;
798 file = strchr (args, '"') + 1;
799 *strchr (file, '"') = 0;
800 scanner_cursor.file = current_file = uniqstr_new (file);
801 scanner_cursor.line = lineno;
802 scanner_cursor.column = 1;
806 /*----------------------------------------------------------------.
807 | For a token or comment starting at START, report message MSGID, |
808 | which should say that an end marker was found before |
809 | the expected TOKEN_END. |
810 `----------------------------------------------------------------*/
813 unexpected_end (boundary start, char const *msgid, char const *token_end)
817 loc.end = scanner_cursor;
818 complain_at (loc, _(msgid), token_end);
822 /*------------------------------------------------------------------------.
823 | Report an unexpected EOF in a token or comment starting at START. |
824 | An end of file was encountered and the expected TOKEN_END was missing. |
825 `------------------------------------------------------------------------*/
828 unexpected_eof (boundary start, char const *token_end)
830 unexpected_end (start, N_("missing `%s' at end of file"), token_end);
834 /*----------------------------------------.
835 | Likewise, but for unexpected newlines. |
836 `----------------------------------------*/
839 unexpected_newline (boundary start, char const *token_end)
841 unexpected_end (start, N_("missing `%s' at end of line"), token_end);
845 /*-------------------------.
846 | Initialize the scanner. |
847 `-------------------------*/
850 scanner_initialize (void)
852 obstack_init (&obstack_for_string);
856 /*-----------------------------------------------.
857 | Free all the memory allocated to the scanner. |
858 `-----------------------------------------------*/
863 obstack_free (&obstack_for_string, 0);
864 /* Reclaim Flex's buffers. */
865 yy_delete_buffer (YY_CURRENT_BUFFER);