4
I am using the LEX generator to do a lexical analysis of a simple C++ code. The following code is from the generator:
%{
#include<stdio.h>
%}
extern FILE *yyin;
%%
"<" {printf("(Identifier, %s)\n",&yytext[0]);}
">" {printf("(Identifier, %s)\n",&yytext[0]);}
"+" {printf("operador de soma %s\n",&yytext[0]);}
"-" {printf("operador de subtracao %s\n",&yytext[0]);}
%%
int yywrap(){
return 1;
}
int main(){
yyin=fopen("cpp.cpp","r");
yylex();
fclose(yyin);
return;
}
As you can see, I used the 'yyin' variable to call the cpp.cpp file for lexical analysis. I would like instead of printing the text to be written in the cpp.cpp file. That is, the result for each lexema was written in the analyzed code itself. cpp file:
#include<iostream>
using namespace std;
int main(){
int a = 0;
int b = 2;
int c = a + b;
cout << c << endl;
return 0;
}
*I know you have lexemas that will not be found by grammar, but it’s just an example to explain that I want the lexemas found to be written inside the cpp.cpp file(as if instead of the 'printf' function was a fprintf function - which writes to a file, using C, or a RETURN so that I can write to the file inside the main method).
If I want to use another file to write ? I saw a 'yyout' function, but I don’t know how to use it. I could describe how to use it?
– Fillipe
yyout is the default output of Lex, you can do yyout = stdout, give me an example of how you would like it to be the output of your program, I have an incomplete project, maybe I can help :https://github.com/CarlosPereira27/Compillators_TP/blob/masterlex/c_minus.l
– Gabriel Rodrigues
My question is, how to generate tokens (the lex automatically generates or I that Gero any number ?), how to write the table of symbols in an output file, which would be precisely by yyout. I have this code and want to generate a symbol table from it to the simbTables.txt file by reading the cpp.cpp file (file contains anything, it’s just for testing) as I would write the symbol table and install the ID for all tokens ?
– Fillipe
Well I made a code here and it works, do the following :
%{
 #include<stdio.h>
%}

extern FILE *yyin;

%%
"<" {fprintf(yyout,"(Identifier, %s)\n",yytext);}
">" {fprintf(yyout,"(Identifier, %s)\n",yytext);}
"+" {fprintf(yyout,"operador de soma %s\n",yytext);}
"-" {fprintf(yyout,"operador de subtracao %s\n",yytext);}
%%

int yywrap(){
 return 1;
}

int main(int argc, char **argv){

 yyin=fopen("code.cpp","r");
 yyout=fopen("saida.txt", "w");
 yylex();
 fclose(yyin); 
 fclose(yyout);
 return 0;
}
– Gabriel Rodrigues