PEG.buildParser now accepts grammars only in string format.

redux
David Majda 14 years ago
parent 927f2d65c9
commit 48da65d08e

@ -11,32 +11,18 @@ function nop() {}
/* /*
* Generates a parser from a specified grammar and start rule and returns it. * Generates a parser from a specified grammar and start rule and returns it.
* *
* The grammar may be either an object or a string. If it is an object, it * The grammar must be a string in the format described by the metagramar in the
* must contain AST of the parsing expressions (i.e. instances of |PEG.Grammar.* * metagrammar.pegjs file. The start rule may be unspecified, in which case
* classes| for the grammar rules in its properties. If it is a string, it is * "start" is used.
* parsed using |PEG.grammarParser| to obtain the grammar AST and thus it must
* be in a format that this parser accepts (see the source code for details).
* *
* The start rule may be unspecified, in which case "start" is used. * Throws |PEG.Grammar.GrammarError| if the grammar contains an error. Note that
* * not all errors are detected during the generation and some may protrude to
* Throws |PEG.Grammar.GrammarError| if the grammar definition is not object nor * the generated parser and cause its malfunction.
* string or if it contains an error. Note that not all errors are detected
* during the generation and some may protrude to the generated parser and cause
* its malfunction.
*/ */
PEG.buildParser = function(grammar, startRule) { PEG.buildParser = function(grammar, startRule) {
startRule = startRule || "start"; startRule = startRule || "start";
switch (typeof(grammar)) { var ast = PEG.grammarParser.parse(grammar);
case "object":
var ast = grammar;
break;
case "string":
var ast = PEG.grammarParser.parse(grammar);
break;
default:
throw new PEG.Grammar.GrammarError("Grammar must be object or string.");
}
for (var key in ast) { for (var key in ast) {
ast[key].checkReferencedRulesExist(ast); ast[key].checkReferencedRulesExist(ast);

@ -169,17 +169,9 @@ test("generateUniqueIdentifier", function() {
module("PEG"); module("PEG");
test("buildParser reports invalid grammar object", function() {
throws(
function() { PEG.buildParser(42); },
PEG.Grammar.GrammarError,
{ message: "Grammar must be object or string." }
);
});
test("buildParser reports missing start rule", function() { test("buildParser reports missing start rule", function() {
throws( throws(
function() { PEG.buildParser({}); }, function() { PEG.buildParser('notStart: "abcd"'); },
PEG.Grammar.GrammarError, PEG.Grammar.GrammarError,
{ message: "Missing \"start\" rule." } { message: "Missing \"start\" rule." }
); );

Loading…
Cancel
Save