ANTL4 上的相互左递归词法分析器规则?

Mutually left-recursive lexer rules on ANTL4?

我正在尝试编写 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
   : Type '?' 
   | 'Any' 
   | 'Self' 
   ; 

但问题依旧:下面的几组规则是相互左递归的[Type]

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

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

请注意,现有 Swift 个语法:

注意这些语法是user-comitted,好好测试一下!

编辑

I'm still unable to understand it from the point of view of lexical analysis

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

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

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

那么你应该这样重写:

Type
   : TypeStart TypeTrailing?
   ;

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

fragment TypeTrailing: [?!];