Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created November 2, 2011 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/1335148 to your computer and use it in GitHub Desktop.
Save robotlolita/1335148 to your computer and use it in GitHub Desktop.
Parsing API
// 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
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment