【发布时间】:2018-10-06 01:26:30
【问题描述】:
所以,我刚开始学习 antlr4,我只是做了一个非常简单的编程语言。该语言可以创建变量(int、布尔值和字符串)、更改它们的值并输出它们的值。但是,我正在尝试做一个 if 语句,但经过多次尝试,它没有用。谷歌搜索也没有帮助,因为大多数其他代码都太不同了,无法自己理解和应用。我的大部分代码都遵循本教程:
https://progur.com/2016/09/how-to-create-language-using-antlr4.html
这是我的语法文件
grammar valhallap;
program : 'begin' statement+ 'end';
ifState : ifDec 'STARTIF' statement+ 'ENDIF';
statement : createINT|assign|addINT|printVar|createString|print|createBool|;
ifDec: 'if' (NUMBER|ID) EXPRESION (NUMBER|ID) 'then';
createINT : 'new' 'int' ID;
createBool: 'new' 'bool' ID;
createString : 'new' 'string' ID;
addINT : 'addINT' ID NUMBER;
assign : 'set' ID (STRING|BOOL|NUMBER);
print : 'output' 'say' STRING;
printVar : 'output' 'var' ID;
ID : [A-z]+;
NUMBER : [0-9]+ ;
STRING : ["] ( ~["\r\n\\] | '\\' ~[\r\n] )* ["] | ['] ( ~['\r\n\\] | '\\' ~[\r\n] )* ['];
BOOL : 'true' | 'false';
WS : [ \n\t]+ -> skip;
Comment: '**' ~( '\r' | '\n' )* -> skip;
STATEMENT : .;
EXPRESION:
'MORETHAN'
|'LESSTHAN'
|'EQUALS'
|'LESSEQUALS'
|'MOREEQUALS';
最后是监听器类
import com.power.valhallap.grammar.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
/**
*
* @author admin
*/
public class ValhallaListener extends valhallapBaseListener{
/**
* @param args the command line arguments
*/
private Map<String, Object> variables;
public static boolean ifState = false;
public ValhallaListener()
{
//init all the variables
variables = new HashMap<>();
}
//if statements
@Override
public void exitAssign(valhallapParser.AssignContext ctx)
{
String variable = ctx.ID().getText();
if(variables.get(variable) instanceof String)
{
if(ctx.NUMBER() != null || ctx.BOOL() != null)
{`enter code here`
System.out.println("error expecting string");
}
}
if(variables.get(variable) instanceof Boolean)
{
if(ctx.NUMBER() != null || ctx.STRING() != null)
{
System.out.println("error expecting boolean");
}
}
if(variables.get(variable) instanceof Integer)
{
if(ctx.STRING() != null || ctx.BOOL() != null)
{
System.out.println("error expecting integer");
}
}
if(ctx.STRING() != null)
{
if(variables.get(variable) instanceof String)
{
String finalString = ctx.STRING().getText();
finalString = finalString.replace("\"", "");
variables.put(variable, finalString);
}
}
if(ctx.NUMBER() != null)
{
if(variables.get(variable) instanceof Integer)
{
variables.put(variable, Integer.parseInt(ctx.NUMBER().getText()));
}
}
if(ctx.BOOL() != null)
{
if(variables.get(variable) instanceof Boolean)
{
boolean answer = Boolean.parseBoolean(ctx.BOOL().getText());
variables.put(variable, answer);
}
}
}
@Override
public void exitCreateINT(valhallapParser.CreateINTContext ctx)
{
//get's the variable name of int
String variableName = ctx.ID().getText();
if(!variables.containsKey(variableName))
{
//add the name to the hashmap with the init value of 0
variables.put(variableName, 0);
}
}
@Override
public void exitAddINT(valhallapParser.AddINTContext ctx)
{
//get the var name
String varName = ctx.ID().getText();
//get the value
int first = Integer.parseInt(variables.get(varName).toString());
int addValue = Integer.parseInt(ctx.NUMBER().getText());
int finalValue = first + addValue;
//assign the new value
variables.put(varName, finalValue);
}
@Override
public void exitPrintVar(valhallapParser.PrintVarContext ctx)
{
String varName = ctx.ID().getText();
System.out.println(variables.get(varName));
}
@Override
public void exitPrint(valhallapParser.PrintContext ctx)
{
String output = ctx.STRING().getText();
output = output.replace("\"", "");
System.out.println(output);
}
@Override
public void exitCreateString(valhallapParser.CreateStringContext ctx)
{
String variableName = ctx.ID().getText();
if(!variables.containsKey(variableName))
{
//add the name to the hashmap with the init value of null
variables.put(variableName, "");
}
}
@Override
public void exitCreateBool(valhallapParser.CreateBoolContext ctx)
{
//get's the variable name of int
String variableName = ctx.ID().getText();
if(!variables.containsKey(variableName))
{
//add the name to the hashmap with the init value of false
variables.put(variableName, false);
}
}
public static void main(String[] args) {
try {
ANTLRInputStream input = new ANTLRInputStream(
new FileInputStream(args[0]));
valhallapLexer lexer = new valhallapLexer(input);
valhallapParser parser = new valhallapParser(new CommonTokenStream(lexer));
parser.addParseListener(new ValhallaListener());
// Start parsing
parser.program();
if(ifState)
{
parser.ifState();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我要实现的if语句的语法是:
begin
if 5 MORETHAN 4 then
.....
ENDIF
end
我是antlr4的新手,有些概念对我来说是新的,如果有人能帮助我,谢谢!
【问题讨论】:
-
“它不起作用”什么也没告诉我们。请阅读:stackoverflow.com/help/how-to-ask
-
所以,我的程序开始解析“开始”和“结束”关键字之间的“语句”。所以我尝试的是在 then 关键字之后调用语法文件中的“语句”,如果 if 语句返回 true,则将执行该语句。但是,我无法通过 if 语句从解析器中停止解析器。换句话说,解析器只是忽略 if 语句并解析所有内容。所以我认为肯定有其他方法,因为我在互联网上看到了许多不同的例子,但我只是需要对所有这些进行一些解释。
-
一步一步更好地解决您的问题。你的问题不是听众。您的问题是对解析的理解。如果您想在
begin...end之间使用 if 语句,您应该允许它作为语句(而不是显式解析它,取决于静态变量ifState。请将您的示例简化为您的主要问题。如果您问另一个问题,没人会介意当您的第一个问题解决时提出问题。
标签: java antlr antlr4 language-design