JLex 扫描仪生成
我正在使用 JLex 来完成我们最新的作业,尝试为教授给我们的语言生成扫描仪。
此时,我编写了以下内容 - 假设关键字和标识符规则对于我们正在使用的语言是正确的。
import java.io.*;
%%
%{
public static void main(String argv[]) throws java.io.IOException
{
MyLexer yy= new MyLexer(new FileReader("input"));
while( yy.yylex() >= 0);
}
%}
%integer
%class MyLexer
INT =int
KEYWORDS =IF|ELSE|WRITE|READ|RETURN|BEGIN|END|MAIN|INT|REAL
IDENTIFIER =[a-zA-Z_][a-zA-Z0-9_]*
%state COMMENT
%%
{KEYWORDS}
{
System.out.println("keyword is .. " + yytext());
}
{IDENTIFIER}
{
System.out.println("ID is .." + yytext());
}
\r\n|.|\n {}
任何人都可以提供一些有关如何执行以下操作的提示或建议: 1. 检测注释(/* */ 格式) 2. 统计标识符、关键字等的每次出现。
I'm using JLex for our latest assignment, attempting to generate a scanner for a language given to us by the professor.
At this point, I have the following written - assume the keywords and identifier rules are correct for the language we're working with.
import java.io.*;
%%
%{
public static void main(String argv[]) throws java.io.IOException
{
MyLexer yy= new MyLexer(new FileReader("input"));
while( yy.yylex() >= 0);
}
%}
%integer
%class MyLexer
INT =int
KEYWORDS =IF|ELSE|WRITE|READ|RETURN|BEGIN|END|MAIN|INT|REAL
IDENTIFIER =[a-zA-Z_][a-zA-Z0-9_]*
%state COMMENT
%%
{KEYWORDS}
{
System.out.println("keyword is .. " + yytext());
}
{IDENTIFIER}
{
System.out.println("ID is .." + yytext());
}
\r\n|.|\n {}
Could anyone give some sort of hint or suggestion on how to:
1. detect comments (of the /* */ format)
2. count each occurrence of identifiers, keywords, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您创建了 main 方法,您还可以在 lex 文件中为您的词法分析器创建成员变量:
然后您可以在与 KEYWORDS 关联的代码中增加 keywordsCount:
检测注释听起来像是本作业的主要任务,所以我将保留它给你;)
但我会告诉你,你应该研究 LEX / JFlex 状态。您将检测到 /*,然后转换为注释状态。当您在注释状态下检测到 */ 时,您将退出注释状态。
You created the main method, you can also create member variables for you lexer in the lex file:
Then you can increment keywordCount in the code associated with KEYWORDS:
Detecting comments sounds like the main task for this homework assignment, so I'll leave that to you ;)
but I'll tell you that you should look into LEX / JFlex states. You would detect a /* and then transition into a comment state. When you detect */, while in the comment state, you would transition out of the comment state.