Created
November 2, 2011 22:33
-
-
Save robotlolita/1335148 to your computer and use it in GitHub Desktop.
Parsing API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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