public
Created

Parsing API

  • Download Gist
parser.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// It would be this:
//---
var Literal = clone(Base, {
// :: Str → Literal
make: function make(text) {
return clone(Literal, { text: String(text) })
},
 
// :this: ParserState → [Token, ParserState]
parse: function parse(ps) {
var text = this.text
return ps.match(text)? [Token.copy('LITERAL', text), ps.move(text.length)]
: /* failed? */ [null, ps]
},
 
// :this: ParserState → Error
failed: function failed(ps) {
return new SyntaxError( this.error(ps)
+ '\n Arising from ' + ps.describe()
+ '\n\n'
+ ps.snippet())
},
 
// :this: ParserState → Str
error: function error(ps) {
return 'Expected the literal "' + this.text + '", '
+ 'got "' + ps.lookahead(this.text.length) + '" instead.'
}
})
//---
 
// Instead of this:
//---
function literal(text) { return function(ps) {
return ps.match(text)? [Token.copy('LITERAL', text), ps.move(text.length)]
: /* failed? */ [null, ps]
}}
//---
 
 
// That is, given the error handling is performed by operators, like the
// `required' one:
function required(matcher){ return function(ps) { var result
result = matcher.parse(ps)
if (failedp(result)) throw matcher.failed(ps)
 
return result
}}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.