Search code examples
ccompiler-constructionyacclexgoto

compiler design code to parse goto and blocks


Can someone please help me understand how to code lex and yacc file for a C program to parse goto and blocks(labels).

Here is some example I found on the net:

<statement> ::= 
<variable> <inc> <semi>
| <variable> <assign> <null> <semi> 
| <goto> <label> <semi>

But how to uniquely identify label. Can someone give me an example of this or any link where it is mentioned.


Solution

  • You don't need to "uniquely identify" as part of the parser, a label is identified by the syntax of the language. It is entirely legal to allow labels to overlap with other symbol / variable names. Just add a rule for a legal label, reuse the lexer TOKEN for IDENTIFIER, then store labels in a symbol table per function so you can detect duplicate labels.

    Typically in C-like languages, a label is part of a statement rule. It doesn't usually make sense anywhere else. The way I do it:

    labeled_statement:
        IDENTIFIER ':' statement
        {
            $$ = $3;
            $$->label = new Label($1);
        }
        ;
    

    Another way:

     label:
         IDENTIFIER ':'
         { $$ = new Label($1); }
         ;
    
    labeled_statement:
        label statement
        {
            $$ = $2;
            $$->label = $1;
        }
        ;