【发布时间】:2020-04-15 21:41:40
【问题描述】:
我是第一次使用 jflex,我正在按照我在互联网上找到的母语(葡萄牙语)教程进行安装和组装。
但是当我尝试生成“Lexer”类时,它在我的“.flex”文件中显示语法错误,我不知道会发生什么,因为一切似乎都正常。
.flex 文件
//NOME_VARIAVEL,INT,DEC,COMENTARIO,BRANCO,PALAVRA_CHAVE,ERRO
package Compilador;
import static Compilador.Token.*;
%%
%{
private void imprimir (String token,String lexema){
System.out.println(lexema +" ===>> " + token);
}
%}
%class Lexer
%type Token
nomeVariavel = [_a-zA-Z][_zA-z0-9]*
inteiro = [0-9]+
decimal = [0-9]+["."]+[0-9]+
blocoComentario = "/*" ~"*/"
branco = [\t|\n|\r]+
linhaComentario = [branco]*"//" .*
palavrasChave = "if" | "class" | "int" | "while" | "for" | "do" | "float"
%%
{palavrasChave} { imprimir("PALAVRA_CHAVE : ", yytext()); return PALAVRA_CHAVE; }
{nomeVariavel} { imprimir("VARIAVEL : ", yytext()); return NOME_VARIAVEL; }
{inteiro} { imprimir("NUMERO INTEIRO : ", yytext()); return INT; }
{decimal} { imprimir("NUMERO DECIMAL : ", yytext()); return DEC; }
{blocoComentario} { imprimir("COMENTARIO : ", yytext()); return COMENTARIO; }
{linhaComentario} { imprimir("COMENTARIO : ", yytext()); return COMENTARIO; }
{branco} ( return BRANCO; }
. {imprimir("<<< CARACTER INVALIDO!!! >>> ",yytext()); return ERROR;}
<<EOF>> {return null;}
Token.java 文件
package compilador;
public enum Token{
NOME_VARIAVEL, INT, DEC, COMENTARIO, BRANCO, PALAVRA_CHAVE, ERROR;
}
generator.flex 文件
package compilador;
import java.io.*;
public class GeraLexer {
public static void main(String[] args) throws IOException {
String arquivo ="<path redacted for reasons, but it is finding the file>";
geraLexer(arquivo);
}
public static void geraLexer(String arq){
File file = new File(arq);
jflex.Main.generate(file);
}
}
生成时出现错误
Reading "<path redacted for reasons, but it is finding the file>"
Error in file "<path redacted for reasons, but it is finding the file>" (line 28):
Syntax error.
. {imprimir("<<< CARACTER INVALIDO!!! >>> ",yytext()); return ERROR;}
^
Exception in thread "main" jflex.GeneratorException: Generation aborted
at jflex.Main.generate(Main.java:139)
at compilador.GeraLexer.geraLexer(GeraLexer.java:13)
at compilador.GeraLexer.main(GeraLexer.java:8)
Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)
感谢任何愿意提供帮助的人,是的,我先用谷歌搜索了。
【问题讨论】:
-
您的规则中还有许多其他错误。
["."]中的引号和[\t|\n|\r]中的竖线被视为普通字符,因此它们成为字符类的一部分。[branco]是一个匹配这六个字符中的任何一个的字符类;你打算宏扩展{branco}。
标签: java lexical-analysis jflex