I don't know how to solve this problem for home-work ; we are told to write a flex and bison code for a Language called Exp that offers structures control: sequence, condition and repetition. I wrote the code but I don't know how to construct an AST and display it on an XML file. Here is the Flex code :
START%{
#include"parser.tab.h"
%}
lettre [a-z]
chiffre [0-9]
%x comment
%%
"/*" BEGIN(comment);
<comment>. ;
<comment>"*/" BEGIN(INITIAL);
debut return DEBUT;
fin return END;
si return IF;
alors return ALORS;
sinon return SINON;
repeter return REPETER;
jusqua return JUSQUA;
pour return POUR;
tantque return TANTQUE;
lire return READ;
ecrire return ECRIRE;
" "|\t ;
{lettre}({chiffre}|{lettre}){0,35} {return ID;}
"-"?{chiffre}+ {return NUM;}
"==" return EQUAL;
"*"|"/"|"+"|"-"|"="|"<"|">" return *yytext;
"("|")"|","|";"|"." return *yytext;
\n ;
. {
printf("erreur\n");
return 0;
}
%%
and Here is Bison Code
%{
#include<stdio.h>
extern FILE* yyin;
int numAffec = 0;
int numLecture = 0;
int numEcriture = 0;
int numnumCondition = 0;
int numPour = 0;
int numTantque = 0;
int numRepeter = 0;
%}
%start prog
%token DEBUT END IF ALORS SINON REPETER JUSQUA POUR TANTQUE READ ECRIRE NUM ID EQUAL
%%
prog : DEBUT seq_instr END '.'
seq_instr : seq_instr instr ';'
| instr ';'
instr : instr_si {numCondition++;}
| instr_repeter {numRepeter++;}
| instr_pour {numPour++;}
| instr_tant_que {numTantque++;}
| instr_aff {numAffec++;}
| instr_lect {numLecture++;}
| instr_ecrit
instr_si : IF exp ALORS seq_instr END
| IF exp ALORS seq_instr SINON seq_instr END
;
instr_repeter : REPETER seq_instr JUSQUA '(' exp ')'
;
instr_pour : POUR '(' instr_aff ',' exp ',' instr_aff ')' seq_instr END
;
instr_tant_que : TANTQUE '(' exp ')' seq_instr END
;
instr_aff : ID '=' exp
;
instr_lect : READ '(' ID ')'
;
instr_ecrit : ECRIRE '(' exp ')'
;
exp : exp_simple '<' exp_simple
| exp_simple '>' exp_simple
| exp_simple EQUAL exp_simple
| exp_simple
exp_simple : exp_simple '+' term
| exp_simple '-' term
| term
term : term '*' facteur
| term '/' facteur
| facteur
facteur : '(' exp ')'
| NUM
| ID
%%
int main(int arg,char** var) {
yyin = fopen(var[1],"r");
if(yyin == NULL) {
printf("erreur\n");
return ;
}
yyparse();
printf("Affectation : %d\n",numAffec);
printf("Lecture : %d\n",numLecture);
printf("Ecriture : %d\n",numEcriture);
printf("Conditionnel : %d\n",numCondition);
printf(" Pour : %d\n",numPour);
printf(" Tant Que: %d\n",numTantque);
printf(" Repeter : %d\n",numRepeter);
return 0;
}