Note that there are some explanatory texts on larger screens.

plurals
  1. POUnintentional concatenation in Bison/Yacc grammar
    text
    copied!<p>I am experimenting with lex and yacc and have run into a strange issue, but I think it would be best to show you my code before detailing the issue. This is my lexer:</p> <pre><code>%{ #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "y.tab.h" void yyerror(char *); %} %% [a-zA-Z]+ { yylval.strV = yytext; return ID; } [0-9]+ { yylval.intV = atoi(yytext); return INTEGER; } [\n] { return *yytext; } [ \t] ; . yyerror("invalid character"); %% int yywrap(void) { return 1; } </code></pre> <p>This is my parser:</p> <pre><code>%{ #include &lt;stdio.h&gt; int yydebug=1; void prompt(); void yyerror(char *); int yylex(void); %} %union { int intV; char *strV; } %token INTEGER ID %% program: program statement EOF { prompt(); } | program EOF { prompt(); } | { prompt(); } ; args: /* empty */ | args ID { printf(":%s ", $&lt;strV&gt;2); } ; statement: ID args { printf("%s", $&lt;strV&gt;1); } | INTEGER { printf("%d", $&lt;intV&gt;1); } ; EOF: '\n' %% void yyerror(char *s) { fprintf(stderr, "%s\n", s); } void prompt() { printf("&gt; "); } int main(void) { yyparse(); return 0; } </code></pre> <p>A very simple language, consisting of no more than strings and integer and a basic REPL. Now, you'll note in the parser that <em>args</em> are output with a leading colon, the intention being that, when combined with the first pattern of the rule of the <em>statement</em> the interaction with the REPL would look something like this:</p> <pre><code>&gt; aaa aa a :aa :a aaa&gt; </code></pre> <p>However, the interaction is this:</p> <pre><code>&gt; aaa aa a :aa :a aaa aa aa &gt; </code></pre> <p>Why does the token ID in the following rule</p> <pre><code>statement: ID args { printf("%s", $&lt;strV&gt;1); } | INTEGER { printf("%d", $&lt;intV&gt;1); } ; </code></pre> <p>have the semantic value of the total input string, newline included? How can my grammar be reworked so that the interaction I intended?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload