2014-11-21 64 views
0
處理

我已生成使用JISON解析器:錯誤JISON

%lex 
%x TEXT 
%% 

("Project"|"project") {return 'PROJECTCOMMAND';} 
"-au" {return 'ADDUSER';} 
"-n" {this.begin('TEXT'); return 'NAMEOPTION';} 
"-k" {return 'KEYOPTION';} 
"-desc" {return 'DESCRIPTION';} 
("--add"|"-a") {return 'ADDOPTION';} 
<TEXT>[[email protected]\.]+ {this.popState(); return 'TEXT';} 
<INITIAL,TEXT>\s+ // Ignore white space... 

/lex 
%% 
line : 
     PROJECTCOMMAND ADDUSER 
      { 
       //Project Command of add user 
       var res = new Object(); 
       res.value = "addUser Project"; 
       return res; 
      }  
    | PROJECTCOMMAND ADDOPTION 
      { 
       //Project Command with no arguments 
       var res = new Object(); 
       res.value = "addProject"; 
       return res; 
      } 
    | PROJECTCOMMAND ADDOPTION NAMEOPTION TEXT 
      { 
       //Project command with project name as argument 
       var res = new Object(); 
       res.value = "addProject name"; 
       res.name = $4; 
       return res; 

    }  

以上工作正常,如果我給喜歡命令:

project -a 
project -au 
project -a -n abc 
... 

但是如果我在這樣的命令類型給出了錯誤:

project -a abcd  

它引發錯誤。
同樣的方式,如果我給一個命令

project -a -n 

錯誤:解決這個問題是寫所有可能的錯誤情況,但會被永遠不會結束,因爲作爲命令增加可能

Expecting 'TEXT' got `1' 

的一種方式錯誤的情況也增加,反正我可以告訴解析器,如果它不滿足任何上述命令然後拋出一個常見錯誤?

由於提前

回答

1

我GESS,projectPROJECTCOMMAND-aADDOPTIONabcdNAMEOPTION和解析器aspected第四點 - TEXT。你有一個,兩個和四個節點的替代品,但不是三個。

1

這是一個老問題,但我回答只是爲了防止有人來到這裏,這可能會有所幫助。

如果我理解正確,你想要的是能夠有一個通用的錯誤消息。

What I'm doing is surrounding the .parse() in a try/catch clause and replacing the error message with the one I want (specially because error messages in a complex grammar can be giant)

但我只想澄清錯誤:

的事情是,有沒有比賽的情況下爲

"PROJECTCOMMAND ADDOPTION TEXT" 
(project -a abcd) 

您需要創建此規則。這就是你得到錯誤的原因。

同樣的事情用project -a -n當你得到的錯誤是,有遺漏的參數匹配

"PROJECTCOMMAND ADDOPTION NAMEOPTION TEXT" 

我還重寫規則:

%% 
("Project"|"project") return 'PROJECTCOMMAND'; 

"-au"     return 'ADDUSER'; 
"-n"     return 'NAMEOPTION'; 
"-k"     return 'KEYOPTION'; 
"-desc"     return 'DESCRIPTION'; 
("--add"|"-a")   return 'ADDOPTION'; 
<TEXT>[[email protected]\.]+ {this.popState(); return 'TEXT';} 
<INITIAL,TEXT>\s+ 
<<EOF>>     return 'EOF'; 
/lex 
%start line 

%% 

line 
    : PROJECTCOMMAND options EOF 
     { 
      //enter code here 
     } 
    | PROJECTCOMMAND options TEXT EOF 
     { 
      //enter code here 
     } 
    ; 
options 
    : option 
     { 
      //enter code here 
     } 
    | options option 
     { 
      //enter code here 
     } 
    ; 

option 
    : ADDUSER 
     { 
      //enter code here 
     } 
    | NAMEOPTION 
     { 
      //enter code here 
     } 
    | KEYOPTION 
     { 
      //enter code here 
     } 
    | DESCRIPTION 
     { 
      //enter code here 
     } 
    | ADDOPTION 
     { 
      //enter code here 
     } 
    ; 

這樣,您就可以輕鬆添加不同的選項並一起處理它們的行爲。