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"
35 #define YY_USER_INIT \
37 LOCATION_RESET (*loc); \
38 loc->file = current_file; \
41 /* Each time we match a string, move the end cursor to its end. */
42 #define STEP LOCATION_STEP (*loc)
44 #define YY_USER_ACTION extend_location (loc, yytext, yyleng);
46 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
49 /* Read bytes from FP into buffer BUF of size SIZE. Return the
50 number of bytes read. Remove '\r' from input, treating \r\n
51 and isolated \r as \n. */
54 no_cr_read (FILE *fp, char *buf, size_t size)
56 size_t s = fread (buf, 1, size, fp);
59 char *w = memchr (buf, '\r', s);
63 char const *lim = buf + s;
67 /* Found an '\r'. Treat it like '\n', but ignore any
68 '\n' that immediately follows. */
73 if (ch != '\n' && ungetc (ch, fp) != ch)
79 /* Copy until the next '\r'. */
85 while ((*w++ = *r++) != '\r');
96 /* Extend *LOC to account for token TOKEN of size SIZE. */
99 extend_location (location_t *loc, char const *token, int size)
101 int line = loc->last_line;
102 int column = loc->last_column;
103 char const *p0 = token;
104 char const *p = token;
105 char const *lim = token + size;
107 for (p = token; p < lim; p++)
111 /* \r shouldn't survive no_cr_read. */
121 column += mbsnwidth (p0, p - p0, 0);
122 column += 8 - ((column - 1) & 7);
127 loc->last_line = line;
128 loc->last_column = column + mbsnwidth (p0, p - p0, 0);
133 /* STRING_OBSTACK -- Used to store all the characters that we need to
134 keep (to construct ID, STRINGS etc.). Use the following macros to
137 Use STRING_GROW to append what has just been matched, and
138 STRING_FINISH to end the string (it puts the ending 0).
139 STRING_FINISH also stores this string in LAST_STRING, which can be
140 used, and which is used by STRING_FREE to free the last string. */
142 static struct obstack string_obstack;
144 /* A string representing the most recently saved token. */
145 static char *last_string;
148 #define STRING_GROW \
149 obstack_grow (&string_obstack, yytext, yyleng)
151 #define STRING_FINISH \
153 obstack_1grow (&string_obstack, '\0'); \
154 last_string = obstack_finish (&string_obstack); \
157 #define STRING_FREE \
158 obstack_free (&string_obstack, last_string)
161 scanner_last_string_free (void)
166 /* Within well-formed rules, RULE_LENGTH is the number of values in
167 the current rule so far, which says where to find `$0' with respect
168 to the top of the stack. It is not the same as the rule->length in
169 the case of mid rule actions.
171 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
172 static int rule_length;
174 static void handle_dollar (braced_code_t code_kind,
175 char *cp, location_t location);
176 static void handle_at (braced_code_t code_kind,
177 char *cp, location_t location);
178 static void handle_syncline (char *args, location_t *location);
179 static int convert_ucn_to_byte (char const *hex_text);
180 static void unexpected_end_of_file (location_t *, char const *);
183 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
184 %x SC_STRING SC_CHARACTER
185 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
186 %x SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
188 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
189 id {letter}({letter}|[0-9])*
190 directive %{letter}({letter}|[0-9]|-)*
193 /* POSIX says that a tag must be both an id and a C union member, but
194 historically almost any character is allowed in a tag. We disallow
195 NUL and newline, as this simplifies our implementation. */
198 /* Zero or more instances of backslash-newline. Following GCC, allow
199 white space between the backslash and the newline. */
200 splice (\\[ \f\t\v]*\n)*
204 /* Nesting level of the current code in braces. */
205 int braces_level IF_LINT (= 0);
207 /* Scanner context when scanning C code. */
208 int c_context IF_LINT (= 0);
210 /* At each yylex invocation, mark the current position as the
211 start of the next token. */
216 /*----------------------------.
217 | Scanning Bison directives. |
218 `----------------------------*/
221 "%binary" return PERCENT_NONASSOC;
222 "%debug" return PERCENT_DEBUG;
223 "%define" return PERCENT_DEFINE;
224 "%defines" return PERCENT_DEFINES;
225 "%destructor" return PERCENT_DESTRUCTOR;
226 "%dprec" return PERCENT_DPREC;
227 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
228 "%expect" return PERCENT_EXPECT;
229 "%file-prefix" return PERCENT_FILE_PREFIX;
230 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
231 "%glr-parser" return PERCENT_GLR_PARSER;
232 "%left" return PERCENT_LEFT;
233 "%locations" return PERCENT_LOCATIONS;
234 "%merge" return PERCENT_MERGE;
235 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
236 "%no"[-_]"lines" return PERCENT_NO_LINES;
237 "%nonassoc" return PERCENT_NONASSOC;
238 "%nterm" return PERCENT_NTERM;
239 "%output" return PERCENT_OUTPUT;
240 "%parse-param" return PERCENT_PARSE_PARAM;
241 "%prec" rule_length--; return PERCENT_PREC;
242 "%printer" return PERCENT_PRINTER;
243 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
244 "%right" return PERCENT_RIGHT;
245 "%lex-param" return PERCENT_LEX_PARAM;
246 "%skeleton" return PERCENT_SKELETON;
247 "%start" return PERCENT_START;
248 "%term" return PERCENT_TOKEN;
249 "%token" return PERCENT_TOKEN;
250 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
251 "%type" return PERCENT_TYPE;
252 "%union" return PERCENT_UNION;
253 "%verbose" return PERCENT_VERBOSE;
254 "%yacc" return PERCENT_YACC;
257 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
261 ^"#line "{int}" \"".*"\"\n" {
262 handle_syncline (yytext + sizeof "#line " - 1, loc);
267 ":" rule_length = 0; return COLON;
268 "|" rule_length = 0; return PIPE;
270 ";" return SEMICOLON;
275 val->symbol = symbol_get (yytext, *loc);
283 num = strtoul (yytext, 0, 10);
284 if (INT_MAX < num || errno)
286 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
293 /* Characters. We don't check there is only one. */
294 "'" STRING_GROW; BEGIN SC_ESCAPED_CHARACTER;
297 "\"" STRING_GROW; BEGIN SC_ESCAPED_STRING;
300 "/*" BEGIN SC_YACC_COMMENT;
304 "%{" BEGIN SC_PROLOGUE;
306 /* Code in between braces. */
307 "{" STRING_GROW; braces_level = 0; BEGIN SC_BRACED_CODE;
311 obstack_grow (&string_obstack, yytext + 1, yyleng - 2);
313 val->struniq = struniq_new (last_string);
319 static int percent_percent_count;
320 if (++percent_percent_count == 2)
322 return PERCENT_PERCENT;
326 complain_at (*loc, _("invalid character: %s"), quote (yytext));
332 /*---------------------------------------------------------------.
333 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
334 `---------------------------------------------------------------*/
344 <<EOF>> unexpected_end_of_file (loc, "*/");
348 /*------------------------------------------------------------.
349 | Scanning a C comment. The initial `/ *' is already eaten. |
350 `------------------------------------------------------------*/
354 "*"{splice}"/" STRING_GROW; BEGIN c_context;
355 <<EOF>> unexpected_end_of_file (loc, "*/");
359 /*--------------------------------------------------------------.
360 | Scanning a line comment. The initial `//' is already eaten. |
361 `--------------------------------------------------------------*/
365 "\n" STRING_GROW; BEGIN c_context;
366 {splice} STRING_GROW;
367 <<EOF>> BEGIN c_context;
371 /*----------------------------------------------------------------.
372 | Scanning a C string, including its escapes. The initial `"' is |
374 `----------------------------------------------------------------*/
381 val->string = last_string;
388 <<EOF>> unexpected_end_of_file (loc, "\"");
391 /*---------------------------------------------------------------.
392 | Scanning a C character, decoding its escapes. The initial "'" |
393 | is already eaten. |
394 `---------------------------------------------------------------*/
396 <SC_ESCAPED_CHARACTER>
401 val->symbol = symbol_get (last_string, *loc);
402 symbol_class_set (val->symbol, token_sym, *loc);
403 symbol_user_token_number_set (val->symbol,
404 (unsigned char) last_string[1], *loc);
412 <<EOF>> unexpected_end_of_file (loc, "'");
416 /*----------------------------.
417 | Decode escaped characters. |
418 `----------------------------*/
420 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
423 unsigned long c = strtoul (yytext + 1, 0, 8);
426 complain_at (*loc, _("invalid escape sequence: %s"),
431 obstack_1grow (&string_obstack, c);
437 c = strtoul (yytext + 2, 0, 16);
438 if (UCHAR_MAX < c || errno)
440 complain_at (*loc, _("invalid escape sequence: %s"),
445 obstack_1grow (&string_obstack, c);
448 \\a obstack_1grow (&string_obstack, '\a');
449 \\b obstack_1grow (&string_obstack, '\b');
450 \\f obstack_1grow (&string_obstack, '\f');
451 \\n obstack_1grow (&string_obstack, '\n');
452 \\r obstack_1grow (&string_obstack, '\r');
453 \\t obstack_1grow (&string_obstack, '\t');
454 \\v obstack_1grow (&string_obstack, '\v');
456 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
457 \\("\""|"'"|"?"|"\\") obstack_1grow (&string_obstack, yytext[1]);
459 \\(u|U[0-9a-fA-F]{4})[0-9a-fA-F]{4} {
460 int c = convert_ucn_to_byte (yytext);
463 complain_at (*loc, _("invalid escape sequence: %s"),
468 obstack_1grow (&string_obstack, c);
471 complain_at (*loc, _("unrecognized escape sequence: %s"),
478 /*----------------------------------------------------------.
479 | Scanning a C character without decoding its escapes. The |
480 | initial "'" is already eaten. |
481 `----------------------------------------------------------*/
485 "'" STRING_GROW; BEGIN c_context;
486 \\{splice}[^$@\[\]] STRING_GROW;
487 <<EOF>> unexpected_end_of_file (loc, "'");
491 /*----------------------------------------------------------------.
492 | Scanning a C string, without decoding its escapes. The initial |
493 | `"' is already eaten. |
494 `----------------------------------------------------------------*/
498 "\"" STRING_GROW; BEGIN c_context;
499 \\{splice}[^$@\[\]] STRING_GROW;
500 <<EOF>> unexpected_end_of_file (loc, "\"");
504 /*---------------------------------------------------.
505 | Strings, comments etc. can be found in user code. |
506 `---------------------------------------------------*/
508 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
510 "'" STRING_GROW; c_context = YY_START; BEGIN SC_CHARACTER;
511 "\"" STRING_GROW; c_context = YY_START; BEGIN SC_STRING;
512 "/"{splice}"*" STRING_GROW; c_context = YY_START; BEGIN SC_COMMENT;
513 "/"{splice}"/" STRING_GROW; c_context = YY_START; BEGIN SC_LINE_COMMENT;
517 /*---------------------------------------------------------------.
518 | Scanning some code in braces (%union and actions). The initial |
519 | "{" is already eaten. |
520 `---------------------------------------------------------------*/
524 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
525 "%"{splice}">" STRING_GROW; braces_level--;
529 if (braces_level < 0)
532 val->string = last_string;
539 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
541 "<"{splice}"<" STRING_GROW;
543 "$"("<"{tag}">")?(-?[0-9]+|"$") { handle_dollar (current_braced_code,
545 "@"(-?[0-9]+|"$") { handle_at (current_braced_code,
548 <<EOF>> unexpected_end_of_file (loc, "}");
552 /*--------------------------------------------------------------.
553 | Scanning some prologue: from "%{" (already scanned) to "%}". |
554 `--------------------------------------------------------------*/
560 val->string = last_string;
565 <<EOF>> unexpected_end_of_file (loc, "%}");
569 /*---------------------------------------------------------------.
570 | Scanning the epilogue (everything after the second "%%", which |
571 | has already been eaten). |
572 `---------------------------------------------------------------*/
578 val->string = last_string;
585 /*----------------------------------------------------------------.
586 | By default, grow the string obstack with the input, escaping M4 |
587 | quoting characters. |
588 `----------------------------------------------------------------*/
590 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
592 \$ obstack_sgrow (&string_obstack, "$][");
593 \@ obstack_sgrow (&string_obstack, "@@");
594 \[ obstack_sgrow (&string_obstack, "@{");
595 \] obstack_sgrow (&string_obstack, "@}");
602 /*------------------------------------------------------------------.
603 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
605 | Possible inputs: $[<TYPENAME>]($|integer) |
607 | Output to the STRING_OBSTACK a reference to this semantic value. |
608 `------------------------------------------------------------------*/
611 handle_action_dollar (char *text, location_t location)
613 const char *type_name = NULL;
616 /* Get the type name if explicit. */
629 type_name = symbol_list_n_type_name_get (current_rule, location, 0);
630 if (!type_name && typed)
631 complain_at (location, _("$$ of `%s' has no declared type"),
632 current_rule->sym->tag);
635 obstack_fgrow1 (&string_obstack,
636 "]b4_lhs_value([%s])[", type_name);
642 num = strtol (cp, 0, 10);
644 if (INT_MIN <= num && num <= rule_length && ! errno)
647 if (!type_name && n > 0)
648 type_name = symbol_list_n_type_name_get (current_rule, location,
650 if (!type_name && typed)
651 complain_at (location, _("$%d of `%s' has no declared type"),
652 n, current_rule->sym->tag);
655 obstack_fgrow3 (&string_obstack,
656 "]b4_rhs_value([%d], [%d], [%s])[",
657 rule_length, n, type_name);
660 complain_at (location, _("integer out of range: %s"), quote (text));
665 /*---------------------------------------------------------------.
666 | TEXT is expected to be $$ in some code associated to a symbol: |
667 | destructor or printer. |
668 `---------------------------------------------------------------*/
671 handle_symbol_code_dollar (char *text, location_t location)
675 obstack_sgrow (&string_obstack, "]b4_dollar_dollar[");
677 complain_at (location, _("invalid value: %s"), quote (text));
681 /*-----------------------------------------------------------------.
682 | Dispatch onto handle_action_dollar, or handle_destructor_dollar, |
683 | depending upon CODE_KIND. |
684 `-----------------------------------------------------------------*/
687 handle_dollar (braced_code_t braced_code_kind,
688 char *text, location_t location)
690 switch (braced_code_kind)
692 case action_braced_code:
693 handle_action_dollar (text, location);
696 case destructor_braced_code:
697 case printer_braced_code:
698 handle_symbol_code_dollar (text, location);
704 /*------------------------------------------------------.
705 | TEXT is a location token (i.e., a `@...'). Output to |
706 | STRING_OBSTACK a reference to this location. |
707 `------------------------------------------------------*/
710 handle_action_at (char *text, location_t location)
717 obstack_sgrow (&string_obstack, "]b4_lhs_location[");
723 num = strtol (cp, 0, 10);
725 if (INT_MIN <= num && num <= rule_length && ! errno)
728 obstack_fgrow2 (&string_obstack, "]b4_rhs_location([%d], [%d])[",
732 complain_at (location, _("integer out of range: %s"), quote (text));
737 /*---------------------------------------------------------------.
738 | TEXT is expected to be @$ in some code associated to a symbol: |
739 | destructor or printer. |
740 `---------------------------------------------------------------*/
743 handle_symbol_code_at (char *text, location_t location)
747 obstack_sgrow (&string_obstack, "]b4_at_dollar[");
749 complain_at (location, _("invalid value: %s"), quote (text));
753 /*-------------------------------------------------------------------.
754 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
756 `-------------------------------------------------------------------*/
759 handle_at (braced_code_t braced_code_kind,
760 char *text, location_t location)
762 switch (braced_code_kind)
764 case action_braced_code:
765 handle_action_at (text, location);
768 case destructor_braced_code:
769 case printer_braced_code:
770 handle_symbol_code_at (text, location);
776 /*------------------------------------------------------------------.
777 | Convert universal character name UCN to a single-byte character, |
778 | and return that character. Return -1 if UCN does not correspond |
779 | to a single-byte character. |
780 `------------------------------------------------------------------*/
783 convert_ucn_to_byte (char const *ucn)
785 unsigned long code = strtoul (ucn + 2, 0, 16);
787 /* FIXME: Currently we assume Unicode-compatible unibyte characters
788 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
789 non-ASCII hosts we support only the portable C character set.
790 These limitations should be removed once we add support for
791 multibyte characters. */
793 if (UCHAR_MAX < code)
796 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
798 /* A non-ASCII host. Use CODE to index into a table of the C
799 basic execution character set, which is guaranteed to exist on
800 all Standard C platforms. This table also includes '$', '@',
801 and '`', which are not in the basic execution character set but
802 which are unibyte characters on all the platforms that we know
804 static signed char const table[] =
806 '\0', -1, -1, -1, -1, -1, -1, '\a',
807 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
808 -1, -1, -1, -1, -1, -1, -1, -1,
809 -1, -1, -1, -1, -1, -1, -1, -1,
810 ' ', '!', '"', '#', '$', '%', '&', '\'',
811 '(', ')', '*', '+', ',', '-', '.', '/',
812 '0', '1', '2', '3', '4', '5', '6', '7',
813 '8', '9', ':', ';', '<', '=', '>', '?',
814 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
815 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
816 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
817 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
818 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
819 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
820 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
821 'x', 'y', 'z', '{', '|', '}', '~'
824 code = code < sizeof table ? table[code] : -1;
832 /*----------------------------------------------------------------.
833 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
834 `----------------------------------------------------------------*/
837 handle_syncline (char *args, location_t *location)
839 int lineno = strtol (args, &args, 10);
840 const char *file = NULL;
841 file = strchr (args, '"') + 1;
842 *strchr (file, '"') = 0;
843 current_file = xstrdup (file);
844 location->file = current_file;
845 location->last_line = lineno;
849 /*-------------------------------------------------------------.
850 | Report an unexpected end of file at LOC. An end of file was |
851 | encountered and the expected TOKEN_END was missing. After |
852 | reporting the problem, pretend that TOKEN_END was found. |
853 `-------------------------------------------------------------*/
856 unexpected_end_of_file (location_t *loc, char const *token_end)
858 size_t i = strlen (token_end);
860 complain_at (*loc, _("missing `%s' at end of file"), token_end);
862 /* Adjust location's last column so that any later message does not
863 mention the characters just inserted. */
864 loc->last_column -= i;
867 unput (token_end[--i]);
871 /*-------------------------.
872 | Initialize the scanner. |
873 `-------------------------*/
876 scanner_initialize (void)
878 obstack_init (&string_obstack);
882 /*-----------------------------------------------.
883 | Free all the memory allocated to the scanner. |
884 `-----------------------------------------------*/
889 obstack_free (&string_obstack, 0);
890 /* Reclaim Flex's buffers. */
891 yy_delete_buffer (YY_CURRENT_BUFFER);