简体   繁体   English

Antlr4-多行文件解析器-

[英]Antlr4 - Parser for multi line file -

I'm trying to use antlr4 to parse a ssh command result, but I can not figure out why this code doesn't work, I keep getting an "extraneous input" error. 我正在尝试使用antlr4解析ssh命令结果,但是我无法弄清楚为什么此代码不起作用,我不断收到“外部输入”错误。

Here is a sample of the file I'm trying to parse : 这是我要解析的文件的示例:

system
home[1]  HOME-NEW
    sp
    cpu[1]
    cpu[2]
home[2]  SECOND-HOME
    sp
    cpu[1]
    cpu[2]

Here is my grammar file : 这是我的语法文件:

listAll 
  : ( system | home | NL)*
  ;

elements
  : (sp | cpu )*
  ;

home 
  : 'home['  number ']' value NL elements
  ;

system
  : 'system' NL
  ;

sp 
  : 'sp' NL
  ;

cpu
  : 'cpu[' number ']' NL
  ;

value 
  : VALUE
  ;

number
  : INT
  ;

VALUE : STRING+; 
STRING: ('a'..'z'|'A'..'Z'| '-' | ' ' | '(' | ')' | '/' | '.' | '[' | ']');
INT   :    ('0'..'9')+ ;
NL  : '\r'? '\n';
WS    :     (' '|'\t')* {skip();} ;

The entry point is 'listAll'. 入口点是“ listAll”。 Here is the result I get : 这是我得到的结果:

(listAll \r\n (system system \r\n) home[1]  HOME-NEW \r\n sp \r\n cpu[1] \r\n cpu[2] \r\n[...])

The parsing failed after 'system'. 在“系统”之后解析失败。 And I get this error : line 2:1 extraneous input 'home[1] HOME-NEW' expecting {, system', NL, WS} 我得到这个错误:2:1行多余的输入'home [1] HOME-NEW'期望{,system',NL,WS}

Does anybody know why this is not working ? 有人知道为什么这不起作用吗? I am a beginner with Antlr, and I'm not sure I really understand how it works ! 我是Antlr的初学者,我不确定我是否真的了解它的工作原理! Thank you all ! 谢谢你们 !

You need to combine NL and WS as one WS element and skip it using -> skip (not {skip()} ) 您需要将NLWS合并为一个WS元素,并使用-> skip (不是{skip()} )跳过它

And since the WS will be skipped automatically, no need to specify it in all the rules. 并且由于将自动跳过WS ,因此无需在所有规则中都指定它。

Also, your STRING had a space ( ' ' ) which was causing the error and taking up the next input. 另外, STRINGspace' ' )导致了错误并占用了下一个输入。

Here is your complete grammar : 这是您完整的语法:

listAll   :   ( system | home )* ;

elements  :   ( sp | cpu )* ;

home      :   'home['  number ']' value elements;

system    :   'system' ;

sp        :   'sp' ;

cpu       :   'cpu[' number ']' ;

value     :   VALUE ;

number    :   INT ;

VALUE     :   STRING+; 

STRING    :   ('a'..'z'|'A'..'Z'| '-' | '(' | ')' | '/' | '.' | '[' | ']') ;

INT       :   [0-9]+ ;

WS        :   [ \t\r\n]+ -> skip ;

Also, I'll suggest you to go through the ANTLR4 Documentation 另外,我建议您阅读ANTLR4文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM