node/tools/eslint/lib/rules/no-control-regex.js
Michaël Zasso 2d441493a4 tools: update eslint to v1.10.3
PR-URL: https://github.com/nodejs/io.js/pull/2286
Reviewed-By: Roman Reiss <me@silverwind.io>
2016-01-13 23:15:39 +01:00

65 lines
1.6 KiB
JavaScript

/**
* @fileoverview Rule to forbid control charactes from regular expressions.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
/**
* Get the regex expression
* @param {ASTNode} node node to evaluate
* @returns {*} Regex if found else null
* @private
*/
function getRegExp(node) {
if (node.value instanceof RegExp) {
return node.value;
} else if (typeof node.value === "string") {
var parent = context.getAncestors().pop();
if ((parent.type === "NewExpression" || parent.type === "CallExpression") &&
parent.callee.type === "Identifier" && parent.callee.name === "RegExp") {
// there could be an invalid regular expression string
try {
return new RegExp(node.value);
} catch (ex) {
return null;
}
}
} else {
return null;
}
}
return {
"Literal": function(node) {
var computedValue,
regex = getRegExp(node);
if (regex) {
computedValue = regex.toString();
if (/[\x00-\x1f]/.test(computedValue)) {
context.report(node, "Unexpected control character in regular expression.");
}
}
}
};
};
module.exports.schema = [];