为什么我的词法分析器无法识别数字、ID 和运算符

why my lexical analyzer can not recognize numbers and ids and operators

我在 flex 中的词法分析器无法识别数字和 ID 和运算符,只能识别关键字我的错误在哪里?这是我的代码:

%{
#include<stdio.h>
%}

Nums  [0-9]
LowerCase  [a-z]
UpperCase  [A-Z]
Letters  LowerCase|UpperCase|[_]
Id  {Letters}({Letters}|{Nums})*
operators  +|-|\|*
%%
"if" {printf("if keyword founded \n");}
"then" {printf("then keyword founded \n");}
"else" {printf("else keyword founded \n");}
Operators {printf(" operator founded \n");}
Id {printf(" id founded ");}
%%
int main (void)
{ yylex(); return(0);}
int yywrap(void)
{ return 1;}

模式 Operators 等同于 "Operators",因此它只匹配那个单词。如果您打算用该名称扩展宏,则语法为 {Operators}。 (实际上,{operators} 因为您似乎在所有小写的宏名称中拼写不一致。)

如果您这样做,flex 会因为该宏中的语法错误而报错。 (除非扩展宏,否则不会检测到宏中的语法错误。这只是使用宏的问题之一。)

您的其他宏有不同的问题。例如,Nums 根本没有出现在任何规则中。

我的建议是使用更少(或不使用)宏和更多字符 classes。例如:

[[:alpha:]_][[:alnum:]_]*  { /* Action for identifier. */ }
[[:digit:]]+               { /* Action for number. */ }
[-+*/]                     { /* Action for operator. */ }

请阅读 Patterns section in the flex manual 以获得模式语法的完整描述,包括上面前两个模式中使用的命名字符 class 表达式。

要使用命名定义,它必须包含在 {} 中。所以你的 Letters 规则应该是

Letters   {LowerCase}|{UpperCase}|[_]

... 实际上,它匹配文字输入 LowerCaseUpperCase。同样在你的规则中,你想要

{Operators}  ...
{Id}  ...

因为您所拥有的将匹配文字输入字符串 OperatorsId