2013-03-12 23 views
3

我想,只有0和32767之間的數字識別解析規則,我想是這樣的:PetitParser解析規則如何發出錯誤信號?

integerConstant 
^(#digit asParser min: 1 max: 5) flatten 
     ==> [ :string | | value | 
      value := string asNumber. 
      (value between: 0 and: 32767) 
       ifTrue: [ value ] 
       ifFalse: [ **???** ]] 

但我不知道該怎麼寫的???。我想回到PPFailure,但這需要知道流的位置。

回答

7

正如您懷疑的那樣,您可以使該操作返回PPFailure。雖然通常這不是很好的風格(混合語法和語義分析),但它有時很有用。在PetitParser的測試中有幾個例子。您在PPXmlGrammar>>#elementPPSmalltalkGrammar>>#number處看到的好用處。

PPFailure的位置只是PetitParser向其用戶(工具)提供的東西。它不是用於解析本身的東西,因此如果您覺得懶惰,可以將其設置爲0。或者,您可以使用以下示例獲取輸入中的當前位置:

positionInInput 
    "A parser that does not consume anything, that always succeeds and that 
    returns the current position in the input." 

    ^[ :stream | stream position ] asParser 

integerConstant 
    ^(self positionInInput , (#digit asParser min: 1 max: 5) flatten) map: [ :pos :string | 
     | value | 
     value := string asNumber. 
     (value between: 0 and: 32767) 
      ifTrue: [ value ] 
      ifFalse: [ PPFailure message: value , ' out of range' at: pos ] ] 
+0

好吧,瘋狂的解決方案,但工作:-)。你有沒有特意寫出「self positionInput」,還是你的意思是「positionInput」作爲一個實例變量? – 2013-03-13 16:16:20

+0

您不需要循環中未使用的規則的實例變量。如果解析器'positionInInput'足夠常見,它可以移到某個地方的工廠方法中,甚至在它自己的PPParser子類中。 – 2013-03-16 23:21:08

相關問題