0

Can I make PEG.js return a default value instead of throwing a parse error?

basically I would like to have

/ anything:.* {return anything} 

in my grammar, but if any rule partially mathes it will still throw a Parse error.

So

start 
  = digits:[0-9]+ 
  / anything:.* {return "hello world"+anything}

will still throw a parse error on "546aueu". Try at http://pegjs.org/online

how can I tell make a parser return something instead of throwing an error.

As far as i know it should try to match the first rule and if it fails it should match the secon.

Thans for any help and suggestions.

zidarsk8
  • 3,088
  • 4
  • 23
  • 30

2 Answers2

1

You could try using the ! operator

start 
  = digits:[0-9]+ ![^0-9] { return {type: 'digits', number: digits.join('')}; }
  / anything:.* { return { type: 'anything', anything: anything.join('') }; }


parser.parse('123456')

{
   "type": "digits",
   "number": "123456"
}

parser.parse('123abc456')

{
   "type": "anything",
   "anything": "123abc456"
}
dan
  • 2,378
  • 18
  • 17
0

You can only do this by putting a fallback as a last item in every rule that can fail. This is because pegjs does not do backtracking, so when a rule matches it will either succeed or quit the entire process with a parse error.

fafl
  • 7,222
  • 3
  • 27
  • 50