[英]Arithmetic expression nor properly parsed in yacc grammar
我有以下yacc
:
%{
#include <stdio.h>
extern FILE* yyin;
extern char* yytext;
%}
%token VAR ID_NAME TYPE_STRING TYPE_BOOL TYPE_NUMBER
%token CONST VALUE_STRING VALUE_BOOL VALUE_NUMBER
%left '*' '/'
%left '+' '-'
%%
program
: declarations
;
declarations
: declaration
| declarations declaration
;
declaration
: var_declaration
| const_declaration
;
value
: VALUE_BOOL
| VALUE_STRING
;
arithmetic_expression
: arithmetic_expression '+' arithmetic_expression
| arithmetic_expression '-' arithmetic_expression
| arithmetic_expression '*' arithmetic_expression
| arithmetic_expression '/' arithmetic_expression
| '(' arithmetic_expression ')'
| VALUE_NUMBER
;
initializer
: value
| arithmetic_expression
;
initialization
: ID_NAME '=' initializer
;
init_list
: initialization
| init_list ',' initialization
;
init_or_id
: initialization
| ID_NAME
;
init_or_id_list
: init_or_id
| init_or_id_list ',' init_or_id
;
var_declaration
: VAR ':' type init_or_id_list ';' { printf("%s booyah\n", $1); }
;
const_declaration: CONST ':' type init_list ';' {printf("koskos\n");}
;
type: TYPE_NUMBER
| TYPE_STRING
| TYPE_BOOL
;
%%
void yyerror (char const *s) {
fprintf (stderr, "%s\n", s);
}
int main(int argc, char** argv[])
{
yyparse();
return 0;
}
功能之一應該是允許用戶使用算術表達式(的值)初始化變量和常量。 像這樣的var:number = (1+2+3);
。 但是,我不確定為什么,但是解析器僅識別使用運算符*
和/
表達式。 給我一個語法錯誤,當我使用表達式其利用運營商的+
和-
這是關聯的lex
文件:
%{
#include <stdio.h>
#include "y.tab.h"
%}
id_name [a-zA-Z]([a-zA-Z0-9])*
value_string \"([a-zA-Z0-9*+z=])*\"
value_number [+-]?([0-9]*[.])?[0-9]+
%%
"var" { return VAR; }
"const" { return CONST; }
"string" { return TYPE_STRING; }
"number" { return TYPE_NUMBER; }
"bool" { return TYPE_BOOL; }
"true" { return VALUE_BOOL; }
"false" { return VALUE_BOOL; }
{value_number} { return VALUE_NUMBER; }
{value_string} { return VALUE_STRING; }
{id_name} { return ID_NAME; }
"," { return ','; }
":" { return ':'; }
";" { return ';'; }
"=" { return '='; }
"+" { return '+'; }
"-" { return '-'; }
"*" { return '*'; }
"/" { return '/'; }
"(" { return '('; }
")" { return ')'; }
%%
我編譯使用以下命令的文件:
yacc -vd grammar.y
flex -l lex.l
gcc -Wall -o lang lex.yy.c y.tab.c -ll -lfl
例如,以下表達式: var:number var1=12*12;
被成功識別。 但是這一個: var:number var1=12+12;
導致syntax error
。 我不確定我的意思是什么。
嘗試使用flex --debug
選項。 這將生成一個掃描儀,向您顯示其運行情況的痕跡。 我想您會很快發現問題。
+12
被詞法化為單個數字令牌,而不是運算符,后跟數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.