Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could pass lexer result tokens through a function that inserts semicolons where necessary. Upon detection of the need to insert, the next token can be put back to the input stream, basically lexing it again in the next turn.</p> <p>Below is an example that inserts a SEMICOLON before a newline, when it follows a WORD. The bison file "insert.y" is this:</p> <pre><code>%{ #include &lt;stdio.h&gt; void yyerror(const char *str) { printf("ERROR: %s\n", str); } int main() { yyparse(); return 0; } %} %union { char *string; } %token &lt;string&gt; WORD %token SEMICOLON NEWLINE %% input: | input WORD {printf("WORD: %s\n", $2); free($2);} | input SEMICOLON {printf("SEMICOLON\n");} ; %% </code></pre> <p>and the lexer is generated by flex from this:</p> <pre><code>%{ #include &lt;string.h&gt; #include "insert.tab.h" int f(int token); %} %option noyywrap %% [ \t] ; [^ \t\n;]+ {yylval.string = strdup(yytext); return f(WORD);} ; {return f(SEMICOLON);} \n {int token = f(NEWLINE); if (token != NEWLINE) return token;} %% int insert = 0; int f(int token) { if (insert &amp;&amp; token == NEWLINE) { unput('\n'); insert = 0; return SEMICOLON; } else { insert = token == WORD; return token; } } </code></pre> <p>For input </p> <pre><code>abc def ghi jkl; </code></pre> <p>it prints</p> <pre><code>WORD: abc WORD: def SEMICOLON WORD: ghi SEMICOLON WORD: jkl SEMICOLON </code></pre> <p>Unputting a non-constant token requires a little extra work - I have tried to keep the example simple, just to give the idea.</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