cpdyj0
V2EX  ›  问与答

想不通为什么这个 ANTLR 文法达不到预期效果?

  •  1
     
  •   cpdyj0 · Sep 7, 2018 · 1397 views
    This topic created in 2810 days ago, the information mentioned may be changed or developed.

    想用来处理 Windows 的 hosts 文件,但是只能正确处理注释部分。

    
    grammar hosts;
    
    hostfile: line* EOF;
    line : item
         | comment
         ;
    item: IPADDRESS HOSTNAME ;
    comment: COMMENT;
    HOSTNAME: [A-z0-9.]+;
    NUM: [0-9] +;
    IPADDRESS: NUM ;
    
    COMMENT: '#' .*? '\r'? '\n';
    NL: ('\r\n'|'\n\r'|'\r'|'\n') ->skip;
    BLANK: (' '|'\t') ->skip;
    
    cpdyj0
        1
    cpdyj0  
    OP
       Sep 7, 2018
    算了,自问自答下吧,在 StackOverFlow 上得到答案了,ANTLR 生成的 lexer 和 parser 是独立的两个东西,parser 不能影响 lexer,所以 lexer 按照最长匹配原则匹配下去,靠前的优先。(发出来的 grammar `IPADDRESS` 那里有误,debug 时改来改去忘记改回来了)`IPADDRESS` 和 `HOSTNAME` 都可以匹配到 IP 地址,`HOSTNAME` 靠前,所以就都成了域名了,文法规则识别不到。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5681 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    ♥ Do have faith in what you're doing.