【问题标题】:Mutually left-recursive lexer rules on ANTL4?ANTLR4 上的相互左递归词法分析器规则?
【发布时间】:2018-03-08 11:30:47
【问题描述】:

我正在尝试编写 Swift 语言亮点。除了一些语言结构的标记之外,我还想强调一下。以下规则有问题:

Type
   : '[' Type ']'   
   | '[' Type ':' Type ']' 
   | (Attributes? Function_type_argument_clause 'throws'? '->' Type | Attributes? Function_type_argument_clause 'rethrows' '->' Type)
   | (Type_name Generic_argument_clause? | Type_name Generic_argument_clause? '.' Type)
   | Tuple_type
   | Type '?' 
   | Type '!' 
   | (Type_name Generic_argument_clause? | Type_name Generic_argument_clause? '.' Type) '&' Protocol_composition_continuation 
   | (Type '.' 'Type' | Type '.' 'Protocol')
   | 'Any' 
   | 'Self' 
   | '(' Type ')'
   ;

错误:以下规则集是相互左递归的[类型]

试图在规则中离开,只有以下几种情况:

Type
   : Type '?' 
   | 'Any' 
   | 'Self' 
   ; 

但问题依然存在:以下几组规则是相互左递归的[Type]

【问题讨论】:

    标签: antlr antlr4 lexer


    【解决方案1】:

    您将Type 定义为词法分析器规则。 Lexer 规则不能是递归的。 Type 应该是解析器规则。

    见:Practical difference between parser rules and lexer rules in ANTLR?

    请注意,已有 Swift 语法:

    请注意,这些语法是用户自定义的,请正确测试它们!

    编辑

    从词法分析的角度我还是无法理解

    哦,你只是在标记化?好吧,那么你不能像现在这样使用Type。您将不得不重写它,以便不再有左递归。

    例如,假设简化的Type 规则如下所示:

    Type
       : '[' Type ']'   
       | '[' Type ':' Type ']' 
       | Type '?' 
       | Type '!' 
       | 'Any' 
       | 'Self' 
       | '(' Type ')'
       ;
    

    那么你应该像这样重写它:

    Type
       : TypeStart TypeTrailing?
       ;
    
    fragment TypeStart
       : '[' Type ']' 
       | '[' Type ':' Type ']'
       | 'Any'
       | 'Self'
       | '(' Type ')'
       ;
    
    fragment TypeTrailing: [?!];
    

    【讨论】:

    • 我了解你。我该如何处理语法高亮?从词法分析的角度来看,我仍然无法理解它 - 找到所需的标记并突出显示。以及如何使用解析器规则来做到这一点?
    • @jeudesprit 检查我的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多