1 /* Bison Action Scanner -*- C -*-
3 Copyright (C) 2006-2015, 2018-2021 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 <https://www.gnu.org/licenses/>. */
20 %option debug nodefault noinput nounput noyywrap never-interactive
21 %option prefix="code_" outfile="lex.yy.c"
25 #include <get-errno.h>
28 #include "src/complain.h"
29 #include "src/getargs.h"
30 #include "src/muscle-tab.h"
31 #include "src/reader.h"
32 #include "src/scan-code.h"
33 #include "src/symlist.h"
35 #define FLEX_PREFIX(Id) code_ ## Id
36 #include "src/flex-scanner.h"
38 /* Work around a bug in flex 2.5.31. See Debian bug 333231
39 <https://bugs.debian.org/333231>. */
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,
51 const location *dollar_loc);
53 static void handle_action_dollar (symbol_list *rule, char *cp,
54 const location *dollar_loc);
55 static void handle_action_at (symbol_list *rule, char *cp,
56 const location *at_loc);
58 /* A string to be pushed to obstack after dollar/at has been handled. */
59 static char *ref_tail_fields;
61 static location current_loc;
62 static location *loc = ¤t_loc;
64 /* A string representing the most recent translation. */
65 static char *last_string;
67 /* True if an untyped $$ or $n was seen. */
68 static bool untyped_var_seen;
71 /* C and C++ comments in code. */
72 %x SC_COMMENT SC_LINE_COMMENT
73 /* Strings and characters in code. */
74 %x SC_STRING SC_CHARACTER
75 /* Whether in a rule or symbol action. Specifies the translation
77 %x SC_RULE_ACTION SC_SYMBOL_ACTION
80 /* POSIX says that a tag must be both an id and a C union member, but
81 historically almost any character is allowed in a tag. We disallow
82 NUL and newline, as this simplifies our implementation. We allow
83 "->" as a means to dereference a pointer. */
84 tag ([^\0\n>]|->)*[^-]
86 /* Zero or more instances of backslash-newline. Following GCC, allow
87 white space between the backslash and the newline. */
88 splice (\\[ \f\t\v]*\n)*
90 /* C style identifier. Must start with letter. Will be used for
91 named symbol references. Shall be kept synchronized with
92 scan-gram.l "letter" and "id". */
93 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
94 id {letter}({letter}|[-0-9])*
95 ref -?[0-9]+|{id}|"["{id}"]"|"$"
100 /* This scanner is special: it is invoked only once, henceforth
101 is expected to return only once. This initialization is
102 therefore done once per action to translate. */
103 aver (sc_context == SC_SYMBOL_ACTION
104 || sc_context == SC_RULE_ACTION
105 || sc_context == INITIAL);
109 /*------------------------------------------------------------.
110 | Scanning a C comment. The initial '/ *' is already eaten. |
111 `------------------------------------------------------------*/
115 "*"{splice}"/" STRING_GROW (); BEGIN sc_context;
119 /*--------------------------------------------------------------.
120 | Scanning a line comment. The initial '//' is already eaten. |
121 `--------------------------------------------------------------*/
125 "\n" STRING_GROW (); BEGIN sc_context;
126 {splice} STRING_GROW ();
130 /*--------------------------------------------.
131 | Scanning user-code characters and strings. |
132 `--------------------------------------------*/
134 <SC_CHARACTER,SC_STRING>
136 {splice}|\\{splice}. STRING_GROW ();
141 "'" STRING_GROW (); BEGIN sc_context;
146 "\"" STRING_GROW (); BEGIN sc_context;
150 <SC_RULE_ACTION,SC_SYMBOL_ACTION>
152 "'" STRING_GROW (); BEGIN SC_CHARACTER;
153 "\"" STRING_GROW (); BEGIN SC_STRING;
154 "/"{splice}"*" STRING_GROW (); BEGIN SC_COMMENT;
155 "/"{splice}"/" STRING_GROW (); BEGIN SC_LINE_COMMENT;
158 complain (loc, Wother, _("stray '%s'"), yytext);
159 obstack_escape (&obstack_for_string, yytext);
165 "$"("<"{tag}">")?{ref} {
166 ref_tail_fields = NULL;
167 handle_action_dollar (self->rule, yytext, loc);
169 obstack_sgrow (&obstack_for_string, ref_tail_fields);
172 ref_tail_fields = NULL;
173 handle_action_at (self->rule, yytext, loc);
175 obstack_sgrow (&obstack_for_string, ref_tail_fields);
181 "$"("<"{tag}">")?"$" {
182 const char *type_name = NULL;
183 fetch_type_name (yytext + 1, &type_name, loc)[-1] = 0;
184 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar(");
185 obstack_quote (&obstack_for_string, type_name);
186 obstack_sgrow (&obstack_for_string, ")[");
187 self->is_value_used = true;
190 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
191 muscle_percent_define_ensure("locations", *loc, true);
198 /* Escape M4 quoting characters in C code. */
199 [$@\[\]] obstack_escape (&obstack_for_string, yytext);
201 /* By default, grow the string obstack with the input. */
204 /* End of processing. */
205 <<EOF>> STRING_FINISH (); return last_string;
211 is_dot_or_dash (char ch)
213 return ch == '.' || ch == '-';
217 contains_dot_or_dash (const char* p)
219 return !!strpbrk (p, ".-");
222 /* Defines a variant of a symbolic name resolution. */
225 /* Index in symbol list. */
228 /* Matched symbol id and loc. */
232 /* Hiding named reference. */
233 named_ref* hidden_by;
235 /* Error flags. May contain zero (no errors) or
236 a combination of VARIANT_* values. */
240 /* Set when the variant refers to a symbol hidden
241 by an explicit symbol reference. */
242 #define VARIANT_HIDDEN (1 << 0)
244 /* Set when the variant refers to a symbol containing
245 dots or dashes. Will require explicit bracketing. */
246 #define VARIANT_BAD_BRACKETING (1 << 1)
248 /* Set when the variant refers to a symbol which is
249 not visible from current midrule. */
250 #define VARIANT_NOT_VISIBLE_FROM_MIDRULE (1 << 2)
252 static variant *variant_table = NULL;
253 static int variant_table_size = 0;
254 static int variant_count = 0;
257 variant_table_grow (void)
260 if (variant_count > variant_table_size)
262 while (variant_count > variant_table_size)
263 variant_table_size = 2 * variant_table_size + 3;
264 variant_table = xnrealloc (variant_table, variant_table_size,
265 sizeof *variant_table);
267 return &variant_table[variant_count - 1];
271 variant_table_free (void)
273 free (variant_table);
274 variant_table = NULL;
275 variant_table_size = variant_count = 0;
279 find_prefix_end (char const *prefix, char const *cp, char const *end)
281 for (; *prefix && cp != end; ++prefix, ++cp)
285 return *prefix ? NULL : cp;
289 variant_add (uniqstr id, location id_loc, int symbol_index,
290 char const *cp, char const *cp_end, bool explicit_bracketing)
292 char const *prefix_end = find_prefix_end (id, cp, cp_end);
294 (prefix_end == cp_end ||
295 (!explicit_bracketing && is_dot_or_dash (*prefix_end))))
297 variant *r = variant_table_grow ();
298 r->symbol_index = symbol_index;
310 get_at_spec(int symbol_index)
312 static char at_buf[20];
313 if (symbol_index == 0)
314 strcpy (at_buf, "$$");
316 snprintf (at_buf, sizeof at_buf, "$%u", symbol_index);
321 show_sub_message (warnings warning,
322 const char* cp, bool explicit_bracketing,
323 int midrule_rhs_index, char dollar_or_at,
326 const char *at_spec = get_at_spec (var->symbol_index);
329 subcomplain (&var->loc, warning,
330 _("refers to: %c%s at %s"), dollar_or_at,
339 id = var->hidden_by->id;
340 id_loc = var->hidden_by->loc;
348 const char *tail = explicit_bracketing ? "" : cp + strlen (var->id);
350 /* Create the explanation message. */
351 static struct obstack msg_buf;
352 obstack_init (&msg_buf);
354 obstack_printf (&msg_buf, _("possibly meant: %c"), dollar_or_at);
355 if (contains_dot_or_dash (id))
356 obstack_printf (&msg_buf, "[%s]", id);
358 obstack_sgrow (&msg_buf, id);
359 obstack_sgrow (&msg_buf, tail);
361 if (var->err & VARIANT_HIDDEN)
363 obstack_printf (&msg_buf, _(", hiding %c"), dollar_or_at);
364 if (contains_dot_or_dash (var->id))
365 obstack_printf (&msg_buf, "[%s]", var->id);
367 obstack_sgrow (&msg_buf, var->id);
368 obstack_sgrow (&msg_buf, tail);
371 obstack_printf (&msg_buf, _(" at %s"), at_spec);
373 if (var->err & VARIANT_NOT_VISIBLE_FROM_MIDRULE)
374 obstack_printf (&msg_buf,
375 _(", cannot be accessed from midrule action at $%d"),
378 subcomplain (&id_loc, warning, "%s",
379 obstack_finish0 (&msg_buf));
380 obstack_free (&msg_buf, 0);
385 show_sub_messages (warnings warning,
386 const char* cp, bool explicit_bracketing,
387 int midrule_rhs_index, char dollar_or_at)
389 for (int i = 0; i < variant_count; ++i)
390 show_sub_message (warning | silent,
391 cp, explicit_bracketing,
392 midrule_rhs_index, dollar_or_at,
396 /* Returned from "parse_ref" when the reference
398 #define INVALID_REF (INT_MIN)
400 /* Returned from "parse_ref" when the reference
401 points to LHS ($$) of the current rule or midrule. */
402 #define LHS_REF (INT_MIN + 1)
404 /* Parse named or positional reference. In case of positional
405 references, can return negative values for $-n "deep" stack
408 parse_ref (char *cp, symbol_list *rule, int rule_length,
409 int midrule_rhs_index, char *text, const location *text_loc,
415 if (c_isdigit (*cp) || (*cp == '-' && c_isdigit (* (cp + 1))))
417 long num = strtol (cp, &cp, 10);
418 if (1 - INT_MAX + rule_length <= num && num <= rule_length)
422 complain (text_loc, complaint, _("integer out of range: %s"),
428 bool const explicit_bracketing = *cp == '[';
430 if (explicit_bracketing)
433 ref_tail_fields = strpbrk (cp, ".-");
435 char const *cp_end = strchr (cp, explicit_bracketing ? ']' : '\0');
437 /* Add all relevant variants. */
442 for (symbol_index = 0, l = rule; !symbol_list_null (l);
443 ++symbol_index, l = l->next)
445 if (l->content_type != SYMLIST_SYMBOL)
449 = variant_add (l->content.sym->tag, l->sym_loc,
450 symbol_index, cp, cp_end, explicit_bracketing);
451 if (var && l->named_ref)
452 var->hidden_by = l->named_ref;
455 variant_add (l->named_ref->id, l->named_ref->loc,
456 symbol_index, cp, cp_end, explicit_bracketing);
461 int valid_variants = 0;
462 int valid_variant_index = 0;
463 for (int i = 0; i < variant_count; ++i)
465 variant *var = &variant_table[i];
466 int symbol_index = var->symbol_index;
468 /* Check visibility from midrule actions. */
469 if (midrule_rhs_index != 0
470 && (symbol_index == 0 || midrule_rhs_index < symbol_index))
471 var->err |= VARIANT_NOT_VISIBLE_FROM_MIDRULE;
473 /* Check correct bracketing. */
474 if (!explicit_bracketing && contains_dot_or_dash (var->id))
475 var->err |= VARIANT_BAD_BRACKETING;
477 /* Check using of hidden symbols. */
479 var->err |= VARIANT_HIDDEN;
483 valid_variant_index = i;
488 switch (valid_variants)
492 int len = (explicit_bracketing || !ref_tail_fields) ?
493 cp_end - cp : ref_tail_fields - cp;
495 complain (text_loc, complaint,
496 _("invalid reference: %s"), quote (text));
499 location sym_loc = *text_loc;
500 sym_loc.start.column += 1;
501 sym_loc.end = sym_loc.start;
502 subcomplain (&sym_loc, complaint,
503 _("syntax error after '%c', expecting integer, "
504 "letter, '_', '[', or '$'"),
507 else if (midrule_rhs_index)
508 subcomplain (&rule->rhs_loc, complaint,
509 _("symbol not found in production before $%d: "
511 midrule_rhs_index, len, cp);
513 subcomplain (&rule->rhs_loc, complaint,
514 _("symbol not found in production: %.*s"),
517 if (variant_count > 0)
518 show_sub_messages (complaint,
519 cp, explicit_bracketing, midrule_rhs_index,
525 if (variant_count > 1)
527 complain (text_loc, Wother,
528 _("misleading reference: %s"), quote (text));
529 show_sub_messages (Wother,
530 cp, explicit_bracketing, midrule_rhs_index,
535 variant_table[valid_variant_index].symbol_index;
536 return (symbol_index == midrule_rhs_index) ? LHS_REF : symbol_index;
542 complain (text_loc, complaint,
543 _("ambiguous reference: %s"), quote (text));
544 show_sub_messages (complaint,
545 cp, explicit_bracketing, midrule_rhs_index,
552 /* Keeps track of the maximum number of semantic values to the left of
553 a handle (those referenced by $0, $-1, etc.) are required by the
554 semantic actions of this grammar. */
555 int max_left_semantic_context = 0;
558 /* If CP points to a typename (i.e., <.*?>), set TYPE_NAME to its
559 beginning (i.e., after the opening "<", and return the pointer
560 immediately after it. */
564 fetch_type_name (char *cp, char const **type_name,
565 const location *dollar_loc)
570 /* Series of non-'>' or "->". */
571 while (*cp != '>' || cp[-1] == '-')
574 /* The '>' symbol will be later replaced by '\0'. Original
575 'text' is needed for error messages. */
577 if (untyped_var_seen)
578 complain (dollar_loc, complaint,
579 _("explicit type given in untyped grammar"));
585 /*------------------------------------------------------------------.
586 | TEXT is pointing to a wannabee semantic value (i.e., a '$'). |
588 | Possible inputs: $[<TYPENAME>]($|integer) |
590 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
591 `------------------------------------------------------------------*/
594 handle_action_dollar (symbol_list *rule, char *text, const location *dollar_loc)
596 symbol_list *effective_rule;
597 int effective_rule_length;
599 if (rule->midrule_parent_rule)
601 effective_rule = rule->midrule_parent_rule;
602 effective_rule_length = rule->midrule_parent_rhs_index - 1;
606 effective_rule = rule;
607 effective_rule_length = symbol_list_length (rule->next);
610 /* The type name if explicit, otherwise left null. */
611 char const *type_name = NULL;
612 char *cp = fetch_type_name (text + 1, &type_name, dollar_loc);
613 int n = parse_ref (cp, effective_rule, effective_rule_length,
614 rule->midrule_parent_rhs_index, text, dollar_loc, '$');
615 /* End type_name. Don't do it earlier: parse_ref depends on TEXT. */
626 symbol_list *sym = symbol_list_n_get (rule, 0);
628 && !sym->content.sym->content->type_name)
630 if (union_seen || tag_seen)
632 if (rule->midrule_parent_rule)
633 complain (dollar_loc, complaint,
634 _("$$ for the midrule at $%d of %s"
635 " has no declared type"),
636 rule->midrule_parent_rhs_index,
637 quote (effective_rule->content.sym->tag));
639 complain (dollar_loc, complaint,
640 _("$$ of %s has no declared type"),
641 quote (rule->content.sym->tag));
644 untyped_var_seen = true;
647 obstack_printf (&obstack_for_string, "]b4_lhs_value(orig %d, ",
648 sym->content.sym->content->number);
649 obstack_quote (&obstack_for_string, type_name);
650 obstack_sgrow (&obstack_for_string, ")[");
651 rule->action_props.is_value_used = true;
655 /* Reference to a RHS symbol. */
658 if (max_left_semantic_context < 1 - n)
659 max_left_semantic_context = 1 - n;
660 symbol_list *sym = 0 < n ? symbol_list_n_get (effective_rule, n) : NULL;
662 && (!sym || !sym->content.sym->content->type_name))
664 if (union_seen || tag_seen)
665 complain (dollar_loc, complaint,
666 _("$%s of %s has no declared type"), cp,
667 quote (effective_rule->content.sym->tag));
669 untyped_var_seen = true;
672 obstack_printf (&obstack_for_string,
673 "]b4_rhs_value(%d, %d, ",
674 effective_rule_length, n);
676 obstack_printf (&obstack_for_string, "%s%d, ",
677 sym->content.sym->content->class == nterm_sym ? "orig " : "",
678 sym->content.sym->content->number);
680 obstack_sgrow (&obstack_for_string, "[], ");
682 obstack_quote (&obstack_for_string, type_name);
683 obstack_sgrow (&obstack_for_string, ")[");
686 if (muscle_percent_define_ifdef ("api.value.automove")
687 && sym->action_props.is_value_used)
688 complain (dollar_loc, Wother,
689 _("multiple occurrences of $%d with api.value.automove"),
691 sym->action_props.is_value_used = true;
699 /*------------------------------------------------------.
700 | TEXT is a location token (i.e., a '@...'). Output to |
701 | OBSTACK_FOR_STRING a reference to this location. |
702 `------------------------------------------------------*/
705 handle_action_at (symbol_list *rule, char *text, const location *at_loc)
707 symbol_list *effective_rule;
708 int effective_rule_length;
710 if (rule->midrule_parent_rule)
712 effective_rule = rule->midrule_parent_rule;
713 effective_rule_length = rule->midrule_parent_rhs_index - 1;
717 effective_rule = rule;
718 effective_rule_length = symbol_list_length (rule->next);
721 muscle_percent_define_ensure ("locations", *at_loc, true);
723 int n = parse_ref (text + 1, effective_rule, effective_rule_length,
724 rule->midrule_parent_rhs_index, text, at_loc, '@');
731 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
735 obstack_printf (&obstack_for_string, "]b4_rhs_location(%d, %d)[",
736 effective_rule_length, n);
742 /*-------------------------.
743 | Initialize the scanner. |
744 `-------------------------*/
746 /* Translate the '$...' and '@...' in \a self, in the context \a
747 sc_context (SC_RULE_ACTION, SC_SYMBOL_ACTION, INITIAL). */
750 translate_action (code_props *self, int sc_context)
752 static bool initialized = false;
755 obstack_init (&obstack_for_string);
760 loc->start = loc->end = self->location.start;
761 yy_switch_to_buffer (yy_scan_string (self->code));
762 char *res = code_lex (self, sc_context);
763 yy_delete_buffer (YY_CURRENT_BUFFER);
768 /*------------------------------------------------------------------------.
769 | Implementation of the public interface as documented in "scan-code.h". |
770 `------------------------------------------------------------------------*/
773 code_props_none_init (code_props *self)
775 *self = code_props_none;
778 code_props code_props_none = CODE_PROPS_NONE_INIT;
781 code_props_plain_init (code_props *self, char const *code,
784 code_props_none_init (self);
785 self->kind = CODE_PROPS_PLAIN;
787 self->location = code_loc;
791 code_props_symbol_action_init (code_props *self, char const *code,
794 code_props_none_init (self);
795 self->kind = CODE_PROPS_SYMBOL_ACTION;
797 self->location = code_loc;
801 code_props_rule_action_init (code_props *self, char const *code,
802 location code_loc, symbol_list *rule,
803 named_ref *name, uniqstr type,
806 code_props_none_init (self);
807 self->kind = CODE_PROPS_RULE_ACTION;
809 self->location = code_loc;
811 self->named_ref = name;
813 self->is_predicate = is_predicate;
817 code_props_translate_code (code_props *self)
821 case CODE_PROPS_NONE:
823 case CODE_PROPS_PLAIN:
824 self->code = translate_action (self, INITIAL);
826 case CODE_PROPS_SYMBOL_ACTION:
827 self->code = translate_action (self, SC_SYMBOL_ACTION);
829 case CODE_PROPS_RULE_ACTION:
830 self->code = translate_action (self, SC_RULE_ACTION);
836 code_scanner_last_string_free (void)
842 code_scanner_free (void)
844 obstack_free (&obstack_for_string, 0);
845 variant_table_free ();
847 /* Reclaim Flex's buffers. */