返回不同类型的对象时,将访问者或侦听器与ANTLR4一起使用

问题描述 投票:3回答:3

我使用ANTLR4将一种语言翻译成另一种语言。例如,当我阅读数字文字时,我可以返回IntegerDouble

@Override
public Integer visitIntegerValue(Parser.IntegerValueContext ctx) {
    return Integer.valueOf(ctx.getText());
}

@Override
public Double visitDoubleValue(Parser.DoubleValueContext ctx) {
    return Double.valueOf(ctx.getText());
}

最终,如果进一步扩展此方法并引入其他构造(如字符串和条件),则对于访客来说,唯一合理的类型是class Visitor extends BaseVisitor<Object>,但它会导致代码与instanceof紧密相关。例如

@Override
public CollectionQuery visitCondition(Parser.ConditionContext ctx) {
    Property property = (Property) visit(ctx.property());
    String operator = (String) visit(ctx.operator());
    Object value = visit(ctx.amount());
    Object condition;
    if (value instanceof String && operator.equals("$regex")) {
        condition = Pattern.compile((String) value, Pattern.CASE_INSENSITIVE);
    }
    ...
}

虽然我不介意这种“动态性”,但我想知道这是否是一种可维护的方法,还是我应该使用其他技术来代替,例如创建目标语言结构的适当层次结构。

java antlr antlr4
3个回答
2
投票

以给人留下深刻印象的自定义后处理效果。

一些ANTLR代码

topMostRule : childRule+ EOL;
childRule : variantOne | variantTwo;
variantOne : 'A';
variantTwo : '1';
...

用于自定义后处理的伪代码(比Java多的C#,而不是ANTLR使用的真实方法名):

public class MyCustomPostprocessor
{
    private IntermediateResults lookupTable; // use private fields for lookup tables etc.

    public ResultType process(Parser.TopMostRuleContext ctx)
    {
        // inspect the children
        var children = new List<object>();
        foreach (var rule in ctx.ChildRules)
        {
            switch (rule.Type)
            {
            case typeof (Parser.ChildRuleContext):
                var result = process(rule);
                children.Add(result);
            else
                throw new NotImplementedException("Don't know what to do with " + rule.Type.ToString());
            }

            // use the information gathered so far to form the result
            return new ResultType (children);
        }
    }


    public object process (Parser.ChildRuleContext)
    {
        foreach (var rule in ctx.ChildRules)
        {
            switch (rule.Type)
            {
            case typeof (Parser.VariantOneContext):
                var result = process(rule);
                return result;
            case typeof (Parser.VariantTwoContext):
                var result = process(rule);
                return result;
            else
                throw new NotImplementedException("Don't know what to do with " + rule.Type.ToString());
            }

        }
    }

    public string process (Parser.VariantOneContext ctx)
    {
        return ctx.GetText();
    }

    public int process (Parser.VariantTwoContext ctx)
    {
        return Int.Parse(ctx.GetText());
    }


}

1
投票

我建议创建一个Value类来包装不同类型的对象,然后将此值类用作访问者的通用类型。

Visitor<Value> visitor;

public class Value {
    private Object value;

    public Value(Object object) {
        this.value = object
        if (!(isDouble() || isInteger))
            throw new IllegalArgumentException();
    }


    public boolean isDouble() {
        return value instanceof Double;
    }
    public Double asDouble() {
        return (Double) value;
    }

    public boolean isInteger() {
        return value instanceof Integer;
    }

    public Integer asInteger() {
        return (Integer) value;
    }


    @Override
    public int hashCode() {
        // generate hascode
    }

    @Override
    public boolean equals(Object object) {
        // equals
    }
}

0
投票

一个建议是每个返回类型都有一个访客:

public class IntegerVisitor extends BaseListener<Integer> {
  @Override
  public Integer visitIntegerValue(Parser.IntegerValueContext ctx) {
    return Integer.valueOf(ctx.getText());
  }
}

public class DoubleVisitor extends BaseListener<Double> {
  @Override
  public Double visitDoubleValue(Parser.DoubleValueContext ctx) {
    return Integer.valueOf(ctx.getText());
  }
}

[当您访问截然不同的事物时,这更有意义(例如,如果您使用Java语法进行解析,则可能会有MethodVisitorClassVisitor等。请参见此处的示例:See an example here

© www.soinside.com 2019 - 2024. All rights reserved.