Browse Source

Replace "var" with "let" & "const"

This is purely a mechanical change, not taking advantage of block scope
of "let" and "const". Minimizing variable scope will come in the next
commit.

In general, "var" is converted into "let" and "const" is used only for
immutable variables of permanent character (generally spelled in
ALL_CAPS). Using it for any immutable variable regardless on its
permanence would feel confusing.

Any code which is not transpiled and needs to run in ES6 environment
(examples, code in grammars embedded in specs, ...) is kept unchanged.
This is also true for code generated by PEG.js.

See #442.
redux
David Majda 5 years ago
parent
commit
bdf91b5941
  1. 2
      benchmark/benchmarks.js
  2. 10
      benchmark/index.js
  3. 22
      benchmark/run
  4. 10
      benchmark/runner.js
  5. 6
      benchmark/server
  6. 36
      bin/pegjs
  7. 6
      lib/compiler/asts.js
  8. 6
      lib/compiler/index.js
  9. 2
      lib/compiler/js.js
  10. 2
      lib/compiler/opcodes.js
  11. 30
      lib/compiler/passes/generate-bytecode.js
  12. 42
      lib/compiler/passes/generate-js.js
  13. 6
      lib/compiler/passes/remove-proxy-rules.js
  14. 4
      lib/compiler/passes/report-duplicate-labels.js
  15. 6
      lib/compiler/passes/report-duplicate-rules.js
  16. 6
      lib/compiler/passes/report-infinite-recursion.js
  17. 4
      lib/compiler/passes/report-infinite-repetition.js
  18. 4
      lib/compiler/passes/report-undefined-rules.js
  19. 12
      lib/compiler/visitor.js
  20. 2
      lib/grammar-error.js
  21. 6
      lib/parser.js
  22. 8
      lib/peg.js
  23. 8
      lib/utils/arrays.js
  24. 2
      lib/utils/classes.js
  25. 8
      lib/utils/objects.js
  26. 14
      spec/api/generated-parser-api.spec.js
  27. 38
      spec/api/pegjs-api.spec.js
  28. 20
      spec/api/plugin-api.spec.js
  29. 248
      spec/behavior/generated-parser-behavior.spec.js
  30. 6
      spec/server
  31. 40
      spec/unit/compiler/passes/generate-bytecode.spec.js
  32. 8
      spec/unit/compiler/passes/helpers.js
  33. 4
      spec/unit/compiler/passes/remove-proxy-rules.spec.js
  34. 4
      spec/unit/compiler/passes/report-duplicate-labels.spec.js
  35. 4
      spec/unit/compiler/passes/report-duplicate-rules.spec.js
  36. 4
      spec/unit/compiler/passes/report-infinite-recursion.spec.js
  37. 4
      spec/unit/compiler/passes/report-infinite-repetition.spec.js
  38. 4
      spec/unit/compiler/passes/report-undefined-rules.spec.js
  39. 14
      spec/unit/parser.spec.js
  40. 6
      src/parser.pegjs

2
benchmark/benchmarks.js

