【问题标题】:Xtext 2.8+ formatter, formatting simple ruleXtext 2.8+ 格式化程序,格式化简单规则
【发布时间】:2016-04-07 21:20:18
【问题描述】:

我是 Xtend/Xtext 新手。目前我正在使用新的格式化程序 API,我正在尝试格式化规则,如下所示:

Expression:
    Error|Warning|Enum|Text
;

用这样的 xtend 调度方法

def dispatch void format(Expression e){
        if (e instanceof ErrorImpl)
            ((ErrorImpl)e).format
}

问题是,那种类型的表达式 e 是无法发现的,我收到了这个错误

Type mismatch: cannot convert from Class<ErrorImpl> to Expression

为什么我不能进行这种转换(我当然怀疑 xTend 语义)(甚至 Eclipse 都告诉我 Expression 只是创建子对象的接口。)以及如何我可以为这条规则的每个孩子调用 format 方法吗?谢谢。

【问题讨论】:

    标签: xtext xtend


    【解决方案1】:

    Xtend 的类型转换语法不同:你写 e as ErrorImpl 而不是 (ErrorImpl) e。在这种情况下,甚至不需要类型大小写:由于前面的instanceof 检查,变量e 被隐式转换为ErrorImpl,因此您可以编写与

    相同的代码
    def dispatch void format(Expression e) {
        if (e instanceof ErrorImpl)
            e.format
    }
    

    但是,此代码会导致堆栈溢出,因为 format(EObject) 方法是用相同的输入递归调用的。为了正确利用调度方法的强大功能,您应该这样编写代码:

    def dispatch void format(Error error) {
        // Code for handling Errors
    }
    def dispatch void format(Warning warning) {
        // Code for handling Warnings
    }
    def dispatch void format(Enum enum) {
        // Code for handling Enums
    }
    def dispatch void format(Text text) {
        // Code for handling Texts
    }
    

    这会生成一个方法format(Expression),它会根据参数类型自动分派到更具体的方法。

    请注意,格式化程序调度方法还需要 IFormattableDocument 类型的第二个参数,因此它们应该看起来像

    def dispatch void format(Error error, extension IFormattableDocument document) {
        // Code for handling Errors
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 2012-05-05
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多