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

Fixed: prevent codegen'ing a function with an invalid name. #870

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions lib/codegen/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
"use strict";
module.exports = codegen;

var makeValidFunctionName = function() {
var memoized = {};

return function makeValidFunctionName(name) {
if ((name in memoized) && memoized[name]) {
return memoized[name];
}

try {
Function("return function " + name + "(){};");
memoized[name] = name;
} catch (err) {
if (/^[a-z]+$/i.test(name)) {
memoized[name] = makeValidFunctionName(name + "_");
} else {
memoized[name] = makeValidFunctionName(name.replace(/[^a-z]+/ig, '_'));
}
}
return memoized[name];
};
}();

/**
* Begins generating a function.
* @memberof util
Expand All @@ -16,6 +38,8 @@ function codegen(functionParams, functionName) {
functionParams = undefined;
}

functionName = makeValidFunctionName(functionName);

var body = [];

/**
Expand Down
20 changes: 19 additions & 1 deletion lib/codegen/tests/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var codegen = require("..");

// new require("benchmark").Suite().add("add", function() {
// new require("benchmark").Suite().add("add + delete", function() {

var add = codegen(["a", "b"], "add")
("// awesome comment")
Expand All @@ -10,4 +10,22 @@ var add = codegen(["a", "b"], "add")
if (add(1, 2) !== 3)
throw Error("failed");

var object = { a: 1, b: 2 };
var delete_ = codegen(["object", "property"], "delete3")
("delete object[property];")
();

delete_(object, 'a');

if ("a" in object)
throw Error("expected 'a' property to be deleted but was not");

if (!delete_.name.includes('delete'))
throw Error("expected function name to contain 'delete': " + delete_.name);

delete_(object, 'b');

if (JSON.stringify(object) !== '{}')
throw Error("unexpected JSON: " + JSON.stringify(object));

// }).on("cycle", function(event) { process.stdout.write(String(event.target) + "\n"); }).run();