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 static void extend_location (location_t *, char const *, int);
45 #define YY_USER_ACTION extend_location (loc, yytext, yyleng);
47 static size_t no_cr_read (FILE *, char *, size_t);
48 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
51 /* STRING_OBSTACK -- Used to store all the characters that we need to
52 keep (to construct ID, STRINGS etc.). Use the following macros to
55 Use STRING_GROW to append what has just been matched, and
56 STRING_FINISH to end the string (it puts the ending 0).
57 STRING_FINISH also stores this string in LAST_STRING, which can be
58 used, and which is used by STRING_FREE to free the last string. */
60 static struct obstack string_obstack;
62 /* A string representing the most recently saved token. */
63 static char *last_string;
67 obstack_grow (&string_obstack, yytext, yyleng)
69 #define STRING_FINISH \
71 obstack_1grow (&string_obstack, '\0'); \
72 last_string = obstack_finish (&string_obstack); \
76 obstack_free (&string_obstack, last_string)
79 scanner_last_string_free (void)
84 /* Within well-formed rules, RULE_LENGTH is the number of values in
85 the current rule so far, which says where to find `$0' with respect
86 to the top of the stack. It is not the same as the rule->length in
87 the case of mid rule actions.
89 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
90 static int rule_length;
92 static void handle_dollar (braced_code_t code_kind,
93 char *cp, location_t location);
94 static void handle_at (braced_code_t code_kind,
95 char *cp, location_t location);
96 static void handle_syncline (char *args, location_t *location);
97 static int convert_ucn_to_byte (char const *hex_text);
98 static void unexpected_end_of_file (location_t *, char const *);
101 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
102 %x SC_STRING SC_CHARACTER
103 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
104 %x SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
106 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
107 id {letter}({letter}|[0-9])*
108 directive %{letter}({letter}|[0-9]|-)*
111 /* POSIX says that a tag must be both an id and a C union member, but
112 historically almost any character is allowed in a tag. We disallow
113 NUL and newline, as this simplifies our implementation. */
116 /* Zero or more instances of backslash-newline. Following GCC, allow
117 white space between the backslash and the newline. */
118 splice (\\[ \f\t\v]*\n)*
122 /* Nesting level of the current code in braces. */
123 int braces_level IF_LINT (= 0);
125 /* Scanner context when scanning C code. */
126 int c_context IF_LINT (= 0);
128 /* At each yylex invocation, mark the current position as the
129 start of the next token. */
134 /*----------------------------.
135 | Scanning Bison directives. |
136 `----------------------------*/
139 "%binary" return PERCENT_NONASSOC;
140 "%debug" return PERCENT_DEBUG;
141 "%define" return PERCENT_DEFINE;
142 "%defines" return PERCENT_DEFINES;
143 "%destructor" return PERCENT_DESTRUCTOR;
144 "%dprec" return PERCENT_DPREC;
145 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
146 "%expect" return PERCENT_EXPECT;
147 "%file-prefix" return PERCENT_FILE_PREFIX;
148 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
149 "%glr-parser" return PERCENT_GLR_PARSER;
150 "%left" return PERCENT_LEFT;
151 "%locations" return PERCENT_LOCATIONS;
152 "%merge" return PERCENT_MERGE;
153 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
154 "%no"[-_]"lines" return PERCENT_NO_LINES;
155 "%nonassoc" return PERCENT_NONASSOC;
156 "%nterm" return PERCENT_NTERM;
157 "%output" return PERCENT_OUTPUT;
158 "%parse-param" return PERCENT_PARSE_PARAM;
159 "%prec" rule_length--; return PERCENT_PREC;
160 "%printer" return PERCENT_PRINTER;
161 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
162 "%right" return PERCENT_RIGHT;
163 "%lex-param" return PERCENT_LEX_PARAM;
164 "%skeleton" return PERCENT_SKELETON;
165 "%start" return PERCENT_START;
166 "%term" return PERCENT_TOKEN;
167 "%token" return PERCENT_TOKEN;
168 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
169 "%type" return PERCENT_TYPE;
170 "%union" return PERCENT_UNION;
171 "%verbose" return PERCENT_VERBOSE;
172 "%yacc" return PERCENT_YACC;
175 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
179 ^"#line "{int}" \"".*"\"\n" {
180 handle_syncline (yytext + sizeof "#line " - 1, loc);
185 ":" rule_length = 0; return COLON;
186 "|" rule_length = 0; return PIPE;
187 ";" return SEMICOLON;
192 warn_at (*loc, _("stray `,' treated as white space"));
197 val->symbol = symbol_get (yytext, *loc);
205 num = strtoul (yytext, 0, 10);
206 if (INT_MAX < num || errno)
208 complain_at (*loc, _("integer out of range: %s"), quote (yytext));
215 /* Characters. We don't check there is only one. */
216 "'" STRING_GROW; BEGIN SC_ESCAPED_CHARACTER;
219 "\"" STRING_GROW; BEGIN SC_ESCAPED_STRING;
222 "/*" BEGIN SC_YACC_COMMENT;
226 "%{" BEGIN SC_PROLOGUE;
228 /* Code in between braces. */
229 "{" STRING_GROW; braces_level = 0; BEGIN SC_BRACED_CODE;
233 obstack_grow (&string_obstack, yytext + 1, yyleng - 2);
235 val->struniq = struniq_new (last_string);
241 static int percent_percent_count;
242 if (++percent_percent_count == 2)
244 return PERCENT_PERCENT;
248 complain_at (*loc, _("invalid character: %s"), quote (yytext));
254 /*---------------------------------------------------------------.
255 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
256 `---------------------------------------------------------------*/
266 <<EOF>> unexpected_end_of_file (loc, "*/");
270 /*------------------------------------------------------------.
271 | Scanning a C comment. The initial `/ *' is already eaten. |
272 `------------------------------------------------------------*/
276 "*"{splice}"/" STRING_GROW; BEGIN c_context;
277 <<EOF>> unexpected_end_of_file (loc, "*/");
281 /*--------------------------------------------------------------.
282 | Scanning a line comment. The initial `//' is already eaten. |
283 `--------------------------------------------------------------*/
287 "\n" STRING_GROW; BEGIN c_context;
288 {splice} STRING_GROW;
289 <<EOF>> BEGIN c_context;
293 /*----------------------------------------------------------------.
294 | Scanning a C string, including its escapes. The initial `"' is |
296 `----------------------------------------------------------------*/
303 val->string = last_string;
310 <<EOF>> unexpected_end_of_file (loc, "\"");
313 /*---------------------------------------------------------------.
314 | Scanning a C character, decoding its escapes. The initial "'" |
315 | is already eaten. |
316 `---------------------------------------------------------------*/
318 <SC_ESCAPED_CHARACTER>
323 val->symbol = symbol_get (last_string, *loc);
324 symbol_class_set (val->symbol, token_sym, *loc);
325 symbol_user_token_number_set (val->symbol,
326 (unsigned char) last_string[1], *loc);
334 <<EOF>> unexpected_end_of_file (loc, "'");
338 /*----------------------------.
339 | Decode escaped characters. |
340 `----------------------------*/
342 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
345 unsigned long c = strtoul (yytext + 1, 0, 8);
348 complain_at (*loc, _("invalid escape sequence: %s"),
353 obstack_1grow (&string_obstack, c);
356 \\x[0-9abcdefABCDEF]+ {
359 c = strtoul (yytext + 2, 0, 16);
360 if (UCHAR_MAX < c || errno)
362 complain_at (*loc, _("invalid escape sequence: %s"),
367 obstack_1grow (&string_obstack, c);
370 \\a obstack_1grow (&string_obstack, '\a');
371 \\b obstack_1grow (&string_obstack, '\b');
372 \\f obstack_1grow (&string_obstack, '\f');
373 \\n obstack_1grow (&string_obstack, '\n');
374 \\r obstack_1grow (&string_obstack, '\r');
375 \\t obstack_1grow (&string_obstack, '\t');
376 \\v obstack_1grow (&string_obstack, '\v');
378 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
379 \\("\""|"'"|"?"|"\\") obstack_1grow (&string_obstack, yytext[1]);
381 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
382 int c = convert_ucn_to_byte (yytext);
385 complain_at (*loc, _("invalid escape sequence: %s"),
390 obstack_1grow (&string_obstack, c);
393 complain_at (*loc, _("unrecognized escape sequence: %s"),
400 /*----------------------------------------------------------.
401 | Scanning a C character without decoding its escapes. The |
402 | initial "'" is already eaten. |
403 `----------------------------------------------------------*/
407 "'" STRING_GROW; BEGIN c_context;
408 \\{splice}[^$@\[\]] STRING_GROW;
409 <<EOF>> unexpected_end_of_file (loc, "'");
413 /*----------------------------------------------------------------.
414 | Scanning a C string, without decoding its escapes. The initial |
415 | `"' is already eaten. |
416 `----------------------------------------------------------------*/
420 "\"" STRING_GROW; BEGIN c_context;
421 \\{splice}[^$@\[\]] STRING_GROW;
422 <<EOF>> unexpected_end_of_file (loc, "\"");
426 /*---------------------------------------------------.
427 | Strings, comments etc. can be found in user code. |
428 `---------------------------------------------------*/
430 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
432 "'" STRING_GROW; c_context = YY_START; BEGIN SC_CHARACTER;
433 "\"" STRING_GROW; c_context = YY_START; BEGIN SC_STRING;
434 "/"{splice}"*" STRING_GROW; c_context = YY_START; BEGIN SC_COMMENT;
435 "/"{splice}"/" STRING_GROW; c_context = YY_START; BEGIN SC_LINE_COMMENT;
439 /*---------------------------------------------------------------.
440 | Scanning some code in braces (%union and actions). The initial |
441 | "{" is already eaten. |
442 `---------------------------------------------------------------*/
446 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
447 "%"{splice}">" STRING_GROW; braces_level--;
451 if (braces_level < 0)
454 val->string = last_string;
461 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
463 "<"{splice}"<" STRING_GROW;
465 "$"("<"{tag}">")?(-?[0-9]+|"$") { handle_dollar (current_braced_code,
467 "@"(-?[0-9]+|"$") { handle_at (current_braced_code,
470 <<EOF>> unexpected_end_of_file (loc, "}");
474 /*--------------------------------------------------------------.
475 | Scanning some prologue: from "%{" (already scanned) to "%}". |
476 `--------------------------------------------------------------*/
482 val->string = last_string;
487 <<EOF>> unexpected_end_of_file (loc, "%}");
491 /*---------------------------------------------------------------.
492 | Scanning the epilogue (everything after the second "%%", which |
493 | has already been eaten). |
494 `---------------------------------------------------------------*/
500 val->string = last_string;
507 /*----------------------------------------------------------------.
508 | By default, grow the string obstack with the input, escaping M4 |
509 | quoting characters. |
510 `----------------------------------------------------------------*/
512 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
514 \$ obstack_sgrow (&string_obstack, "$][");
515 \@ obstack_sgrow (&string_obstack, "@@");
516 \[ obstack_sgrow (&string_obstack, "@{");
517 \] obstack_sgrow (&string_obstack, "@}");
524 /* Extend *LOC to account for token TOKEN of size SIZE. */
527 extend_location (location_t *loc, char const *token, int size)
529 int line = loc->last_line;
530 int column = loc->last_column;
531 char const *p0 = token;
532 char const *p = token;
533 char const *lim = token + size;
535 for (p = token; p < lim; p++)
539 /* \r shouldn't survive no_cr_read. */
549 column += mbsnwidth (p0, p - p0, 0);
550 column += 8 - ((column - 1) & 7);
555 loc->last_line = line;
556 loc->last_column = column + mbsnwidth (p0, p - p0, 0);
560 /* Read bytes from FP into buffer BUF of size SIZE. Return the
561 number of bytes read. Remove '\r' from input, treating \r\n
562 and isolated \r as \n. */
565 no_cr_read (FILE *fp, char *buf, size_t size)
567 size_t s = fread (buf, 1, size, fp);
570 char *w = memchr (buf, '\r', s);
574 char const *lim = buf + s;
578 /* Found an '\r'. Treat it like '\n', but ignore any
579 '\n' that immediately follows. */
584 if (ch != '\n' && ungetc (ch, fp) != ch)
590 /* Copy until the next '\r'. */
596 while ((*w++ = *r++) != '\r');
607 /*------------------------------------------------------------------.
608 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
610 | Possible inputs: $[<TYPENAME>]($|integer) |
612 | Output to the STRING_OBSTACK a reference to this semantic value. |
613 `------------------------------------------------------------------*/
616 handle_action_dollar (char *text, location_t location)
618 const char *type_name = NULL;
621 /* Get the type name if explicit. */
634 type_name = symbol_list_n_type_name_get (current_rule, location, 0);
635 if (!type_name && typed)
636 complain_at (location, _("$$ of `%s' has no declared type"),
637 current_rule->sym->tag);
640 obstack_fgrow1 (&string_obstack,
641 "]b4_lhs_value([%s])[", type_name);
647 num = strtol (cp, 0, 10);
649 if (INT_MIN <= num && num <= rule_length && ! errno)
652 if (!type_name && n > 0)
653 type_name = symbol_list_n_type_name_get (current_rule, location,
655 if (!type_name && typed)
656 complain_at (location, _("$%d of `%s' has no declared type"),
657 n, current_rule->sym->tag);
660 obstack_fgrow3 (&string_obstack,
661 "]b4_rhs_value([%d], [%d], [%s])[",
662 rule_length, n, type_name);
665 complain_at (location, _("integer out of range: %s"), quote (text));
670 /*---------------------------------------------------------------.
671 | TEXT is expected to be $$ in some code associated to a symbol: |
672 | destructor or printer. |
673 `---------------------------------------------------------------*/
676 handle_symbol_code_dollar (char *text, location_t location)
680 obstack_sgrow (&string_obstack, "]b4_dollar_dollar[");
682 complain_at (location, _("invalid value: %s"), quote (text));
686 /*-----------------------------------------------------------------.
687 | Dispatch onto handle_action_dollar, or handle_destructor_dollar, |
688 | depending upon CODE_KIND. |
689 `-----------------------------------------------------------------*/
692 handle_dollar (braced_code_t braced_code_kind,
693 char *text, location_t location)
695 switch (braced_code_kind)
697 case action_braced_code:
698 handle_action_dollar (text, location);
701 case destructor_braced_code:
702 case printer_braced_code:
703 handle_symbol_code_dollar (text, location);
709 /*------------------------------------------------------.
710 | TEXT is a location token (i.e., a `@...'). Output to |
711 | STRING_OBSTACK a reference to this location. |
712 `------------------------------------------------------*/
715 handle_action_at (char *text, location_t location)
722 obstack_sgrow (&string_obstack, "]b4_lhs_location[");
728 num = strtol (cp, 0, 10);
730 if (INT_MIN <= num && num <= rule_length && ! errno)
733 obstack_fgrow2 (&string_obstack, "]b4_rhs_location([%d], [%d])[",
737 complain_at (location, _("integer out of range: %s"), quote (text));
742 /*---------------------------------------------------------------.
743 | TEXT is expected to be @$ in some code associated to a symbol: |
744 | destructor or printer. |
745 `---------------------------------------------------------------*/
748 handle_symbol_code_at (char *text, location_t location)
752 obstack_sgrow (&string_obstack, "]b4_at_dollar[");
754 complain_at (location, _("invalid value: %s"), quote (text));
758 /*-------------------------------------------------------------------.
759 | Dispatch onto handle_action_at, or handle_destructor_at, depending |
761 `-------------------------------------------------------------------*/
764 handle_at (braced_code_t braced_code_kind,
765 char *text, location_t location)
767 switch (braced_code_kind)
769 case action_braced_code:
770 handle_action_at (text, location);
773 case destructor_braced_code:
774 case printer_braced_code:
775 handle_symbol_code_at (text, location);
781 /*------------------------------------------------------------------.
782 | Convert universal character name UCN to a single-byte character, |
783 | and return that character. Return -1 if UCN does not correspond |
784 | to a single-byte character. |
785 `------------------------------------------------------------------*/
788 convert_ucn_to_byte (char const *ucn)
790 unsigned long code = strtoul (ucn + 2, 0, 16);
792 /* FIXME: Currently we assume Unicode-compatible unibyte characters
793 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
794 non-ASCII hosts we support only the portable C character set.
795 These limitations should be removed once we add support for
796 multibyte characters. */
798 if (UCHAR_MAX < code)
801 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
803 /* A non-ASCII host. Use CODE to index into a table of the C
804 basic execution character set, which is guaranteed to exist on
805 all Standard C platforms. This table also includes '$', '@',
806 and '`', which are not in the basic execution character set but
807 which are unibyte characters on all the platforms that we know
809 static signed char const table[] =
811 '\0', -1, -1, -1, -1, -1, -1, '\a',
812 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
813 -1, -1, -1, -1, -1, -1, -1, -1,
814 -1, -1, -1, -1, -1, -1, -1, -1,
815 ' ', '!', '"', '#', '$', '%', '&', '\'',
816 '(', ')', '*', '+', ',', '-', '.', '/',
817 '0', '1', '2', '3', '4', '5', '6', '7',
818 '8', '9', ':', ';', '<', '=', '>', '?',
819 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
820 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
821 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
822 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
823 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
824 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
825 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
826 'x', 'y', 'z', '{', '|', '}', '~'
829 code = code < sizeof table ? table[code] : -1;
837 /*----------------------------------------------------------------.
838 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
839 `----------------------------------------------------------------*/
842 handle_syncline (char *args, location_t *location)
844 int lineno = strtol (args, &args, 10);
845 const char *file = NULL;
846 file = strchr (args, '"') + 1;
847 *strchr (file, '"') = 0;
848 current_file = xstrdup (file);
849 location->file = current_file;
850 location->last_line = lineno;
854 /*-------------------------------------------------------------.
855 | Report an unexpected end of file at LOC. An end of file was |
856 | encountered and the expected TOKEN_END was missing. After |
857 | reporting the problem, pretend that TOKEN_END was found. |
858 `-------------------------------------------------------------*/
861 unexpected_end_of_file (location_t *loc, char const *token_end)
863 size_t i = strlen (token_end);
865 complain_at (*loc, _("missing `%s' at end of file"), token_end);
867 /* Adjust location's last column so that any later message does not
868 mention the characters just inserted. */
869 loc->last_column -= i;
872 unput (token_end[--i]);
876 /*-------------------------.
877 | Initialize the scanner. |
878 `-------------------------*/
881 scanner_initialize (void)
883 obstack_init (&string_obstack);
887 /*-----------------------------------------------.
888 | Free all the memory allocated to the scanner. |
889 `-----------------------------------------------*/
894 obstack_free (&string_obstack, 0);
895 /* Reclaim Flex's buffers. */
896 yy_delete_buffer (YY_CURRENT_BUFFER);