flex / bison将数字解释为浮点数
发布时间:2020-12-15 01:46:08 所属栏目:百科 来源:网络整理
导读:我正在尝试一个可以进行浮点运算的flex / bison计算器.我的flex代码看起来像这样 %{#include "calc.tab.h"#include stdlib.hvoid yyerror(char *s);%}digit [0-9]integer {digit}+real ({digit}+[.]{digit}*)|({digit}*[.]{digit}+)exp ({integer}|{real})[e
我正在尝试一个可以进行浮点运算的flex / bison计算器.我的flex代码看起来像这样
%{ #include "calc.tab.h" #include <stdlib.h> void yyerror(char *s); %} digit [0-9] integer {digit}+ real ({digit}+[.]{digit}*)|({digit}*[.]{digit}+) exp ({integer}|{real})[eE]-?{integer} %% ({integer}|{real}|{exp}) { yylval = atof(yytext); return NUMBER; } [-+*/n] { return *yytext; } [ tvfr] { } . { yyerror("Unknown Character"); } %% int yywrap(void) { return 1; } 我的野牛代码看起来像这样 %{ #include <stdio.h> typedef double YYSTYPE; #define YYSTYPE_IS_DECLARED void yyerror(char *s); extern char *yytext; extern int yylineno; %} %token NUMBER %left '+' '-' %left '*' '/' %% program: program expr 'n' { printf("%gn",$2); } | program 'n' | ; expr: expr '+' expr { $$= $1 + $3; } | expr '-' expr { $$= $1 - $3; } | expr '*' expr { $$= $1 * $3; } | expr '/' expr { $$= $1 / $3; } | NUMBER { $$= $1; } ; %% void yyerror(char *s) { fprintf(stderr,"error: %s at %s,line %dn",s,yytext,yylineno); } int main(int argc,char *argv[]) { yyparse(); return 0; } 这不会产生正确的输出.即使词法分析器将字符串解释为双精度并将它们正确地存储在yylval变量中,但当解析器将数字相加时,它只会吐出0.0000.但是,如果我通过%union指令将yylval声明为union,该指令只包含一个double lf_val;变量,并将atof输出存储在词法分析器的yylval字段中,并声明%token< lf_val> NUMBER和%类型< lf_val>解析器中的expr,事情似乎有效. 但是,为什么不能直接使用类型定义YYSTYPE的方法呢?我也试过#define YYSTYPE double.那也行不通. 解决方法
关于%代码,Bison’s documentation表示:
%code requires [...] is the best place to override Bison's default YYSTYPE and YYLTYPE definitions. 所以juste在你的野牛文件的顶部添加以下内容: %code requires { #define YYSTYPE double } 您还需要删除以下两行: typedef double YYSTYPE; #define YYSTYPE_IS_DECLARED 请注意,据我所知,YYSTYPE_IS_DECLARED在任何地方都没有记录,因此仅供Bison内部使用. 如果你不熟悉Bison的%代码指令比简单的%{prologues更多,你可能会发现this section of the documentation很有意思. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |