简体   繁体   English

调试词法分析器问题

[英]Debugging lexical analyzer issue

I am writing a lexical analyzer here is the code: 我正在写一个词法分析器,代码如下:

%{
#include <stdio.h>
void showToken(char*);
%}

%%
int main(){
void showToken(char* name){
        printf("<%s,%s>",name,yytext);
}
return 0;
}
%%

I am getting the following : 我得到以下内容:

~/hedor1>cc -c -o lexical.o lexical.c
lexical.l:40: error: expected identifier or â(â before â%â token

I cant find where is the problem and moreover in the CODE SECTION must I write : 我找不到问题所在,而且必须在代码部分中写:

int main(){}

what happens if I don't write the main function above? 如果我不写上面的main函数会怎样?

Primary problem 主要问题

You can only have two %% lines in a Lex (Flex) analyzer. Lex(Flex)分析器中只能有两条%%行。

...definitions...
%%
...lexical patterns...
%%
...everything else...

The programs Lex and Flex simply copy the content of the file after the second %% verbatim into the generated C code. 程序Lex和Flex仅将第二个%%逐字记录后的文件内容复制到生成的C代码中。 And C doesn't like %% at any time. C随时都不喜欢%%

Nitpick 尼派克

You shouldn't nest functions inside each other like you're trying to with: 您不应该像尝试使用的那样将函数嵌套在一起:

int main(){
void showToken(char* name){
        printf("<%s,%s>",name,yytext);
}
return 0;
}

You need to separate main() from showToken() . 您需要将main()showToken()分开。 (There is a GCC-specific extension that does allow nested functions. Don't use it.) (有一个特定于GCC的扩展确实允许嵌套函数。不要使用它。)


Also, when you have a line number in an error message, it is helpful to insert a comment to identify the line in the source. 另外,当错误消息中有行号时,插入注释以标识源中的行会很有帮助。 Or describe the line that is identified. 或描述所标识的线。 But we shouldn't have to count the lines in your code, even if the error is in line 1...well, maybe lines 1-3 aren't too critical, but there is a fuzzy breakpoint after which identifying the line is important. 但是,即使错误出现在第1行中,我们也不必对代码中的行进行计数...好吧,也许第1-3行不是很关键,但是有一个模糊断点,之后可以确定该行是重要。 By the time is has reached the teens, it is close to essential; 到了十几岁的时候,它已经很重要了; the first 5 lines probably aren't crucial; 前5行可能并不关键; in between (6-12) it's generally better to indicate the line number. 在(6-12)之间,通常最好指出行号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM