我想要一个解析规则,它只能识别0到32767之间的数字。我试过这样的方法:
integerConstant
^ (#digit asParser min: 1 max: 5) flatten
==> [ :string | | value |
value := string asNumber.
(value between: 0 and: 32767)
ifTrue: [ value ]
ifFalse: [ **???** ]]但我不知道该写什么?我想过返回一个PPFailure,但这需要知道流的位置。
发布于 2013-03-13 07:24:10
正如您所怀疑的,您可以让操作返回一个PPFailure。虽然这通常不是一个好的风格(混合了语法和语义分析),但有时它是有帮助的。在PetitParser的测试中,有几个例子。你在PPXmlGrammar>>#element和PPSmalltalkGrammar>>#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 ] ]https://stackoverflow.com/questions/15371334
复制相似问题