start: (_item | _NL)*

_item: rule
     | token
     | statement

_rule_or_token: RULE
              | TOKEN
rule: RULE rule_params priority? ":" expansions{_rule_or_token} _NL
token: TOKEN priority? ":" expansions{TOKEN} _NL

rule_params: ["{" RULE ("," RULE)* "}"]

priority: "." NUMBER

statement: "%ignore" expansions{TOKEN} _NL         -> ignore
         | "%import" import_path{_rule_or_token} ["->" _rule_or_token] _NL   -> import
         | "%import" import_path{_rule_or_token} name_list{_rule_or_token} _NL     -> multi_import
         | "%declare" TOKEN+                        -> declare

!import_path{name}: "."? name ("." name)*
name_list{name}: "(" name ("," name)* ")"

?expansions{name}: alias{name} (_VBAR alias{name})*

?alias{name}: expansion{name} ["->" RULE]

?expansion{name}: expr{name}*

?expr{name}: atom{name} [OP | "~" NUMBER [".." NUMBER]]

?atom{name}: "(" expansions{name} ")"
           | "[" expansions{name} "]" -> maybe
           | value{name}

?value{name}: STRING ".." STRING -> literal_range
            | name
            | (REGEXP | STRING) -> literal
            | name "{" value{name} ("," value{name})* "}" -> template_usage

_VBAR: _NL? "|"
OP: /[+*]|[?](?![a-z])/
RULE: /!?[_?]?[a-z][_a-z0-9]*/
TOKEN: /_?[A-Z][_A-Z0-9]*/
STRING: _STRING "i"?
REGEXP: /\/(?!\/)(\\\/|\\\\|[^\/\n])*?\/[imslux]*/
_NL: /(\r?\n)+\s*/

%import common.ESCAPED_STRING -> _STRING
%import common.INT -> NUMBER
%import common.WS_INLINE

COMMENT: /\s*/ "//" /[^\n]/*

%ignore WS_INLINE
%ignore COMMENT