@ -1,6 +1,6 @@
"use strict";
var benchmarks = [
let benchmarks = [
{
id: "json",
title: "JSON",

10
benchmark/index.js

@ -1,6 +1,6 @@
/* eslint-env browser, jquery */
var benchmarks = require("./benchmarks.js"),
let benchmarks = require("./benchmarks.js"),
Runner = require("./runner.js");
$("#run").click(function() {
@ -8,7 +8,7 @@ $("#run").click(function() {
/* Results Table Manipulation */
var resultsTable = $("#results-table");
let resultsTable = $("#results-table");
function appendHeading(heading) {
resultsTable.append(
@ -17,8 +17,8 @@ $("#run").click(function() {
}
function appendResult(klass, title, url, inputSize, parseTime) {
var KB = 1024,
MS_IN_S = 1000;
const KB = 1024,
MS_IN_S = 1000;
resultsTable.append(
"<tr class='" + klass + "'>"
@ -62,7 +62,7 @@ $("#run").click(function() {
* 2. To minimize random errors.
*/
var runCount = parseInt($("#run-count").val(), 10),
let runCount = parseInt($("#run-count").val(), 10),
options = {
cache: $("#cache").is(":checked"),
optimize: $("#optimize").val()

22
benchmark/run

@ -5,16 +5,16 @@
"use strict";
var fs = require("fs");
let fs = require("fs");
var benchmarks = require("./benchmarks.js");
var Runner = require("./runner.js");
let benchmarks = require("./benchmarks.js");
let Runner = require("./runner.js");
/* Results Table Manipulation */
function dup(text, count) {
var result = "";
for (var i = 1; i <= count; i++) {
let result = "";
for (let i = 1; i <= count; i++) {
result += text;
}
return result;
@ -29,7 +29,7 @@ function padRight(text, length) {
}
function center(text, length) {
var padLength = (length - text.length) / 2;
let padLength = (length - text.length) / 2;
return dup(" ", Math.floor(padLength))
+ text
+ dup(" ", Math.ceil(padLength));
@ -47,8 +47,8 @@ function writeHeading(heading) {
}
function writeResult(title, inputSize, parseTime) {
var KB = 1024;
var MS_IN_S = 1000;
const KB = 1024;
const MS_IN_S = 1000;
console.log("│ "
+ padRight(title, 35)
@ -99,7 +99,7 @@ function abort(message) {
/* Arguments */
var args = process.argv.slice(2); // Trim "node" and the script path.
let args = process.argv.slice(2); // Trim "node" and the script path.
function isOption(arg) {
return (/^-/).test(arg);
@ -111,8 +111,8 @@ function nextArg() {
/* Main */
var runCount = 10;
var options = {
let runCount = 10;
let options = {
cache: false,
optimize: "speed"
};

10
benchmark/runner.js

@ -2,14 +2,14 @@
"use strict";
var peg = require("../lib/peg");
let peg = require("../lib/peg");
var Runner = {
let Runner = {
run: function(benchmarks, runCount, options, callbacks) {
/* Queue */
var Q = {
let Q = {
functions: [],
add: function(f) {
@ -44,7 +44,7 @@ var Runner = {
* of the |state| object.
*/
var state = {};
let state = {};
function initialize() {
callbacks.start();
@ -68,7 +68,7 @@ var Runner = {
function testRunner(benchmark, test) {
return function() {
var input, parseTime, averageParseTime, i, t;
let input, parseTime, averageParseTime, i, t;
callbacks.testStart(benchmark, test);

6
benchmark/server

@ -9,20 +9,20 @@
* served to the browser.
*/
var express = require("express"),
let express = require("express"),
logger = require("morgan"),
glob = require("glob"),
browserify = require("browserify"),
babelify = require("babelify");
var app = express();
let app = express();
app.use(logger("dev"));
app.use(express.static(__dirname));
app.use("/examples", express.static(__dirname + "/../examples"));
app.get("/bundle.js", function(req, res) {
var files = glob.sync(__dirname + "/**/*.js", {
let files = glob.sync(__dirname + "/**/*.js", {
ignore: __dirname + "/vendor/**/*"
});

36
bin/pegjs

@ -2,9 +2,9 @@
"use strict";
var fs = require("fs");
var path = require("path");
var peg = require("../lib/peg");
let fs = require("fs");
let path = require("path");
let peg = require("../lib/peg");
/* Helpers */
@ -56,7 +56,7 @@ function abort(message) {
}
function addExtraOptions(options, json) {
var extraOptions;
let extraOptions;
try {
extraOptions = JSON.parse(json);
@ -69,7 +69,7 @@ function addExtraOptions(options, json) {
abort("The JSON with extra options has to represent an object.");
}
for (var key in extraOptions) {
for (let key in extraOptions) {
if (extraOptions.hasOwnProperty(key)) {
options[key] = extraOptions[key];
}
@ -86,7 +86,7 @@ function trim(s) {
/* Arguments */
var args = process.argv.slice(2); // Trim "node" and the script path.
let args = process.argv.slice(2); // Trim "node" and the script path.
function isOption(arg) {
return (/^-.+/).test(arg);
@ -99,17 +99,17 @@ function nextArg() {
/* Files */
function readStream(inputStream, callback) {
var input = "";
let input = "";
inputStream.on("data", function(data) { input += data; });
inputStream.on("end", function() { callback(input); });
}
/* Main */
var inputFile = null;
var outputFile = null;
let inputFile = null;
let outputFile = null;
var options = {
let options = {
cache: false,
dependencies: {},
exportVar: null,
@ -121,6 +121,8 @@ var options = {
};
while (args.length > 0 && isOption(args[0])) {
let json, id, mod;
switch (args[0]) {
case "--allowed-start-rules":
nextArg();
@ -143,7 +145,7 @@ while (args.length > 0 && isOption(args[0])) {
abort("Missing parameter of the -d/--dependency option.");
}
if (args[0].indexOf(":") !== -1) {
var parts = args[0].split(":");
let parts = args[0].split(":");
options.dependencies[parts[0]] = parts[1];
} else {
options.dependencies[args[0]] = args[0];
@ -173,7 +175,7 @@ while (args.length > 0 && isOption(args[0])) {
abort("Missing parameter of the --extra-options-file option.");
}
try {
var json = fs.readFileSync(args[0]);
json = fs.readFileSync(args[0]);
} catch(e) {
abort("Can't read from file \"" + args[0] + "\".");
}
@ -223,8 +225,8 @@ while (args.length > 0 && isOption(args[0])) {
if (args.length === 0) {
abort("Missing parameter of the --plugin option.");
}
var id = /^(\.\/|\.\.\/)/.test(args[0]) ? path.resolve(args[0]) : args[0];
var mod;
id = /^(\.\/|\.\.\/)/.test(args[0]) ? path.resolve(args[0]) : args[0];
mod;
try {
mod = require(id);
} catch (e) {
@ -267,8 +269,8 @@ if (options.exportVar !== null) {
}
}
var inputStream;
var outputStream;
let inputStream;
let outputStream;
switch (args.length) {
case 0:
@ -311,7 +313,7 @@ if (outputFile === "-") {
}
readStream(inputStream, function(input) {
var source;
let source;
try {
source = peg.generate(input, options);

6
lib/compiler/asts.js

@ -1,10 +1,10 @@
"use strict";
var arrays = require("../utils/arrays"),
let arrays = require("../utils/arrays"),
visitor = require("./visitor");
/* AST utilities. */
var asts = {
let asts = {
findRule: function(ast, name) {
return arrays.find(ast.rules, function(r) { return r.name === name; });
},
@ -21,7 +21,7 @@ var asts = {
return consumes(node.expression);
}
var consumes = visitor.build({
let consumes = visitor.build({
rule: consumesExpression,
named: consumesExpression,

6
lib/compiler/index.js

@ -1,8 +1,8 @@
"use strict";
var objects = require("../utils/objects");
let objects = require("../utils/objects");
var compiler = {
let compiler = {
/*
* AST node visitor builder. Useful mainly for plugins which manipulate the
* AST.
@ -42,7 +42,7 @@ var compiler = {
compile: function(ast, passes, options) {
options = options !== undefined ? options : {};
var stage;
let stage;
options = objects.clone(options);
objects.defaults(options, {

2
lib/compiler/js.js

@ -3,7 +3,7 @@
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
/* JavaScript code generation helpers. */
var js = {
let js = {
stringEscape: function(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string

2
lib/compiler/opcodes.js

@ -1,7 +1,7 @@
"use strict";
/* Bytecode instruction opcodes. */
var opcodes = {
let opcodes = {
/* Stack Manipulation */
PUSH: 0, // PUSH c

30
lib/compiler/passes/generate-bytecode.js

@ -1,6 +1,6 @@
"use strict";
var arrays = require("../../utils/arrays"),
let arrays = require("../../utils/arrays"),
objects = require("../../utils/objects"),
asts = require("../asts"),
visitor = require("../visitor"),
@ -191,10 +191,10 @@ var arrays = require("../../utils/arrays"),
* silentFails--;
*/
function generateBytecode(ast) {
var consts = [];
let consts = [];
function addConst(value) {
var index = arrays.indexOf(consts, value);
let index = arrays.indexOf(consts, value);
return index === -1 ? consts.push(value) - 1 : index;
}
@ -222,7 +222,7 @@ function generateBytecode(ast) {
}
function buildCall(functionIndex, delta, env, sp) {
var params = objects.values(env).map(function(p) { return sp - p; });
let params = objects.values(env).map(function(p) { return sp - p; });
return [op.CALL, functionIndex, delta, params.length].concat(params);
}
@ -254,7 +254,7 @@ function generateBytecode(ast) {
}
function buildSemanticPredicate(code, negative, context) {
var functionIndex = addFunctionConst(Object.keys(context.env), code);
let functionIndex = addFunctionConst(Object.keys(context.env), code);
return buildSequence(
[op.UPDATE_SAVED_POS],
@ -280,7 +280,7 @@ function generateBytecode(ast) {
);
}
var generate = visitor.build({
let generate = visitor.build({
grammar: function(node) {
node.rules.forEach(generate);
@ -296,7 +296,7 @@ function generateBytecode(ast) {
},
named: function(node, context) {
var nameIndex = addConst(
let nameIndex = addConst(
'peg$otherExpectation("' + js.stringEscape(node.name) + '")'
);
@ -339,7 +339,7 @@ function generateBytecode(ast) {
},
action: function(node, context) {
var env = objects.clone(context.env),
let env = objects.clone(context.env),
emitCall = node.expression.type !== "sequence"
|| node.expression.elements.length === 0,
expressionCode = generate(node.expression, {
@ -368,7 +368,7 @@ function generateBytecode(ast) {
sequence: function(node, context) {
function buildElementsCode(elements, context) {
var processedCount, functionIndex;
let processedCount, functionIndex;
if (elements.length > 0) {
processedCount = node.elements.length - elements.slice(1).length;
@ -427,7 +427,7 @@ function generateBytecode(ast) {
},
labeled: function(node, context) {
var env = objects.clone(context.env);
let env = objects.clone(context.env);
context.env[node.label] = context.sp + 1;
@ -478,7 +478,7 @@ function generateBytecode(ast) {
},
zero_or_more: function(node, context) {
var expressionCode = generate(node.expression, {
let expressionCode = generate(node.expression, {
sp: context.sp + 1,
env: objects.clone(context.env),
action: null
@ -493,7 +493,7 @@ function generateBytecode(ast) {
},
one_or_more: function(node, context) {
var expressionCode = generate(node.expression, {
let expressionCode = generate(node.expression, {
sp: context.sp + 1,
env: objects.clone(context.env),
action: null
@ -531,7 +531,7 @@ function generateBytecode(ast) {
},
literal: function(node) {
var stringIndex, expectedIndex;
let stringIndex, expectedIndex;
if (node.value.length > 0) {
stringIndex = addConst('"'
@ -569,7 +569,7 @@ function generateBytecode(ast) {
},
"class": function(node) {
var regexp = '/^['
let regexp = '/^['
+ (node.inverted ? '^' : '')
+ node.parts.map(function(part) {
return Array.isArray(part)
@ -603,7 +603,7 @@ function generateBytecode(ast) {
},
any: function() {
var expectedIndex = addConst('peg$anyExpectation()');
let expectedIndex = addConst('peg$anyExpectation()');
return buildCondition(
[op.MATCH_ANY],

42
lib/compiler/passes/generate-js.js

@ -1,6 +1,6 @@
"use strict";
var arrays = require("../../utils/arrays"),
let arrays = require("../../utils/arrays"),
objects = require("../../utils/objects"),
asts = require("../asts"),
op = require("../opcodes"),
@ -38,7 +38,7 @@ function generateJS(ast, options) {
}
function generateRuleHeader(ruleNameCode, ruleIndexCode) {
var parts = [];
let parts = [];
parts.push('');
@ -94,7 +94,7 @@ function generateJS(ast, options) {
}
function generateRuleFooter(ruleNameCode, resultCode) {
var parts = [];
let parts = [];
if (options.cache) {
parts.push([
@ -132,10 +132,10 @@ function generateJS(ast, options) {
}
function generateInterpreter() {
var parts = [];
let parts = [];
function generateCondition(cond, argsLength) {
var baseLength = argsLength + 3,
let baseLength = argsLength + 3,
thenLengthCode = 'bc[ip + ' + (baseLength - 2) + ']',
elseLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
@ -156,7 +156,7 @@ function generateJS(ast, options) {
}
function generateLoop(cond) {
var baseLength = 2,
let baseLength = 2,
bodyLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
return [
@ -175,7 +175,7 @@ function generateJS(ast, options) {
}
function generateCall() {
var baseLength = 4,
let baseLength = 4,
paramsLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
return [
@ -410,17 +410,17 @@ function generateJS(ast, options) {
}
function generateRuleFunction(rule) {
var parts = [], code;
let parts = [], code;
function c(i) { return "peg$c" + i; } // |consts[i]| of the abstract machine
function s(i) { return "s" + i; } // |stack[i]| of the abstract machine
var stack = {
let stack = {
sp: -1,
maxSp: -1,
push: function(exprCode) {
var code = s(++this.sp) + ' = ' + exprCode + ';';
let code = s(++this.sp) + ' = ' + exprCode + ';';
if (this.sp > this.maxSp) { this.maxSp = this.sp; }
@ -428,7 +428,7 @@ function generateJS(ast, options) {
},
pop: function(n) {
var values;
let values;
if (n === undefined) {
return s(this.sp--);
@ -450,13 +450,13 @@ function generateJS(ast, options) {
};
function compile(bc) {
var ip = 0,
let ip = 0,
end = bc.length,
parts = [],
value;
function compileCondition(cond, argCount) {
var baseLength = argCount + 3,
let baseLength = argCount + 3,
thenLength = bc[ip + baseLength - 2],
elseLength = bc[ip + baseLength - 1],
baseSp = stack.sp,
@ -490,7 +490,7 @@ function generateJS(ast, options) {
}
function compileLoop(cond) {
var baseLength = 2,
let baseLength = 2,
bodyLength = bc[ip + baseLength - 1],
baseSp = stack.sp,
bodyCode, bodySp;
@ -510,10 +510,10 @@ function generateJS(ast, options) {
}
function compileCall() {
var baseLength = 4,
let baseLength = 4,
paramsLength = bc[ip + baseLength - 1];
var value = c(bc[ip + 1]) + '('
let value = c(bc[ip + 1]) + '('
+ bc.slice(ip + baseLength, ip + baseLength + paramsLength).map(
function(p) { return stack.index(p); }
).join(', ')
@ -745,7 +745,7 @@ function generateJS(ast, options) {
}
function generateToplevel() {
var parts = [],
let parts = [],
startRuleIndices, startRuleIndex,
startRuleFunctions, startRuleFunction,
ruleNames;
@ -1229,7 +1229,7 @@ function generateJS(ast, options) {
].join('\n');
}
var generators = {
let generators = {
bare: function() {
return [
generateGeneratedByComment(),
@ -1244,7 +1244,7 @@ function generateJS(ast, options) {
},
commonjs: function() {
var parts = [],
let parts = [],
dependencyVars = Object.keys(options.dependencies),
requires = dependencyVars.map(
function(variable) {
@ -1278,7 +1278,7 @@ function generateJS(ast, options) {
},
amd: function() {
var dependencyIds = objects.values(options.dependencies),
let dependencyIds = objects.values(options.dependencies),
dependencyVars = Object.keys(options.dependencies),
dependencies = '['
+ dependencyIds.map(
@ -1315,7 +1315,7 @@ function generateJS(ast, options) {
},
umd: function() {
var parts = [],
let parts = [],
dependencyIds = objects.values(options.dependencies),
dependencyVars = Object.keys(options.dependencies),
dependencies = '['

6
lib/compiler/passes/remove-proxy-rules.js

@ -1,6 +1,6 @@
"use strict";
var arrays = require("../../utils/arrays"),
let arrays = require("../../utils/arrays"),
visitor = require("../visitor");
/*
@ -12,7 +12,7 @@ function removeProxyRules(ast, options) {
}
function replaceRuleRefs(ast, from, to) {
var replace = visitor.build({
let replace = visitor.build({
rule_ref: function(node) {
if (node.name === from) {
node.name = to;
@ -23,7 +23,7 @@ function removeProxyRules(ast, options) {
replace(ast);
}
var indices = [];
let indices = [];
ast.rules.forEach(function(rule, i) {
if (isProxyRule(rule)) {

4
lib/compiler/passes/report-duplicate-labels.js

@ -1,6 +1,6 @@
"use strict";
var GrammarError = require("../../grammar-error"),
let GrammarError = require("../../grammar-error"),
objects = require("../../utils/objects"),
visitor = require("../visitor");
@ -10,7 +10,7 @@ function reportDuplicateLabels(ast) {
check(node.expression, objects.clone(env));
}
var check = visitor.build({
let check = visitor.build({
rule: function(node) {
check(node.expression, { });
},

6
lib/compiler/passes/report-duplicate-rules.js

@ -1,13 +1,13 @@
"use strict";
var GrammarError = require("../../grammar-error"),
let GrammarError = require("../../grammar-error"),
visitor = require("../visitor");
/* Checks that each rule is defined only once. */
function reportDuplicateRules(ast) {
var rules = {};
let rules = {};
var check = visitor.build({
let check = visitor.build({
rule: function(node) {
if (rules.hasOwnProperty(node.name)) {
throw new GrammarError(

6
lib/compiler/passes/report-infinite-recursion.js

@ -1,6 +1,6 @@
"use strict";
var arrays = require("../../utils/arrays"),
let arrays = require("../../utils/arrays"),
GrammarError = require("../../grammar-error"),
asts = require("../asts"),
visitor = require("../visitor");
@ -18,9 +18,9 @@ var arrays = require("../../utils/arrays"),
* it can lead to left recursion.
*/
function reportInfiniteRecursion(ast) {
var visitedRules = [];
let visitedRules = [];
var check = visitor.build({
let check = visitor.build({
rule: function(node) {
visitedRules.push(node.name);
check(node.expression);

4
lib/compiler/passes/report-infinite-repetition.js

@ -1,6 +1,6 @@
"use strict";
var GrammarError = require("../../grammar-error"),
let GrammarError = require("../../grammar-error"),
asts = require("../asts"),
visitor = require("../visitor");
@ -9,7 +9,7 @@ var GrammarError = require("../../grammar-error"),
* grammar, which prevents infinite loops in the generated parser.
*/
function reportInfiniteRepetition(ast) {
var check = visitor.build({
let check = visitor.build({
zero_or_more: function(node) {
if (!asts.alwaysConsumesOnSuccess(ast, node.expression)) {
throw new GrammarError(

4
lib/compiler/passes/report-undefined-rules.js

@ -1,12 +1,12 @@
"use strict";
var GrammarError = require("../../grammar-error"),
let GrammarError = require("../../grammar-error"),
asts = require("../asts"),
visitor = require("../visitor");
/* Checks that all referenced rules exist. */
function reportUndefinedRules(ast) {
var check = visitor.build({
let check = visitor.build({
rule_ref: function(node) {
if (!asts.findRule(ast, node.name)) {
throw new GrammarError(

12
lib/compiler/visitor.js

@ -1,9 +1,9 @@
"use strict";
var objects = require("../utils/objects");
let objects = require("../utils/objects");
/* Simple AST node visitor builder. */
var visitor = {
let visitor = {
build: function(functions) {
function visit(node) {
return functions[node.type].apply(null, arguments);
@ -12,14 +12,14 @@ var visitor = {
function visitNop() { }
function visitExpression(node) {
var extraArgs = Array.prototype.slice.call(arguments, 1);
let extraArgs = Array.prototype.slice.call(arguments, 1);
visit.apply(null, [node.expression].concat(extraArgs));
}
function visitChildren(property) {
return function(node) {
var extraArgs = Array.prototype.slice.call(arguments, 1);
let extraArgs = Array.prototype.slice.call(arguments, 1);
node[property].forEach(function(child) {
visit.apply(null, [child].concat(extraArgs));
@ -27,9 +27,9 @@ var visitor = {
};
}
var DEFAULT_FUNCTIONS = {
const DEFAULT_FUNCTIONS = {
grammar: function(node) {
var extraArgs = Array.prototype.slice.call(arguments, 1);
let extraArgs = Array.prototype.slice.call(arguments, 1);
if (node.initializer) {
visit.apply(null, [node.initializer].concat(extraArgs));

2
lib/grammar-error.js

@ -1,6 +1,6 @@
"use strict";
var classes = require("./utils/classes");
let classes = require("./utils/classes");
/* Thrown when the grammar contains an error. */
function GrammarError(message, location) {

6
lib/parser.js

@ -4960,19 +4960,19 @@ function peg$parse(input, options) {
}
var OPS_TO_PREFIXED_TYPES = {
const OPS_TO_PREFIXED_TYPES = {
"$": "text",
"&": "simple_and",
"!": "simple_not"
};
var OPS_TO_SUFFIXED_TYPES = {
const OPS_TO_SUFFIXED_TYPES = {
"?": "optional",
"*": "zero_or_more",
"+": "one_or_more"
};
var OPS_TO_SEMANTIC_PREDICATE_TYPES = {
const OPS_TO_SEMANTIC_PREDICATE_TYPES = {
"&": "semantic_and",
"!": "semantic_not"
};

8
lib/peg.js

@ -1,8 +1,8 @@
"use strict";
var objects = require("./utils/objects");
let objects = require("./utils/objects");
var peg = {
let peg = {
/* PEG.js version (uses semantic versioning). */
VERSION: "0.10.0",
@ -25,7 +25,7 @@ var peg = {
options = options !== undefined ? options : {};
function convertPasses(passes) {
var converted = {}, stage;
let converted = {}, stage;
for (stage in passes) {
if (passes.hasOwnProperty(stage)) {
@ -38,7 +38,7 @@ var peg = {
options = objects.clone(options);
var plugins = "plugins" in options ? options.plugins : [],
let plugins = "plugins" in options ? options.plugins : [],
config = {
parser: peg.parser,
passes: convertPasses(peg.compiler.passes)

8
lib/utils/arrays.js

@ -1,9 +1,9 @@
"use strict";
/* Array utilities. */
var arrays = {
let arrays = {
range: function(start, stop) {
var length = stop - start,
let length = stop - start,
result = new Array(length),
i, j;
@ -15,7 +15,7 @@ var arrays = {
},
find: function(array, valueOrPredicate) {
var length = array.length, i;
let length = array.length, i;
if (typeof valueOrPredicate === "function") {
for (i = 0; i < length; i++) {
@ -33,7 +33,7 @@ var arrays = {
},
indexOf: function(array, valueOrPredicate) {
var length = array.length, i;
let length = array.length, i;
if (typeof valueOrPredicate === "function") {
for (i = 0; i < length; i++) {

2
lib/utils/classes.js

@ -1,7 +1,7 @@
"use strict";
/* Class utilities */
var classes = {
let classes = {
subclass: function(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;

8
lib/utils/objects.js

@ -1,9 +1,9 @@
"use strict";
/* Object utilities. */
var objects = {
let objects = {
values: function(object) {
var result = [], key;
let result = [], key;
for (key in object) {
if (object.hasOwnProperty(key)) {
@ -15,7 +15,7 @@ var objects = {
},
clone: function(object) {
var result = {}, key;
let result = {}, key;
for (key in object) {
if (object.hasOwnProperty(key)) {
@ -27,7 +27,7 @@ var objects = {
},
defaults: function(object, defaults) {
var key;
let key;
for (key in defaults) {
if (defaults.hasOwnProperty(key)) {

14
spec/api/generated-parser-api.spec.js

@ -3,24 +3,24 @@
"use strict";
var peg = require("../../lib/peg");
let peg = require("../../lib/peg");
describe("generated parser API", function() {
describe("parse", function() {
it("parses input", function() {
var parser = peg.generate('start = "a"');
let parser = peg.generate('start = "a"');
expect(parser.parse("a")).toBe("a");
});
it("throws an exception on syntax error", function() {
var parser = peg.generate('start = "a"');
let parser = peg.generate('start = "a"');
expect(function() { parser.parse("b"); }).toThrow();
});
describe("start rule", function() {
var parser = peg.generate([
let parser = peg.generate([
'a = "x" { return "a"; }',
'b = "x" { return "b"; }',
'c = "x" { return "c"; }'
@ -49,7 +49,7 @@ describe("generated parser API", function() {
});
describe("tracing", function() {
var parser = peg.generate([
let parser = peg.generate([
'start = a / b',
'a = "a"',
'b = "b"'
@ -77,7 +77,7 @@ describe("generated parser API", function() {
describe("custom tracers", function() {
describe("trace", function() {
it("receives tracing events", function() {
var tracer = jasmine.createSpyObj("tracer", ["trace"]);
let tracer = jasmine.createSpyObj("tracer", ["trace"]);
parser.parse("b", { tracer: tracer });
@ -137,7 +137,7 @@ describe("generated parser API", function() {
});
it("accepts custom options", function() {
var parser = peg.generate('start = "a"');
let parser = peg.generate('start = "a"');
parser.parse("a", { foo: 42 });
});

38
spec/api/pegjs-api.spec.js

@ -1,11 +1,11 @@
"use strict";
var peg = require("../../lib/peg");
let peg = require("../../lib/peg");
describe("PEG.js API", function() {
describe("generate", function() {
it("generates a parser", function() {
var parser = peg.generate('start = "a"');
let parser = peg.generate('start = "a"');
expect(typeof parser).toBe("object");
expect(parser.parse("a")).toBe("a");
@ -20,7 +20,7 @@ describe("PEG.js API", function() {
});
describe("allowed start rules", function() {
var grammar = [
let grammar = [
'a = "x"',
'b = "x"',
'c = "x"'
@ -34,7 +34,7 @@ describe("PEG.js API", function() {
describe("when optimizing for parsing speed", function() {
describe("when |allowedStartRules| is not set", function() {
it("generated parser can start only from the first rule", function() {
var parser = peg.generate(grammar, { optimize: "speed" });
let parser = peg.generate(grammar, { optimize: "speed" });
expect(parser.parse("x", { startRule: "a" })).toBe("x");
expect(
@ -48,7 +48,7 @@ describe("PEG.js API", function() {
describe("when |allowedStartRules| is set", function() {
it("generated parser can start only from specified rules", function() {
var parser = peg.generate(grammar, {
let parser = peg.generate(grammar, {
optimize: "speed",
allowedStartRules: ["b", "c"]
});
@ -65,7 +65,7 @@ describe("PEG.js API", function() {
describe("when optimizing for code size", function() {
describe("when |allowedStartRules| is not set", function() {
it("generated parser can start only from the first rule", function() {
var parser = peg.generate(grammar, { optimize: "size" });
let parser = peg.generate(grammar, { optimize: "size" });
expect(parser.parse("x", { startRule: "a" })).toBe("x");
expect(
@ -79,7 +79,7 @@ describe("PEG.js API", function() {
describe("when |allowedStartRules| is set", function() {
it("generated parser can start only from specified rules", function() {
var parser = peg.generate(grammar, {
let parser = peg.generate(grammar, {
optimize: "size",
allowedStartRules: ["b", "c"]
});
@ -95,7 +95,7 @@ describe("PEG.js API", function() {
});
describe("intermediate results caching", function() {
var grammar = [
let grammar = [
'{ var n = 0; }',
'start = (a "b") / (a "c") { return n; }',
'a = "a" { n++; }'
@ -103,7 +103,7 @@ describe("PEG.js API", function() {
describe("when |cache| is not set", function() {
it("generated parser doesn't cache intermediate parse results", function() {
var parser = peg.generate(grammar);
let parser = peg.generate(grammar);
expect(parser.parse("ac")).toBe(2);
});
@ -111,7 +111,7 @@ describe("PEG.js API", function() {
describe("when |cache| is set to |false|", function() {
it("generated parser doesn't cache intermediate parse results", function() {
var parser = peg.generate(grammar, { cache: false });
let parser = peg.generate(grammar, { cache: false });
expect(parser.parse("ac")).toBe(2);
});
@ -119,7 +119,7 @@ describe("PEG.js API", function() {
describe("when |cache| is set to |true|", function() {
it("generated parser caches intermediate parse results", function() {
var parser = peg.generate(grammar, { cache: true });
let parser = peg.generate(grammar, { cache: true });
expect(parser.parse("ac")).toBe(1);
});
@ -127,11 +127,11 @@ describe("PEG.js API", function() {
});
describe("tracing", function() {
var grammar = 'start = "a"';
let grammar = 'start = "a"';
describe("when |trace| is not set", function() {
it("generated parser doesn't trace", function() {
var parser = peg.generate(grammar),
let parser = peg.generate(grammar),
tracer = jasmine.createSpyObj("tracer", ["trace"]);
parser.parse("a", { tracer: tracer });
@ -142,7 +142,7 @@ describe("PEG.js API", function() {
describe("when |trace| is set to |false|", function() {
it("generated parser doesn't trace", function() {
var parser = peg.generate(grammar, { trace: false }),
let parser = peg.generate(grammar, { trace: false }),
tracer = jasmine.createSpyObj("tracer", ["trace"]);
parser.parse("a", { tracer: tracer });
@ -153,7 +153,7 @@ describe("PEG.js API", function() {
describe("when |trace| is set to |true|", function() {
it("generated parser traces", function() {
var parser = peg.generate(grammar, { trace: true }),
let parser = peg.generate(grammar, { trace: true }),
tracer = jasmine.createSpyObj("tracer", ["trace"]);
parser.parse("a", { tracer: tracer });
@ -169,11 +169,11 @@ describe("PEG.js API", function() {
*/
describe("output", function() {
var grammar = 'start = "a"';
let grammar = 'start = "a"';
describe("when |output| is not set", function() {
it("returns generated parser object", function() {
var parser = peg.generate(grammar);
let parser = peg.generate(grammar);
expect(typeof parser).toBe("object");
expect(parser.parse("a")).toBe("a");
@ -182,7 +182,7 @@ describe("PEG.js API", function() {
describe("when |output| is set to |\"parser\"|", function() {
it("returns generated parser object", function() {
var parser = peg.generate(grammar, { output: "parser" });
let parser = peg.generate(grammar, { output: "parser" });
expect(typeof parser).toBe("object");
expect(parser.parse("a")).toBe("a");
@ -191,7 +191,7 @@ describe("PEG.js API", function() {
describe("when |output| is set to |\"source\"|", function() {
it("returns generated parser source code", function() {
var source = peg.generate(grammar, { output: "source" });
let source = peg.generate(grammar, { output: "source" });
expect(typeof source).toBe("string");
expect(eval(source).parse("a")).toBe("a");

20
spec/api/plugin-api.spec.js

@ -1,6 +1,6 @@
"use strict";
var peg = require("../../lib/peg");
let peg = require("../../lib/peg");
describe("plugin API", function() {
beforeEach(function() {
@ -38,10 +38,10 @@ describe("plugin API", function() {
});
describe("use", function() {
var grammar = 'start = "a"';
let grammar = 'start = "a"';
it("is called for each plugin", function() {
var pluginsUsed = [false, false, false],
let pluginsUsed = [false, false, false],
plugins = [
{ use: function() { pluginsUsed[0] = true; } },
{ use: function() { pluginsUsed[1] = true; } },
@ -54,7 +54,7 @@ describe("plugin API", function() {
});
it("receives configuration", function() {
var plugin = {
let plugin = {
use: function(config) {
expect(config).toBeObject();
@ -84,7 +84,7 @@ describe("plugin API", function() {
});
it("receives options", function() {
var plugin = {
let plugin = {
use: function(config, options) {
expect(options).toEqual(generateOptions);
}
@ -95,9 +95,9 @@ describe("plugin API", function() {
});
it("can replace parser", function() {
var plugin = {
let plugin = {
use: function(config) {
var parser = peg.generate([
let parser = peg.generate([
'start = .* {',
' return {',
' type: "grammar",',
@ -121,9 +121,9 @@ describe("plugin API", function() {
});
it("can change compiler passes", function() {
var plugin = {
let plugin = {
use: function(config) {
var pass = function(ast) {
let pass = function(ast) {
ast.code = '({ parse: function() { return 42; } })';
};
@ -136,7 +136,7 @@ describe("plugin API", function() {
});
it("can change options", function() {
var grammar = [
let grammar = [
'a = "x"',
'b = "x"',
'c = "x"'

248
spec/behavior/generated-parser-behavior.spec.js

@ -3,12 +3,12 @@
"use strict";
var peg = require("../../lib/peg");
let peg = require("../../lib/peg");
describe("generated parser behavior", function() {
function varyOptimizationOptions(block) {
function clone(object) {
var result = {}, key;
let result = {}, key;
for (key in object) {
if (object.hasOwnProperty(key)) {
@ -19,7 +19,7 @@ describe("generated parser behavior", function() {
return result;
}
var optionsVariants = [
let optionsVariants = [
{ cache: false, optimize: "speed", trace: false },
{ cache: false, optimize: "speed", trace: true },
{ cache: false, optimize: "size", trace: false },
@ -43,7 +43,7 @@ describe("generated parser behavior", function() {
toParse: function(input, expected, options) {
options = options !== undefined ? options : {};
var result;
let result;
try {
result = this.actual.parse(input, options);
@ -77,7 +77,7 @@ describe("generated parser behavior", function() {</