Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use template strings for generated code #599

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 106 additions & 96 deletions lib/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
root.generate = factory(root.nearley);
}
}(this, function(nearley) {
function generateComment(parser, beginning) {
var message = "Generated automatically by nearley, version"
var link = "http://github.com/Hardmath123/nearley"
return `${beginning} ${message} ${parser.version}\n${beginning} ${link}`
}

function serializeRules(rules, builtinPostprocessors, extraIndent) {
if (extraIndent == null) {
Expand All @@ -16,6 +21,19 @@
}).join(',\n ') + '\n' + extraIndent + ']';
}

function dedent(line, indent) {
if (line.slice(0, indent.length) === indent) {
return line.slice(indent.length);
}
return line;
}

function dedentMultiline(multiline, indent) {
return multiline.split("\n").map(function (line) {
return dedent(line, indent);
}).join("\n");
}

function dedentFunc(func) {
var lines = func.toString().split(/\n/);

Expand All @@ -39,11 +57,8 @@
return lines;
}

return lines.map(function dedent(line) {
if (line.slice(0, indent.length) === indent) {
return line.slice(indent.length);
}
return line;
return lines.map(function (line) {
return dedent(line, indent);
});
}

Expand Down Expand Up @@ -110,26 +125,23 @@
};

generate.js = generate._default = generate.javascript = function (parser, exportName) {
var output = "// Generated automatically by nearley, version " + parser.version + "\n";
output += "// http://github.com/Hardmath123/nearley\n";
output += "(function () {\n";
output += "function id(x) { return x[0]; }\n";
output += parser.body.join('\n');
output += "var grammar = {\n";
output += " Lexer: " + parser.config.lexer + ",\n";
output += " ParserRules: " +
serializeRules(parser.rules, generate.javascript.builtinPostprocessors)
+ "\n";
output += " , ParserStart: " + JSON.stringify(parser.start) + "\n";
output += "}\n";
output += "if (typeof module !== 'undefined'"
+ "&& typeof module.exports !== 'undefined') {\n";
output += " module.exports = grammar;\n";
output += "} else {\n";
output += " window." + exportName + " = grammar;\n";
output += "}\n";
output += "})();\n";
return output;
var output = `${generateComment(parser, "//")}
(function () {
function id(x) { return x[0]; }
${parser.body.join('\n')}var grammar = {
Lexer: ${parser.config.lexer},
ParserRules: ${serializeRules(parser.rules, generate.javascript.builtinPostprocessors)}
, ParserStart: ${JSON.stringify(parser.start)}
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = grammar;
} else {
window.${exportName} = grammar;
}
})();
`

return dedentMultiline(output, " ");
};

generate.javascript.builtinPostprocessors = {
Expand All @@ -141,39 +153,38 @@
}

generate.module = generate.esmodule = function (parser, exportName) {
var output = "// Generated automatically by nearley, version " + parser.version + "\n";
output += "// http://github.com/Hardmath123/nearley\n";
output += "function id(x) { return x[0]; }\n";
output += parser.body.join('\n');
output += "let Lexer = " + parser.config.lexer + ";\n";
output += "let ParserRules = " + serializeRules(parser.rules, generate.javascript.builtinPostprocessors) + ";\n";
output += "let ParserStart = " + JSON.stringify(parser.start) + ";\n";
output += "export default { Lexer, ParserRules, ParserStart };\n";
return output;
var output = `${generateComment(parser, "//")}
function id(x) { return x[0]; }
${parser.body.join('\n')}let Lexer = ${parser.config.lexer};
let ParserRules = ${serializeRules(parser.rules, generate.javascript.builtinPostprocessors)};
let ParserStart = ${JSON.stringify(parser.start)};
export default { Lexer, ParserRules, ParserStart };
`
return dedentMultiline(output, " ");
};

generate.cs = generate.coffee = generate.coffeescript = function (parser, exportName) {
var output = "# Generated automatically by nearley, version " + parser.version + "\n";
output += "# http://github.com/Hardmath123/nearley\n";
output += "do ->\n";
output += " id = (d) -> d[0]\n";
output += tabulateString(dedentFunc(parser.body.join('\n')), ' ') + '\n';
output += " grammar = {\n";
output += " Lexer: " + parser.config.lexer + ",\n";
output += " ParserRules: " +
var output = `${generateComment(parser, "#")}
do ->
id = (d) -> d[0]
${tabulateString(dedentFunc(parser.body.join('\n')), ' ')}
grammar = {
Lexer: ${parser.config.lexer},
ParserRules: ${
tabulateString(
serializeRules(parser.rules, generate.coffeescript.builtinPostprocessors),
' ',
" " + " ",
{indentFirst: false})
+ ",\n";
output += " ParserStart: " + JSON.stringify(parser.start) + "\n";
output += " }\n";
output += " if typeof module != 'undefined' "
+ "&& typeof module.exports != 'undefined'\n";
output += " module.exports = grammar;\n";
output += " else\n";
output += " window." + exportName + " = grammar;\n";
return output;
},
ParserStart: ${JSON.stringify(parser.start)}
}
if typeof module != 'undefined' && typeof module.exports != 'undefined'
module.exports = grammar;
else
window.${exportName} = grammar;
`;

return dedentMultiline(output, " ");
};

generate.coffeescript.builtinPostprocessors = {
Expand All @@ -185,50 +196,49 @@
};

generate.ts = generate.typescript = function (parser, exportName) {
var output = "// Generated automatically by nearley, version " + parser.version + "\n";
output += "// http://github.com/Hardmath123/nearley\n";
output += "// Bypasses TS6133. Allow declared but unused functions.\n";
output += "// @ts-ignore\n";
output += "function id(d: any[]): any { return d[0]; }\n";
output += parser.customTokens.map(function (token) { return "declare var " + token + ": any;\n" }).join("")
output += parser.body.join('\n');
output += "\n";
output += "interface NearleyToken {\n";
output += " value: any;\n";
output += " [key: string]: any;\n";
output += "};\n";
output += "\n";
output += "interface NearleyLexer {\n";
output += " reset: (chunk: string, info: any) => void;\n";
output += " next: () => NearleyToken | undefined;\n";
output += " save: () => any;\n";
output += " formatError: (token: never) => string;\n";
output += " has: (tokenType: string) => boolean;\n";
output += "};\n";
output += "\n";
output += "interface NearleyRule {\n";
output += " name: string;\n";
output += " symbols: NearleySymbol[];\n";
output += " postprocess?: (d: any[], loc?: number, reject?: {}) => any;\n";
output += "};\n";
output += "\n";
output += "type NearleySymbol = string | { literal: any } | { test: (token: any) => boolean };\n";
output += "\n";
output += "interface Grammar {\n";
output += " Lexer: NearleyLexer | undefined;\n";
output += " ParserRules: NearleyRule[];\n";
output += " ParserStart: string;\n";
output += "};\n";
output += "\n";
output += "const grammar: Grammar = {\n";
output += " Lexer: " + parser.config.lexer + ",\n";
output += " ParserRules: " + serializeRules(parser.rules, generate.typescript.builtinPostprocessors, " ") + ",\n";
output += " ParserStart: " + JSON.stringify(parser.start) + ",\n";
output += "};\n";
output += "\n";
output += "export default grammar;\n";

return output;
var output = `${generateComment(parser, "//")}
// Bypasses TS6133. Allow declared but unused functions.
// @ts-ignore
function id(d: any[]): any { return d[0]; }
${parser.customTokens.map(function (token) { return "declare var " + token + ": any;" }).join("\n")}
${parser.body.join('\n')}
interface NearleyToken {
value: any;
[key: string]: any;
};

interface NearleyLexer {
reset: (chunk: string, info: any) => void;
next: () => NearleyToken | undefined;
save: () => any;
formatError: (token: never) => string;
has: (tokenType: string) => boolean;
};

interface NearleyRule {
name: string;
symbols: NearleySymbol[];
postprocess?: (d: any[], loc?: number, reject?: {}) => any;
};

type NearleySymbol = string | { literal: any } | { test: (token: any) => boolean };

interface Grammar {
Lexer: NearleyLexer | undefined;
ParserRules: NearleyRule[];
ParserStart: string;
};

const grammar: Grammar = {
Lexer: ${parser.config.lexer},
ParserRules: ${serializeRules(parser.rules, generate.typescript.builtinPostprocessors, " ")},
ParserStart: ${JSON.stringify(parser.start)},
};

export default grammar;
`;

return dedentMultiline(output, " ");
};

generate.typescript.builtinPostprocessors = {
Expand Down