fastparse
A very simple and stupid parser, based on a statemachine and regular expressions.
It's not intended for complex languages. It's intended to easily write a simple parser for a simple language.
Usage
Pass a description of statemachine to the constructor. The description must be in this form:
new Parser(description)
description is {
"state-name": {
"a": true,
"b": "other-state-name",
"[cde]": function(match, index, matchLength) {
return "other-state-name";
},
"([0-9]+)(\\.[0-9]+)?": function(match, first, second, index, matchLength) {
},
}
}
The statemachine is compiled down to a single regular expression per state. So basically the parsing work is delegated to the (native) regular expression logic of the javascript runtime.
Parser.prototype.parse(initialState: String, parsedString: String, context: Object)
initialState
: state where the parser starts to parse.
parsedString
: the string which should be parsed.
context
: an object which can be used to save state and results. Available as this
in transition functions.
returns context
Example
var Parser = require("fastparse");
var parser = new Parser({
"source": {
"/\\*": "comment",
"//": "linecomment",
},
"comment": {
"\\*/": "source",
"@licen[cs]e\\s((?:[^*\n]|\\*+[^*/\n])*)": function(match, licenseText) {
this.licences.push(licenseText.trim());
}
},
"linecomment": {
"\n": "source",
"@licen[cs]e\\s(.*)": function(match, licenseText) {
this.licences.push(licenseText.trim());
}
}
});
var licences = parser.parse("source", sourceCode, { licences: [] }).licences;
console.log(licences);
License
MIT (http://www.opensource.org/licenses/mit-license.php)