1 /* Bison Action Scanner -*- C -*-
3 Copyright (C) 2006-2012 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 3 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, see <http://www.gnu.org/licenses/>. */
20 %option debug nodefault noinput nounput noyywrap never-interactive
21 %option prefix="code_" outfile="lex.yy.c"
24 /* Work around a bug in flex 2.5.31. See Debian bug 333231
25 <http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=333231>. */
29 #define FLEX_PREFIX(Id) code_ ## Id
30 #include <src/flex-scanner.h>
32 #include <src/complain.h>
33 #include <src/reader.h>
34 #include <src/getargs.h>
35 #include <src/muscle-tab.h>
36 #include <src/scan-code.h>
37 #include <src/symlist.h>
40 #include <get-errno.h>
43 /* The current calling start condition: SC_RULE_ACTION or
45 # define YY_DECL static char *code_lex (code_props *self, int sc_context)
48 #define YY_USER_ACTION location_compute (loc, &loc->end, yytext, yyleng);
50 static char *fetch_type_name (char *cp, char const **type_name,
53 static void handle_action_dollar (symbol_list *rule, char *cp,
55 static void handle_action_at (symbol_list *rule, char *cp, location at_loc);
57 /* A string to be pushed to obstack after dollar/at has been handled. */
58 static char *ref_tail_fields;
60 static location the_location;
61 static location *loc = &the_location;
63 /* A string representing the most recent translation. */
64 static char *last_string;
66 /* True if an untyped $$ or $n was seen. */
67 static bool untyped_var_seen;
70 /* C and C++ comments in code. */
71 %x SC_COMMENT SC_LINE_COMMENT
72 /* Strings and characters in code. */
73 %x SC_STRING SC_CHARACTER
74 /* Whether in a rule or symbol action. Specifies the translation
76 %x SC_RULE_ACTION SC_SYMBOL_ACTION
79 /* POSIX says that a tag must be both an id and a C union member, but
80 historically almost any character is allowed in a tag. We disallow
81 NUL and newline, as this simplifies our implementation. */
84 /* Zero or more instances of backslash-newline. Following GCC, allow
85 white space between the backslash and the newline. */
86 splice (\\[ \f\t\v]*\n)*
88 /* C style identifier. Must start with letter. Will be used for
89 named symbol references. Shall be kept synchronized with
90 scan-gram.l "letter" and "id". */
91 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
92 id {letter}({letter}|[-0-9])*
93 ref -?[0-9]+|{id}|"["{id}"]"|"$"
98 /* Nesting level of the current code in braces. */
101 /* Whether a semicolon is probably needed.
103 The heuristic is that a semicolon is not needed after '{', '}',
104 ';', or a C preprocessor directive, and that whitespaces and
105 comments do not affect this flag. Note that '{' does not need a
106 semicolon because of '{}'. A semicolon may be needed before a
107 cpp directive, but don't bother.
109 While it is maintained in several start-conditions (factoring
110 opportunities), it is meaningful only for SC_RULE_ACTION. */
111 bool need_semicolon = false;
113 /* Whether in a C preprocessor directive. Don't use a start condition
114 for this because, at the end of strings and comments, we still need
115 to know whether we're in a directive. */
118 /* This scanner is special: it is invoked only once, henceforth
119 is expected to return only once. This initialization is
120 therefore done once per action to translate. */
121 aver (sc_context == SC_SYMBOL_ACTION
122 || sc_context == SC_RULE_ACTION
123 || sc_context == INITIAL);
127 /*------------------------------------------------------------.
128 | Scanning a C comment. The initial '/ *' is already eaten. |
129 `------------------------------------------------------------*/
133 "*"{splice}"/" STRING_GROW; BEGIN sc_context;
137 /*--------------------------------------------------------------.
138 | Scanning a line comment. The initial '//' is already eaten. |
139 `--------------------------------------------------------------*/
143 "\n" STRING_GROW; BEGIN sc_context;
144 {splice} STRING_GROW;
148 /*--------------------------------------------.
149 | Scanning user-code characters and strings. |
150 `--------------------------------------------*/
152 <SC_CHARACTER,SC_STRING>
154 {splice}|\\{splice}. STRING_GROW;
159 "'" STRING_GROW; BEGIN sc_context;
164 "\"" STRING_GROW; BEGIN sc_context;
168 <SC_RULE_ACTION,SC_SYMBOL_ACTION>
173 need_semicolon = true;
178 need_semicolon = true;
186 BEGIN SC_LINE_COMMENT;
189 complain_at (*loc, Wother, _("stray '%s'"), yytext);
190 obstack_escape (&obstack_for_string, yytext);
191 need_semicolon = true;
194 obstack_escape (&obstack_for_string, yytext);
195 need_semicolon = true;
201 "$"("<"{tag}">")?{ref} {
202 ref_tail_fields = NULL;
203 handle_action_dollar (self->rule, yytext, *loc);
205 obstack_sgrow (&obstack_for_string, ref_tail_fields);
206 need_semicolon = true;
209 ref_tail_fields = NULL;
210 handle_action_at (self->rule, yytext, *loc);
212 obstack_sgrow (&obstack_for_string, ref_tail_fields);
213 need_semicolon = true;
216 ";" STRING_GROW; need_semicolon = false;
217 "{" STRING_GROW; ++braces_level; need_semicolon = false;
219 bool outer_brace = --braces_level == 0;
221 /* As an undocumented Bison extension, append ';' before the last
222 brace in braced code, so that the user code can omit trailing
223 ';'. But do not append ';' if emulating Yacc, since Yacc does
225 if (outer_brace && !yacc_flag && language_prio == default_prio
226 && skeleton_prio == default_prio && need_semicolon && ! in_cpp)
228 complain_at (*loc, Wother,
229 _("a ';' might be needed at the end of action code"));
230 complain_at (*loc, Wother,
231 _("future versions of Bison will not add the ';'"));
232 obstack_1grow (&obstack_for_string, ';');
236 need_semicolon = false;
239 /* Preprocessing directives should only be recognized at the beginning
240 of lines, allowing whitespace including comments, but in C/C++,
241 '#' can only be the start of preprocessor directives or within
242 '#define' directives anyway, so don't bother with begin of line. */
243 "#" STRING_GROW; in_cpp = true;
245 {splice} STRING_GROW;
246 [\n\r] STRING_GROW; if (in_cpp) in_cpp = need_semicolon = false;
248 . STRING_GROW; need_semicolon = true;
253 "$"("<"{tag}">")?"$" {
254 const char *type_name = NULL;
255 fetch_type_name (yytext + 1, &type_name, *loc)[-1] = 0;
256 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar(");
257 obstack_quote (&obstack_for_string, type_name);
258 obstack_sgrow (&obstack_for_string, ")[");
259 self->is_value_used = true;
262 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
263 muscle_percent_define_ensure("locations", the_location, true);
270 /* Escape M4 quoting characters in C code. */
271 [$@\[\]] obstack_escape (&obstack_for_string, yytext);
273 /* By default, grow the string obstack with the input. */
276 /* End of processing. */
277 <<EOF>> STRING_FINISH; return last_string;
283 is_dot_or_dash (char ch)
285 return ch == '.' || ch == '-';
289 contains_dot_or_dash (const char* p)
292 if (is_dot_or_dash (*p))
297 /* Defines a variant of a symbolic name resolution. */
300 /* Index in symbol list. */
301 unsigned symbol_index;
303 /* Matched symbol id and loc. */
307 /* Hiding named reference. */
308 named_ref* hidden_by;
310 /* Error flags. May contain zero (no errors) or
311 a combination of VARIANT_* values. */
315 /* Set when the variant refers to a symbol hidden
316 by an explicit symbol reference. */
317 #define VARIANT_HIDDEN (1 << 0)
319 /* Set when the variant refers to a symbol containing
320 dots or dashes. Will require explicit bracketing. */
321 #define VARIANT_BAD_BRACKETING (1 << 1)
323 /* Set when the variant refers to a symbol which is
324 not visible from current midrule. */
325 #define VARIANT_NOT_VISIBLE_FROM_MIDRULE (1 << 2)
327 static variant *variant_table = NULL;
328 static unsigned variant_table_size = 0;
329 static unsigned variant_count = 0;
332 variant_table_grow (void)
335 if (variant_count > variant_table_size)
337 while (variant_count > variant_table_size)
338 variant_table_size = 2 * variant_table_size + 3;
339 variant_table = xnrealloc (variant_table, variant_table_size,
340 sizeof *variant_table);
342 return &variant_table[variant_count - 1];
346 variant_table_free (void)
348 free (variant_table);
349 variant_table = NULL;
350 variant_table_size = variant_count = 0;
354 find_prefix_end (const char *prefix, char *begin, char *end)
358 for (; *prefix && ptr != end; ++prefix, ++ptr)
369 variant_add (uniqstr id, location id_loc, unsigned symbol_index,
370 char *cp, char *cp_end, bool explicit_bracketing)
374 prefix_end = find_prefix_end (id, cp, cp_end);
376 (prefix_end == cp_end ||
377 (!explicit_bracketing && is_dot_or_dash (*prefix_end))))
379 variant *r = variant_table_grow ();
380 r->symbol_index = symbol_index;
392 get_at_spec(unsigned symbol_index)
394 static char at_buf[20];
395 if (symbol_index == 0)
396 strcpy (at_buf, "$$");
398 snprintf (at_buf, sizeof at_buf, "$%u", symbol_index);
403 show_sub_messages (const char* cp, bool explicit_bracketing,
404 int midrule_rhs_index, char dollar_or_at,
405 bool is_warning, unsigned indent)
409 for (i = 0; i < variant_count; ++i)
411 const variant *var = &variant_table[i];
412 const char *at_spec = get_at_spec (var->symbol_index);
417 complain_at_indent (var->loc, Wother, &indent,
418 _("refers to: %c%s at %s"), dollar_or_at,
421 complain_at_indent (var->loc, complaint, &indent,
422 _("refers to: %c%s at %s"), dollar_or_at,
427 static struct obstack msg_buf;
428 const char *tail = explicit_bracketing ? "" :
429 cp + strlen (var->id);
430 const char *id = var->hidden_by ? var->hidden_by->id :
432 location id_loc = var->hidden_by ? var->hidden_by->loc :
435 /* Create the explanation message. */
436 obstack_init (&msg_buf);
438 obstack_printf (&msg_buf, _("possibly meant: %c"), dollar_or_at);
439 if (contains_dot_or_dash (id))
440 obstack_printf (&msg_buf, "[%s]", id);
442 obstack_sgrow (&msg_buf, id);
443 obstack_sgrow (&msg_buf, tail);
445 if (var->err & VARIANT_HIDDEN)
447 obstack_printf (&msg_buf, _(", hiding %c"), dollar_or_at);
448 if (contains_dot_or_dash (var->id))
449 obstack_printf (&msg_buf, "[%s]", var->id);
451 obstack_sgrow (&msg_buf, var->id);
452 obstack_sgrow (&msg_buf, tail);
455 obstack_printf (&msg_buf, _(" at %s"), at_spec);
457 if (var->err & VARIANT_NOT_VISIBLE_FROM_MIDRULE)
460 _(", cannot be accessed from mid-rule action at $%d");
461 obstack_printf (&msg_buf, format, midrule_rhs_index);
464 obstack_1grow (&msg_buf, '\0');
466 complain_at_indent (id_loc, Wother, &indent, "%s",
467 (char *) obstack_finish (&msg_buf));
469 complain_at_indent (id_loc, complaint, &indent, "%s",
470 (char *) obstack_finish (&msg_buf));
471 obstack_free (&msg_buf, 0);
476 /* Returned from "parse_ref" when the reference
478 #define INVALID_REF (INT_MIN)
480 /* Returned from "parse_ref" when the reference
481 points to LHS ($$) of the current rule or midrule. */
482 #define LHS_REF (INT_MIN + 1)
484 /* Sub-messages indent. */
485 #define SUB_INDENT (4)
487 /* Parse named or positional reference. In case of positional
488 references, can return negative values for $-n "deep" stack
491 parse_ref (char *cp, symbol_list *rule, int rule_length,
492 int midrule_rhs_index, char *text, location text_loc,
497 bool explicit_bracketing;
499 unsigned valid_variants = 0;
500 unsigned valid_variant_index = 0;
505 if (c_isdigit (*cp) || (*cp == '-' && c_isdigit (* (cp + 1))))
507 long int num = strtol (cp, &cp, 10);
508 if (1 - INT_MAX + rule_length <= num && num <= rule_length)
512 complain_at (text_loc, complaint, _("integer out of range: %s"),
520 /* Ignore the brackets. */
522 for (p = ++cp; *p != ']'; ++p)
526 explicit_bracketing = true;
530 /* Take all characters of the name. */
532 for (p = cp; *p; ++p)
533 if (is_dot_or_dash (*p))
538 for (p = cp; *p; ++p)
542 explicit_bracketing = false;
545 /* Add all relevant variants. */
547 unsigned symbol_index;
549 for (symbol_index = 0, l = rule; !symbol_list_null (l);
550 ++symbol_index, l = l->next)
553 if (l->content_type != SYMLIST_SYMBOL)
556 var = variant_add (l->content.sym->tag, l->sym_loc,
557 symbol_index, cp, cp_end, explicit_bracketing);
558 if (var && l->named_ref)
559 var->hidden_by = l->named_ref;
562 variant_add (l->named_ref->id, l->named_ref->loc,
563 symbol_index, cp, cp_end, explicit_bracketing);
568 for (i = 0; i < variant_count; ++i)
570 variant *var = &variant_table[i];
571 unsigned symbol_index = var->symbol_index;
573 /* Check visibility from mid-rule actions. */
574 if (midrule_rhs_index != 0
575 && (symbol_index == 0 || midrule_rhs_index < symbol_index))
576 var->err |= VARIANT_NOT_VISIBLE_FROM_MIDRULE;
578 /* Check correct bracketing. */
579 if (!explicit_bracketing && contains_dot_or_dash (var->id))
580 var->err |= VARIANT_BAD_BRACKETING;
582 /* Check using of hidden symbols. */
584 var->err |= VARIANT_HIDDEN;
588 valid_variant_index = i;
593 switch (valid_variants)
597 unsigned len = (explicit_bracketing || !ref_tail_fields) ?
598 cp_end - cp : ref_tail_fields - cp;
601 complain_at_indent (text_loc, complaint, &indent,
602 _("invalid reference: %s"), quote (text));
603 indent += SUB_INDENT;
606 location sym_loc = text_loc;
607 sym_loc.start.column += 1;
608 sym_loc.end = sym_loc.start;
610 _("syntax error after '%c', expecting integer, letter,"
611 " '_', '[', or '$'");
612 complain_at_indent (sym_loc, complaint, &indent, format,
615 else if (midrule_rhs_index)
618 _("symbol not found in production before $%d: %.*s");
619 complain_at_indent (rule->location, complaint, &indent, format,
620 midrule_rhs_index, len, cp);
625 _("symbol not found in production: %.*s");
626 complain_at_indent (rule->location, complaint, &indent, format,
630 if (variant_count > 0)
631 show_sub_messages (cp, explicit_bracketing, midrule_rhs_index,
632 dollar_or_at, false, indent);
638 if (variant_count > 1)
640 complain_at_indent (text_loc, Wother, &indent,
641 _("misleading reference: %s"), quote (text));
642 show_sub_messages (cp, explicit_bracketing, midrule_rhs_index,
643 dollar_or_at, true, indent + SUB_INDENT);
646 unsigned symbol_index =
647 variant_table[valid_variant_index].symbol_index;
648 return (symbol_index == midrule_rhs_index) ? LHS_REF : symbol_index;
655 complain_at_indent (text_loc, complaint, &indent,
656 _("ambiguous reference: %s"), quote (text));
657 show_sub_messages (cp, explicit_bracketing, midrule_rhs_index,
658 dollar_or_at, false, indent + SUB_INDENT);
667 /* Keeps track of the maximum number of semantic values to the left of
668 a handle (those referenced by $0, $-1, etc.) are required by the
669 semantic actions of this grammar. */
670 int max_left_semantic_context = 0;
673 /* If CP points to a typename (i.e., <.*?>), set TYPE_NAME to its
674 beginning (i.e., after the opening "<", and return the pointer
675 immediately after it. */
679 fetch_type_name (char *cp, char const **type_name,
688 /* The '>' symbol will be later replaced by '\0'. Original
689 'text' is needed for error messages. */
691 if (untyped_var_seen)
692 complain_at (dollar_loc, complaint,
693 _("explicit type given in untyped grammar"));
699 /*------------------------------------------------------------------.
700 | TEXT is pointing to a wannabee semantic value (i.e., a '$'). |
702 | Possible inputs: $[<TYPENAME>]($|integer) |
704 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
705 `------------------------------------------------------------------*/
708 handle_action_dollar (symbol_list *rule, char *text, location dollar_loc)
710 char const *type_name = NULL;
712 symbol_list *effective_rule;
713 int effective_rule_length;
716 if (rule->midrule_parent_rule)
718 effective_rule = rule->midrule_parent_rule;
719 effective_rule_length = rule->midrule_parent_rhs_index - 1;
723 effective_rule = rule;
724 effective_rule_length = symbol_list_length (rule->next);
727 /* Get the type name if explicit. */
728 cp = fetch_type_name (cp, &type_name, dollar_loc);
730 n = parse_ref (cp, effective_rule, effective_rule_length,
731 rule->midrule_parent_rhs_index, text, dollar_loc, '$');
744 type_name = symbol_list_n_type_name_get (rule, dollar_loc, 0);
748 if (union_seen | tag_seen)
750 if (rule->midrule_parent_rule)
751 complain_at (dollar_loc, complaint,
752 _("$$ for the midrule at $%d of %s"
753 " has no declared type"),
754 rule->midrule_parent_rhs_index,
755 quote (effective_rule->content.sym->tag));
757 complain_at (dollar_loc, complaint,
758 _("$$ of %s has no declared type"),
759 quote (rule->content.sym->tag));
762 untyped_var_seen = true;
765 obstack_sgrow (&obstack_for_string, "]b4_lhs_value(");
766 obstack_quote (&obstack_for_string, type_name);
767 obstack_sgrow (&obstack_for_string, ")[");
768 rule->action_props.is_value_used = true;
772 if (max_left_semantic_context < 1 - n)
773 max_left_semantic_context = 1 - n;
774 if (!type_name && 0 < n)
776 symbol_list_n_type_name_get (effective_rule, dollar_loc, n);
779 if (union_seen | tag_seen)
780 complain_at (dollar_loc, complaint,
781 _("$%s of %s has no declared type"), cp,
782 quote (effective_rule->content.sym->tag));
784 untyped_var_seen = true;
787 obstack_printf (&obstack_for_string,
788 "]b4_rhs_value(%d, %d, ", effective_rule_length, n);
789 obstack_quote (&obstack_for_string, type_name);
790 obstack_sgrow (&obstack_for_string, ")[");
792 symbol_list_n_get (effective_rule, n)->action_props.is_value_used =
799 /*------------------------------------------------------.
800 | TEXT is a location token (i.e., a '@...'). Output to |
801 | OBSTACK_FOR_STRING a reference to this location. |
802 `------------------------------------------------------*/
805 handle_action_at (symbol_list *rule, char *text, location at_loc)
808 symbol_list *effective_rule;
809 int effective_rule_length;
812 if (rule->midrule_parent_rule)
814 effective_rule = rule->midrule_parent_rule;
815 effective_rule_length = rule->midrule_parent_rhs_index - 1;
819 effective_rule = rule;
820 effective_rule_length = symbol_list_length (rule->next);
823 muscle_percent_define_ensure("locations", at_loc, true);
825 n = parse_ref (cp, effective_rule, effective_rule_length,
826 rule->midrule_parent_rhs_index, text, at_loc, '@');
833 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
837 obstack_printf (&obstack_for_string, "]b4_rhs_location(%d, %d)[",
838 effective_rule_length, n);
844 /*-------------------------.
845 | Initialize the scanner. |
846 `-------------------------*/
848 /* Translate the dollars and ats in \a self, in the context \a sc_context
849 (SC_RULE_ACTION, SC_SYMBOL_ACTION, INITIAL). */
852 translate_action (code_props *self, int sc_context)
855 static bool initialized = false;
858 obstack_init (&obstack_for_string);
863 loc->start = loc->end = self->location.start;
864 yy_switch_to_buffer (yy_scan_string (self->code));
865 res = code_lex (self, sc_context);
866 yy_delete_buffer (YY_CURRENT_BUFFER);
871 /*------------------------------------------------------------------------.
872 | Implementation of the public interface as documented in "scan-code.h". |
873 `------------------------------------------------------------------------*/
876 code_props_none_init (code_props *self)
878 *self = code_props_none;
881 code_props code_props_none = CODE_PROPS_NONE_INIT;
884 code_props_plain_init (code_props *self, char const *code,
887 code_props_none_init (self);
888 self->kind = CODE_PROPS_PLAIN;
890 self->location = code_loc;
894 code_props_symbol_action_init (code_props *self, char const *code,
897 code_props_none_init (self);
898 self->kind = CODE_PROPS_SYMBOL_ACTION;
900 self->location = code_loc;
904 code_props_rule_action_init (code_props *self, char const *code,
905 location code_loc, symbol_list *rule,
906 named_ref *name, bool is_predicate)
908 code_props_none_init (self);
909 self->kind = CODE_PROPS_RULE_ACTION;
911 self->location = code_loc;
913 self->named_ref = name;
914 self->is_predicate = is_predicate;
918 code_props_translate_code (code_props *self)
922 case CODE_PROPS_NONE:
924 case CODE_PROPS_PLAIN:
925 self->code = translate_action (self, INITIAL);
927 case CODE_PROPS_SYMBOL_ACTION:
928 self->code = translate_action (self, SC_SYMBOL_ACTION);
930 case CODE_PROPS_RULE_ACTION:
931 self->code = translate_action (self, SC_RULE_ACTION);
937 code_scanner_last_string_free (void)
943 code_scanner_free (void)
945 obstack_free (&obstack_for_string, 0);
946 variant_table_free ();
948 /* Reclaim Flex's buffers. */