Monday, 23 October 2017

Parser for Sample Language

Creation of Parser for a Sample Language using Lex &Yacc.


Basic Version for Parsing simple c++ code



Lex

%{
#include<stdio.h>
# include "y.tab.h"
extern int yylval;
%}

digit [0-9]
char [A-Za-z_]
identifier {char}({char}|{digit})*
white " "|\t|\n

%%
{white} ;
#include<{identifier}.h> {return PRE;}
int|float {return DT;}
\(|\)|\}|\{|; {return yytext[0];}
return {return RET;}
{digit}+ {return INT;}
main {return MAIN;}

%%

int yywrap(){
    return 1;
}

Yacc

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern FILE* yyin;
void yyerror(char *s);
int yylex();
%}

%token PRE DT RET INT MAIN

%%
s: preprocessor mainblock;
preprocessor: PRE {printf("Preprocessor Statement\n");};
mainblock: DT MAIN '('')''{' RET INT ';''}' {printf("MainBlock\n");}
%%

void yyerror(char *s){
    printf("error %s",s);
}

int main(){

    yyin = fopen("input.c","r");
    yyparse();
    return 0;
}

Input

#include<stdio.h>

int main(){
return 0;
}

Output

[duke@duke-pc a4]$ yacc -d a4.y
[duke@duke-pc a4]$ lex a4.l
[duke@duke-pc a4]$ gcc y.tab.c lex.yy.c
[duke@duke-pc a4]$ ./a.out
Preprocessor Statement
MainBlock

Additional Rules

Add additional rules as per your wish. Make sure to test after every two rules. Debugging Lex & Yacc can be a pain in the ass.



No comments:

Post a Comment