打造自己的脚本语言jacsl-基于C++(1)

水宝石的技术博客 / 2023-07-06 / 原文

目录
  • flex bison
  • 统计字数示例
  • 简单计算器

flex bison

sudo dnf install flex bison
 sudo dnf install flex-devel

统计字数示例

/*字数统计示例*/
%{
int chars=0;
int words=0;
int lines=0;
%}

%%
[a-zA-Z]+ {words++;chars+=strlen(yytext);}
\n {chars++;lines++;}
. {chars++;}
%%
#include <iostream>
using namespace std;
int main(int argc,char **agrv){
	yylex();
	cout<<"单词数:"<<words<<"字符数:"<<chars<<"行数:"<<lines<<endl;
}

g++ lex.yy.c  -o countTxt -lfl
[maisipu@192 test]$ ./countTxt
hello,world
hahah hahah hahah 
单词数:5字符数:31行数:2

简单计算器

/*简单计算器示例*/
%{
#include <iostream>
using namespace std;
%}

%%
"+" {cout<<"PLUS"<<endl;}
"-" {cout<<"SUB" <<endl;}
"*" {cout<<"TIMES"<<endl;}
"/" {cout<<"DIV"<<endl;}
[0-9]+ {cout<<"NUMBER"<<yytext<<endl;}
"\n" {cout<<"新一行"<<endl;}
[ \t] {}
. {cout<<"error:"<<yytext<<endl;}
%%
int main(int argc,char **agrv){
	yylex();
}

[maisipu@192 test]$ ./cpt
11_99+32*77
NUMBER11
error:_
NUMBER99
PLUS
NUMBER32
TIMES
NUMBER77
新一行
 
新一行
[maisipu@192 test]$ ./cpt
11-33-99*212
NUMBER11
SUB
NUMBER33
SUB
NUMBER99
TIMES
NUMBER212
新一行
[maisipu@192 test]$ 


/*简单计算器示例*/
%{
#include <iostream>
using namespace std;
enum class YyTokenType{
PLUS=250,SUB,TIMES,DIV,
INTEGER,
EOL
};
int yylval;
%}

%%
"+" {return int(YyTokenType::PLUS);}
"-" {return int(YyTokenType::SUB);}
"*" {return int(YyTokenType::TIMES);}
"/" {return int(YyTokenType::DIV);}
[0-9]+ {yylval=atoi(yytext);return int(YyTokenType::INTEGER);}
"\n" {return int(YyTokenType::EOL);}
[ \t] {}
. {cout<<"error:"<<yytext<<endl;}
%%
int main(int argc,char **agrv){
	int tok;
	while (tok=yylex()){
		cout<<tok;
		if (tok==int(YyTokenType::INTEGER)){
			cout<<"="<<yylval<<endl;
		}
		else{
			cout<<endl;
		}
	}
}

[maisipu@192 test]$ ./cpt
11*66+99*77
254=11
252
254=66
250
254=99
252
254=77
255
^C
[maisipu@192 test]$ ./cpt
11*66-99*77/3
254=11
252
254=66
251
254=99
252
254=77
253
254=3
255
^C
[maisipu@192 test]$