_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q18000
|
canBecomeVariableDeclaration
|
train
|
function canBecomeVariableDeclaration(identifier) {
let node = identifier.parent;
while (PATTERN_TYPE.test(node.type)) {
node = node.parent;
}
return (
node.type === "VariableDeclarator" ||
(
node.type === "AssignmentExpression" &&
node.parent.type === "ExpressionStatement" &&
DECLARATION_HOST_TYPE.test(node.parent.parent.type)
)
);
}
|
javascript
|
{
"resource": ""
}
|
q18001
|
isOuterVariableInDestructing
|
train
|
function isOuterVariableInDestructing(name, initScope) {
if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) {
return true;
}
const variable = astUtils.getVariableByName(initScope, name);
if (variable !== null) {
return variable.defs.some(def => def.type === "Parameter");
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18002
|
hasMemberExpressionAssignment
|
train
|
function hasMemberExpressionAssignment(node) {
switch (node.type) {
case "ObjectPattern":
return node.properties.some(prop => {
if (prop) {
/*
* Spread elements have an argument property while
* others have a value property. Because different
* parsers use different node types for spread elements,
* we just check if there is an argument property.
*/
return hasMemberExpressionAssignment(prop.argument || prop.value);
}
return false;
});
case "ArrayPattern":
return node.elements.some(element => {
if (element) {
return hasMemberExpressionAssignment(element);
}
return false;
});
case "AssignmentPattern":
return hasMemberExpressionAssignment(node.left);
case "MemberExpression":
return true;
// no default
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18003
|
getIdentifierIfShouldBeConst
|
train
|
function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
if (variable.eslintUsed && variable.scope.type === "global") {
return null;
}
// Finds the unique WriteReference.
let writer = null;
let isReadBeforeInit = false;
const references = variable.references;
for (let i = 0; i < references.length; ++i) {
const reference = references[i];
if (reference.isWrite()) {
const isReassigned = (
writer !== null &&
writer.identifier !== reference.identifier
);
if (isReassigned) {
return null;
}
const destructuringHost = getDestructuringHost(reference);
if (destructuringHost !== null && destructuringHost.left !== void 0) {
const leftNode = destructuringHost.left;
let hasOuterVariables = false,
hasNonIdentifiers = false;
if (leftNode.type === "ObjectPattern") {
const properties = leftNode.properties;
hasOuterVariables = properties
.filter(prop => prop.value)
.map(prop => prop.value.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
} else if (leftNode.type === "ArrayPattern") {
const elements = leftNode.elements;
hasOuterVariables = elements
.map(element => element && element.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
}
if (hasOuterVariables || hasNonIdentifiers) {
return null;
}
}
writer = reference;
} else if (reference.isRead() && writer === null) {
if (ignoreReadBeforeAssign) {
return null;
}
isReadBeforeInit = true;
}
}
/*
* If the assignment is from a different scope, ignore it.
* If the assignment cannot change to a declaration, ignore it.
*/
const shouldBeConst = (
writer !== null &&
writer.from === variable.scope &&
canBecomeVariableDeclaration(writer.identifier)
);
if (!shouldBeConst) {
return null;
}
if (isReadBeforeInit) {
return variable.defs[0].name;
}
return writer.identifier;
}
|
javascript
|
{
"resource": ""
}
|
q18004
|
findUp
|
train
|
function findUp(node, type, shouldStop) {
if (!node || shouldStop(node)) {
return null;
}
if (node.type === type) {
return node;
}
return findUp(node.parent, type, shouldStop);
}
|
javascript
|
{
"resource": ""
}
|
q18005
|
checkGroup
|
train
|
function checkGroup(nodes) {
const nodesToReport = nodes.filter(Boolean);
if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) {
const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement"));
const isVarDecParentNull = varDeclParent === null;
if (!isVarDecParentNull && varDeclParent.declarations.length > 0) {
const firstDeclaration = varDeclParent.declarations[0];
if (firstDeclaration.init) {
const firstDecParent = firstDeclaration.init.parent;
/*
* First we check the declaration type and then depending on
* if the type is a "VariableDeclarator" or its an "ObjectPattern"
* we compare the name from the first identifier, if the names are different
* we assign the new name and reset the count of reportCount and nodeCount in
* order to check each block for the number of reported errors and base our fix
* based on comparing nodes.length and nodesToReport.length.
*/
if (firstDecParent.type === "VariableDeclarator") {
if (firstDecParent.id.name !== name) {
name = firstDecParent.id.name;
reportCount = 0;
}
if (firstDecParent.id.type === "ObjectPattern") {
if (firstDecParent.init.name !== name) {
name = firstDecParent.init.name;
reportCount = 0;
}
}
}
}
}
let shouldFix = varDeclParent &&
// Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
/*
* If options.destructuring is "all", then this warning will not occur unless
* every assignment in the destructuring should be const. In that case, it's safe
* to apply the fix.
*/
nodesToReport.length === nodes.length;
if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) {
if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) {
/*
* Add nodesToReport.length to a count, then comparing the count to the length
* of the declarations in the current block.
*/
reportCount += nodesToReport.length;
shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length);
}
}
nodesToReport.forEach(node => {
context.report({
node,
messageId: "useConst",
data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18006
|
isConstructor
|
train
|
function isConstructor(name) {
const match = CTOR_PREFIX_REGEX.exec(name);
// Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
if (!match) {
return false;
}
const firstChar = name.charAt(match.index);
return firstChar === firstChar.toUpperCase();
}
|
javascript
|
{
"resource": ""
}
|
q18007
|
makeFunctionShorthand
|
train
|
function makeFunctionShorthand(fixer, node) {
const firstKeyToken = node.computed
? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
: sourceCode.getFirstToken(node.key);
const lastKeyToken = node.computed
? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken)
: sourceCode.getLastToken(node.key);
const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
let keyPrefix = "";
if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
return null;
}
if (node.value.async) {
keyPrefix += "async ";
}
if (node.value.generator) {
keyPrefix += "*";
}
if (node.value.type === "FunctionExpression") {
const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
);
}
const arrowToken = sourceCode.getTokenBefore(node.value.body, { filter: token => token.value === "=>" });
const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken);
const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")";
const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]);
const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1])
);
}
|
javascript
|
{
"resource": ""
}
|
q18008
|
enterFunction
|
train
|
function enterFunction() {
lexicalScopeStack.unshift(new Set());
context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => {
variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
});
}
|
javascript
|
{
"resource": ""
}
|
q18009
|
isParseIntMethod
|
train
|
function isParseIntMethod(node) {
return (
node.type === "MemberExpression" &&
!node.computed &&
node.property.type === "Identifier" &&
node.property.name === "parseInt"
);
}
|
javascript
|
{
"resource": ""
}
|
q18010
|
isValidRadix
|
train
|
function isValidRadix(radix) {
return !(
(radix.type === "Literal" && typeof radix.value !== "number") ||
(radix.type === "Identifier" && radix.name === "undefined")
);
}
|
javascript
|
{
"resource": ""
}
|
q18011
|
checkArguments
|
train
|
function checkArguments(node) {
const args = node.arguments;
switch (args.length) {
case 0:
context.report({
node,
message: "Missing parameters."
});
break;
case 1:
if (mode === MODE_ALWAYS) {
context.report({
node,
message: "Missing radix parameter."
});
}
break;
default:
if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) {
context.report({
node,
message: "Redundant radix parameter."
});
} else if (!isValidRadix(args[1])) {
context.report({
node,
message: "Invalid radix parameter."
});
}
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q18012
|
setInvalid
|
train
|
function setInvalid(node) {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].invalidNodes.push(node);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18013
|
setSuperCalled
|
train
|
function setSuperCalled() {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].superCalled = true;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18014
|
assertValidNodeInfo
|
train
|
function assertValidNodeInfo(descriptor) {
if (descriptor.node) {
assert(typeof descriptor.node === "object", "Node must be an object");
} else {
assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
}
}
|
javascript
|
{
"resource": ""
}
|
q18015
|
normalizeReportLoc
|
train
|
function normalizeReportLoc(descriptor) {
if (descriptor.loc) {
if (descriptor.loc.start) {
return descriptor.loc;
}
return { start: descriptor.loc, end: null };
}
return descriptor.node.loc;
}
|
javascript
|
{
"resource": ""
}
|
q18016
|
compareFixesByRange
|
train
|
function compareFixesByRange(a, b) {
return a.range[0] - b.range[0] || a.range[1] - b.range[1];
}
|
javascript
|
{
"resource": ""
}
|
q18017
|
mergeFixes
|
train
|
function mergeFixes(fixes, sourceCode) {
if (fixes.length === 0) {
return null;
}
if (fixes.length === 1) {
return fixes[0];
}
fixes.sort(compareFixesByRange);
const originalText = sourceCode.text;
const start = fixes[0].range[0];
const end = fixes[fixes.length - 1].range[1];
let text = "";
let lastPos = Number.MIN_SAFE_INTEGER;
for (const fix of fixes) {
assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
if (fix.range[0] >= 0) {
text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
}
text += fix.text;
lastPos = fix.range[1];
}
text += originalText.slice(Math.max(0, start, lastPos), end);
return { range: [start, end], text };
}
|
javascript
|
{
"resource": ""
}
|
q18018
|
normalizeFixes
|
train
|
function normalizeFixes(descriptor, sourceCode) {
if (typeof descriptor.fix !== "function") {
return null;
}
// @type {null | Fix | Fix[] | IterableIterator<Fix>}
const fix = descriptor.fix(ruleFixer);
// Merge to one.
if (fix && Symbol.iterator in fix) {
return mergeFixes(Array.from(fix), sourceCode);
}
return fix;
}
|
javascript
|
{
"resource": ""
}
|
q18019
|
createProblem
|
train
|
function createProblem(options) {
const problem = {
ruleId: options.ruleId,
severity: options.severity,
message: options.message,
line: options.loc.start.line,
column: options.loc.start.column + 1,
nodeType: options.node && options.node.type || null
};
/*
* If this isn’t in the conditional, some of the tests fail
* because `messageId` is present in the problem object
*/
if (options.messageId) {
problem.messageId = options.messageId;
}
if (options.loc.end) {
problem.endLine = options.loc.end.line;
problem.endColumn = options.loc.end.column + 1;
}
if (options.fix) {
problem.fix = options.fix;
}
return problem;
}
|
javascript
|
{
"resource": ""
}
|
q18020
|
parens
|
train
|
function parens(node) {
const isAsync = node.async;
const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0);
/**
* Remove the parenthesis around a parameter
* @param {Fixer} fixer Fixer
* @returns {string} fixed parameter
*/
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
// "as-needed", { "requireForBlockBody": true }: x => x
if (
requireForBlockBody &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
node.body.type !== "BlockStatement" &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParensInline",
fix: fixParamsWithParenthesis
});
}
return;
}
if (
requireForBlockBody &&
node.body.type === "BlockStatement"
) {
if (!astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "expectedParensBlock",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
return;
}
// "as-needed": x => x
if (asNeeded &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParens",
fix: fixParamsWithParenthesis
});
}
return;
}
if (firstTokenOfParam.type === "Identifier") {
const after = sourceCode.getTokenAfter(firstTokenOfParam);
// (x) => x
if (after.value !== ")") {
context.report({
node,
messageId: "expectedParens",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18021
|
fixParamsWithParenthesis
|
train
|
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
|
javascript
|
{
"resource": ""
}
|
q18022
|
isSameProperty
|
train
|
function isSameProperty(left, right) {
if (left.property.type === "Identifier" &&
left.property.type === right.property.type &&
left.property.name === right.property.name &&
left.computed === right.computed
) {
return true;
}
const lname = astUtils.getStaticPropertyName(left);
const rname = astUtils.getStaticPropertyName(right);
return lname !== null && lname === rname;
}
|
javascript
|
{
"resource": ""
}
|
q18023
|
isSameMember
|
train
|
function isSameMember(left, right) {
if (!isSameProperty(left, right)) {
return false;
}
const lobj = left.object;
const robj = right.object;
if (lobj.type !== robj.type) {
return false;
}
if (lobj.type === "MemberExpression") {
return isSameMember(lobj, robj);
}
return lobj.type === "Identifier" && lobj.name === robj.name;
}
|
javascript
|
{
"resource": ""
}
|
q18024
|
eachSelfAssignment
|
train
|
function eachSelfAssignment(left, right, props, report) {
if (!left || !right) {
// do nothing
} else if (
left.type === "Identifier" &&
right.type === "Identifier" &&
left.name === right.name
) {
report(right);
} else if (
left.type === "ArrayPattern" &&
right.type === "ArrayExpression"
) {
const end = Math.min(left.elements.length, right.elements.length);
for (let i = 0; i < end; ++i) {
const rightElement = right.elements[i];
eachSelfAssignment(left.elements[i], rightElement, props, report);
// After a spread element, those indices are unknown.
if (rightElement && rightElement.type === "SpreadElement") {
break;
}
}
} else if (
left.type === "RestElement" &&
right.type === "SpreadElement"
) {
eachSelfAssignment(left.argument, right.argument, props, report);
} else if (
left.type === "ObjectPattern" &&
right.type === "ObjectExpression" &&
right.properties.length >= 1
) {
/*
* Gets the index of the last spread property.
* It's possible to overwrite properties followed by it.
*/
let startJ = 0;
for (let i = right.properties.length - 1; i >= 0; --i) {
const propType = right.properties[i].type;
if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") {
startJ = i + 1;
break;
}
}
for (let i = 0; i < left.properties.length; ++i) {
for (let j = startJ; j < right.properties.length; ++j) {
eachSelfAssignment(
left.properties[i],
right.properties[j],
props,
report
);
}
}
} else if (
left.type === "Property" &&
right.type === "Property" &&
!left.computed &&
!right.computed &&
right.kind === "init" &&
!right.method &&
left.key.name === right.key.name
) {
eachSelfAssignment(left.value, right.value, props, report);
} else if (
props &&
left.type === "MemberExpression" &&
right.type === "MemberExpression" &&
isSameMember(left, right)
) {
report(right);
}
}
|
javascript
|
{
"resource": ""
}
|
q18025
|
report
|
train
|
function report(node) {
context.report({
node,
message: "'{{name}}' is assigned to itself.",
data: {
name: sourceCode.getText(node).replace(SPACES, "")
}
});
}
|
javascript
|
{
"resource": ""
}
|
q18026
|
getFixerFunction
|
train
|
function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
const text =
sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
const range = [previousItemToken.range[1], currentItemToken.range[0]];
return function(fixer) {
return fixer.replaceTextRange(range, getReplacedText(styleType, text));
};
}
|
javascript
|
{
"resource": ""
}
|
q18027
|
validateCommaItemSpacing
|
train
|
function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
// if single line
if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
// do nothing.
} else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
!astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
const comment = sourceCode.getCommentsAfter(commaToken)[0];
const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
? style
: "between";
// lone comma
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.start.column
},
messageId: "unexpectedLineBeforeAndAfterComma",
fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
messageId: "expectedCommaFirst",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.end.column
},
messageId: "expectedCommaLast",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18028
|
isArgumentOfMethodCall
|
train
|
function isArgumentOfMethodCall(node, index, object, property) {
const parent = node.parent;
return (
parent.type === "CallExpression" &&
parent.callee.type === "MemberExpression" &&
parent.callee.computed === false &&
isIdentifier(parent.callee.object, object) &&
isIdentifier(parent.callee.property, property) &&
parent.arguments[index] === node
);
}
|
javascript
|
{
"resource": ""
}
|
q18029
|
processPath
|
train
|
function processPath(options) {
const cwd = (options && options.cwd) || process.cwd();
let extensions = (options && options.extensions) || [".js"];
extensions = extensions.map(ext => ext.replace(/^\./u, ""));
let suffix = "/**";
if (extensions.length === 1) {
suffix += `/*.${extensions[0]}`;
} else {
suffix += `/*.{${extensions.join(",")}}`;
}
/**
* A function that converts a directory name to a glob pattern
*
* @param {string} pathname The directory path to be modified
* @returns {string} The glob path or the file path itself
* @private
*/
return function(pathname) {
if (pathname === "") {
return "";
}
let newPath = pathname;
const resolvedPath = path.resolve(cwd, pathname);
if (directoryExists(resolvedPath)) {
newPath = pathname.replace(/[/\\]$/u, "") + suffix;
}
return pathUtils.convertPathToPosix(newPath);
};
}
|
javascript
|
{
"resource": ""
}
|
q18030
|
listFilesToProcess
|
train
|
function listFilesToProcess(globPatterns, providedOptions) {
const options = providedOptions || { ignore: true };
const cwd = options.cwd || process.cwd();
const getIgnorePaths = lodash.memoize(
optionsObj =>
new IgnoredPaths(optionsObj)
);
/*
* The test "should use default options if none are provided" (source-code-utils.js) checks that 'module.exports.resolveFileGlobPatterns' was called.
* So it cannot use the local function "resolveFileGlobPatterns".
*/
const resolvedGlobPatterns = module.exports.resolveFileGlobPatterns(globPatterns, options);
debug("Creating list of files to process.");
const resolvedPathsByGlobPattern = resolvedGlobPatterns.map(pattern => {
if (pattern === "") {
return [{
filename: "",
behavior: SILENTLY_IGNORE
}];
}
const file = path.resolve(cwd, pattern);
if (options.globInputPaths === false || (fs.existsSync(file) && fs.statSync(file).isFile())) {
const ignoredPaths = getIgnorePaths(options);
const fullPath = options.globInputPaths === false ? file : fs.realpathSync(file);
return [{
filename: fullPath,
behavior: testFileAgainstIgnorePatterns(fullPath, options, true, ignoredPaths)
}];
}
// regex to find .hidden or /.hidden patterns, but not ./relative or ../relative
const globIncludesDotfiles = dotfilesPattern.test(pattern);
let newOptions = options;
if (!options.dotfiles) {
newOptions = Object.assign({}, options, { dotfiles: globIncludesDotfiles });
}
const ignoredPaths = getIgnorePaths(newOptions);
const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker();
const globOptions = {
nodir: true,
dot: true,
cwd
};
return new GlobSync(pattern, globOptions, shouldIgnore).found.map(globMatch => {
const relativePath = path.resolve(cwd, globMatch);
return {
filename: relativePath,
behavior: testFileAgainstIgnorePatterns(relativePath, options, false, ignoredPaths)
};
});
});
const allPathDescriptors = resolvedPathsByGlobPattern.reduce((pathsForAllGlobs, pathsForCurrentGlob, index) => {
if (pathsForCurrentGlob.every(pathDescriptor => pathDescriptor.behavior === SILENTLY_IGNORE && pathDescriptor.filename !== "")) {
throw new (pathsForCurrentGlob.length ? AllFilesIgnoredError : NoFilesFoundError)(globPatterns[index]);
}
pathsForCurrentGlob.forEach(pathDescriptor => {
switch (pathDescriptor.behavior) {
case NORMAL_LINT:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: false });
break;
case IGNORE_AND_WARN:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: true });
break;
case SILENTLY_IGNORE:
// do nothing
break;
default:
throw new Error(`Unexpected file behavior for ${pathDescriptor.filename}`);
}
});
return pathsForAllGlobs;
}, []);
return lodash.uniqBy(allPathDescriptors, pathDescriptor => pathDescriptor.filename);
}
|
javascript
|
{
"resource": ""
}
|
q18031
|
disallowBuiltIns
|
train
|
function disallowBuiltIns(node) {
if (node.callee.type !== "MemberExpression" || node.callee.computed) {
return;
}
const propName = node.callee.property.name;
if (DISALLOWED_PROPS.indexOf(propName) > -1) {
context.report({
message: "Do not access Object.prototype method '{{prop}}' from target object.",
loc: node.callee.property.loc.start,
data: { prop: propName },
node
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18032
|
report
|
train
|
function report(node, startOffset, character) {
context.report({
node,
loc: sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset),
message: "Unnecessary escape character: \\{{character}}.",
data: { character }
});
}
|
javascript
|
{
"resource": ""
}
|
q18033
|
validateString
|
train
|
function validateString(node, match) {
const isTemplateElement = node.type === "TemplateElement";
const escapedChar = match[0][1];
let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
let isQuoteEscape;
if (isTemplateElement) {
isQuoteEscape = escapedChar === "`";
if (escapedChar === "$") {
// Warn if `\$` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] !== "{";
} else if (escapedChar === "{") {
/*
* Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
* is necessary and the rule should not warn. If preceded by `/$`, the rule
* will warn for the `/$` instead, as it is the first unnecessarily escaped character.
*/
isUnnecessaryEscape = match.input[match.index - 1] !== "$";
}
} else {
isQuoteEscape = escapedChar === node.raw[0];
}
if (isUnnecessaryEscape && !isQuoteEscape) {
report(node, match.index + 1, match[0].slice(1));
}
}
|
javascript
|
{
"resource": ""
}
|
q18034
|
check
|
train
|
function check(node) {
const isTemplateElement = node.type === "TemplateElement";
if (
isTemplateElement &&
node.parent &&
node.parent.parent &&
node.parent.parent.type === "TaggedTemplateExpression" &&
node.parent === node.parent.parent.quasi
) {
// Don't report tagged template literals, because the backslash character is accessible to the tag function.
return;
}
if (typeof node.value === "string" || isTemplateElement) {
/*
* JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
* In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
*/
if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
return;
}
const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
const pattern = /\\[^\d]/gu;
let match;
while ((match = pattern.exec(value))) {
validateString(node, match);
}
} else if (node.regex) {
parseRegExp(node.regex.pattern)
/*
* The '-' character is a special case, because it's only valid to escape it if it's in a character
* class, and is not at either edge of the character class. To account for this, don't consider '-'
* characters to be valid in general, and filter out '-' characters that appear in the middle of a
* character class.
*/
.filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
/*
* The '^' character is also a special case; it must always be escaped outside of character classes, but
* it only needs to be escaped in character classes if it's at the beginning of the character class. To
* account for this, consider it to be a valid escape character outside of character classes, and filter
* out '^' characters that appear at the start of a character class.
*/
.filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass))
// Filter out characters that aren't escaped.
.filter(charInfo => charInfo.escaped)
// Filter out characters that are valid to escape, based on their position in the regular expression.
.filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text))
// Report all the remaining characters.
.forEach(charInfo => report(node, charInfo.index, charInfo.text));
}
}
|
javascript
|
{
"resource": ""
}
|
q18035
|
drawTable
|
train
|
function drawTable(messages) {
const rows = [];
if (messages.length === 0) {
return "";
}
rows.push([
chalk.bold("Line"),
chalk.bold("Column"),
chalk.bold("Type"),
chalk.bold("Message"),
chalk.bold("Rule ID")
]);
messages.forEach(message => {
let messageType;
if (message.fatal || message.severity === 2) {
messageType = chalk.red("error");
} else {
messageType = chalk.yellow("warning");
}
rows.push([
message.line || 0,
message.column || 0,
messageType,
message.message,
message.ruleId || ""
]);
});
return table(rows, {
columns: {
0: {
width: 8,
wrapWord: true
},
1: {
width: 8,
wrapWord: true
},
2: {
width: 8,
wrapWord: true
},
3: {
paddingRight: 5,
width: 50,
wrapWord: true
},
4: {
width: 20,
wrapWord: true
}
},
drawHorizontalLine(index) {
return index === 1;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q18036
|
fetchPeerDependencies
|
train
|
function fetchPeerDependencies(packageName) {
const npmProcess = spawn.sync(
"npm",
["show", "--json", packageName, "peerDependencies"],
{ encoding: "utf8" }
);
const error = npmProcess.error;
if (error && error.code === "ENOENT") {
return null;
}
const fetchedText = npmProcess.stdout.trim();
return JSON.parse(fetchedText || "{}");
}
|
javascript
|
{
"resource": ""
}
|
q18037
|
check
|
train
|
function check(packages, opt) {
let deps = [];
const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
let fileJson;
if (!pkgJson) {
throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
}
try {
fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
} catch (e) {
const error = new Error(e);
error.messageTemplate = "failed-to-read-json";
error.messageData = {
path: pkgJson,
message: e.message
};
throw error;
}
if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
deps = deps.concat(Object.keys(fileJson.devDependencies));
}
if (opt.dependencies && typeof fileJson.dependencies === "object") {
deps = deps.concat(Object.keys(fileJson.dependencies));
}
return packages.reduce((status, pkg) => {
status[pkg] = deps.indexOf(pkg) !== -1;
return status;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q18038
|
looksLikeImport
|
train
|
function looksLikeImport(node) {
return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" ||
node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
}
|
javascript
|
{
"resource": ""
}
|
q18039
|
isVariableDeclaration
|
train
|
function isVariableDeclaration(node) {
return (
node.type === "VariableDeclaration" ||
(
node.type === "ExportNamedDeclaration" &&
node.declaration &&
node.declaration.type === "VariableDeclaration"
)
);
}
|
javascript
|
{
"resource": ""
}
|
q18040
|
isVarOnTop
|
train
|
function isVarOnTop(node, statements) {
const l = statements.length;
let i = 0;
// skip over directives
for (; i < l; ++i) {
if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) {
break;
}
}
for (; i < l; ++i) {
if (!isVariableDeclaration(statements[i])) {
return false;
}
if (statements[i] === node) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18041
|
globalVarCheck
|
train
|
function globalVarCheck(node, parent) {
if (!isVarOnTop(node, parent.body)) {
context.report({ node, messageId: "top" });
}
}
|
javascript
|
{
"resource": ""
}
|
q18042
|
blockScopeVarCheck
|
train
|
function blockScopeVarCheck(node, parent, grandParent) {
if (!(/Function/u.test(grandParent.type) &&
parent.type === "BlockStatement" &&
isVarOnTop(node, parent.body))) {
context.report({ node, messageId: "top" });
}
}
|
javascript
|
{
"resource": ""
}
|
q18043
|
checkMetaDocsUrl
|
train
|
function checkMetaDocsUrl(context, exportsNode) {
if (exportsNode.type !== "ObjectExpression") {
// if the exported node is not the correct format, "internal-no-invalid-meta" will already report this.
return;
}
const metaProperty = getPropertyFromObject("meta", exportsNode);
const metaDocs = metaProperty && getPropertyFromObject("docs", metaProperty.value);
const metaDocsUrl = metaDocs && getPropertyFromObject("url", metaDocs.value);
if (!metaDocs) {
context.report({
node: metaProperty,
message: "Rule is missing a meta.docs property"
});
return;
}
if (!metaDocsUrl) {
context.report({
node: metaDocs,
message: "Rule is missing a meta.docs.url property"
});
return;
}
const ruleId = path.basename(context.getFilename().replace(/.js$/u, ""));
const expected = `https://eslint.org/docs/rules/${ruleId}`;
const url = metaDocsUrl.value.value;
if (url !== expected) {
context.report({
node: metaDocsUrl.value,
message: `Incorrect url. Expected "${expected}" but got "${url}"`
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18044
|
reportReference
|
train
|
function reportReference(reference) {
const name = reference.identifier.name,
customMessage = restrictedGlobalMessages[name],
message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
context.report({
node: reference.identifier,
message,
data: {
name,
customMessage
}
});
}
|
javascript
|
{
"resource": ""
}
|
q18045
|
isFirstNode
|
train
|
function isFirstNode(node) {
const parentType = node.parent.type;
if (node.parent.body) {
return Array.isArray(node.parent.body)
? node.parent.body[0] === node
: node.parent.body === node;
}
if (parentType === "IfStatement") {
return isPrecededByTokens(node, ["else", ")"]);
}
if (parentType === "DoWhileStatement") {
return isPrecededByTokens(node, ["do"]);
}
if (parentType === "SwitchCase") {
return isPrecededByTokens(node, [":"]);
}
return isPrecededByTokens(node, [")"]);
}
|
javascript
|
{
"resource": ""
}
|
q18046
|
calcCommentLines
|
train
|
function calcCommentLines(node, lineNumTokenBefore) {
const comments = sourceCode.getCommentsBefore(node);
let numLinesComments = 0;
if (!comments.length) {
return numLinesComments;
}
comments.forEach(comment => {
numLinesComments++;
if (comment.type === "Block") {
numLinesComments += comment.loc.end.line - comment.loc.start.line;
}
// avoid counting lines with inline comments twice
if (comment.loc.start.line === lineNumTokenBefore) {
numLinesComments--;
}
if (comment.loc.end.line === node.loc.start.line) {
numLinesComments--;
}
});
return numLinesComments;
}
|
javascript
|
{
"resource": ""
}
|
q18047
|
getLineNumberOfTokenBefore
|
train
|
function getLineNumberOfTokenBefore(node) {
const tokenBefore = sourceCode.getTokenBefore(node);
let lineNumTokenBefore;
/**
* Global return (at the beginning of a script) is a special case.
* If there is no token before `return`, then we expect no line
* break before the return. Comments are allowed to occupy lines
* before the global return, just no blank lines.
* Setting lineNumTokenBefore to zero in that case results in the
* desired behavior.
*/
if (tokenBefore) {
lineNumTokenBefore = tokenBefore.loc.end.line;
} else {
lineNumTokenBefore = 0; // global return at beginning of script
}
return lineNumTokenBefore;
}
|
javascript
|
{
"resource": ""
}
|
q18048
|
hasNewlineBefore
|
train
|
function hasNewlineBefore(node) {
const lineNumNode = node.loc.start.line;
const lineNumTokenBefore = getLineNumberOfTokenBefore(node);
const commentLines = calcCommentLines(node, lineNumTokenBefore);
return (lineNumNode - lineNumTokenBefore - commentLines) > 1;
}
|
javascript
|
{
"resource": ""
}
|
q18049
|
canFix
|
train
|
function canFix(node) {
const leadingComments = sourceCode.getCommentsBefore(node);
const lastLeadingComment = leadingComments[leadingComments.length - 1];
const tokenBefore = sourceCode.getTokenBefore(node);
if (leadingComments.length === 0) {
return true;
}
/*
* if the last leading comment ends in the same line as the previous token and
* does not share a line with the `return` node, we can consider it safe to fix.
* Example:
* function a() {
* var b; //comment
* return;
* }
*/
if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line &&
lastLeadingComment.loc.end.line !== node.loc.start.line) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18050
|
hasFallthroughComment
|
train
|
function hasFallthroughComment(node, context, fallthroughCommentPattern) {
const sourceCode = context.getSourceCode();
const comment = lodash.last(sourceCode.getCommentsBefore(node));
return Boolean(comment && fallthroughCommentPattern.test(comment.value));
}
|
javascript
|
{
"resource": ""
}
|
q18051
|
hasBlankLinesBetween
|
train
|
function hasBlankLinesBetween(node, token) {
return token.loc.start.line > node.loc.end.line + 1;
}
|
javascript
|
{
"resource": ""
}
|
q18052
|
isJSXLiteral
|
train
|
function isJSXLiteral(node) {
return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
}
|
javascript
|
{
"resource": ""
}
|
q18053
|
isAllowedAsNonBacktick
|
train
|
function isAllowedAsNonBacktick(node) {
const parent = node.parent;
switch (parent.type) {
// Directive Prologues.
case "ExpressionStatement":
return isPartOfDirectivePrologue(node);
// LiteralPropertyName.
case "Property":
case "MethodDefinition":
return parent.key === node && !parent.computed;
// ModuleSpecifier.
case "ImportDeclaration":
case "ExportNamedDeclaration":
case "ExportAllDeclaration":
return parent.source === node;
// Others don't allow.
default:
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q18054
|
isUsingFeatureOfTemplateLiteral
|
train
|
function isUsingFeatureOfTemplateLiteral(node) {
const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
if (hasTag) {
return true;
}
const hasStringInterpolation = node.expressions.length > 0;
if (hasStringInterpolation) {
return true;
}
const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
if (isMultilineString) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18055
|
getPeerDependencies
|
train
|
function getPeerDependencies(moduleName) {
let result = getPeerDependencies.cache.get(moduleName);
if (!result) {
log.info(`Checking peerDependencies of ${moduleName}`);
result = npmUtils.fetchPeerDependencies(moduleName);
getPeerDependencies.cache.set(moduleName, result);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q18056
|
getModulesList
|
train
|
function getModulesList(config, installESLint) {
const modules = {};
// Create a list of modules which should be installed based on config
if (config.plugins) {
for (const plugin of config.plugins) {
modules[`eslint-plugin-${plugin}`] = "latest";
}
}
if (config.extends && config.extends.indexOf("eslint:") === -1) {
const moduleName = `eslint-config-${config.extends}`;
modules[moduleName] = "latest";
Object.assign(
modules,
getPeerDependencies(`${moduleName}@latest`)
);
}
if (installESLint === false) {
delete modules.eslint;
} else {
const installStatus = npmUtils.checkDevDeps(["eslint"]);
// Mark to show messages if it's new installation of eslint.
if (installStatus.eslint === false) {
log.info("Local ESLint installation not found.");
modules.eslint = modules.eslint || "latest";
config.installedESLint = true;
}
}
return Object.keys(modules).map(name => `${name}@${modules[name]}`);
}
|
javascript
|
{
"resource": ""
}
|
q18057
|
processAnswers
|
train
|
function processAnswers(answers) {
let config = {
rules: {},
env: {},
parserOptions: {},
extends: []
};
// set the latest ECMAScript version
config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
config.env.es6 = true;
config.globals = {
Atomics: "readonly",
SharedArrayBuffer: "readonly"
};
// set the module type
if (answers.moduleType === "esm") {
config.parserOptions.sourceType = "module";
} else if (answers.moduleType === "commonjs") {
config.env.commonjs = true;
}
// add in browser and node environments if necessary
answers.env.forEach(env => {
config.env[env] = true;
});
// add in library information
if (answers.framework === "react") {
config.parserOptions.ecmaFeatures = {
jsx: true
};
config.plugins = ["react"];
} else if (answers.framework === "vue") {
config.plugins = ["vue"];
config.extends.push("plugin:vue/essential");
}
// setup rules based on problems/style enforcement preferences
if (answers.purpose === "problems") {
config.extends.unshift("eslint:recommended");
} else if (answers.purpose === "style") {
if (answers.source === "prompt") {
config.extends.unshift("eslint:recommended");
config.rules.indent = ["error", answers.indent];
config.rules.quotes = ["error", answers.quotes];
config.rules["linebreak-style"] = ["error", answers.linebreak];
config.rules.semi = ["error", answers.semi ? "always" : "never"];
} else if (answers.source === "auto") {
config = configureRules(answers, config);
config = autoconfig.extendFromRecommended(config);
}
}
// normalize extends
if (config.extends.length === 0) {
delete config.extends;
} else if (config.extends.length === 1) {
config.extends = config.extends[0];
}
ConfigOps.normalizeToStrings(config);
return config;
}
|
javascript
|
{
"resource": ""
}
|
q18058
|
getConfigForStyleGuide
|
train
|
function getConfigForStyleGuide(guide) {
const guides = {
google: { extends: "google" },
airbnb: { extends: "airbnb" },
"airbnb-base": { extends: "airbnb-base" },
standard: { extends: "standard" }
};
if (!guides[guide]) {
throw new Error("You referenced an unsupported guide.");
}
return guides[guide];
}
|
javascript
|
{
"resource": ""
}
|
q18059
|
getLocalESLintVersion
|
train
|
function getLocalESLintVersion() {
try {
const eslintPath = relativeModuleResolver("eslint", path.join(process.cwd(), "__placeholder__.js"));
const eslint = require(eslintPath);
return eslint.linter.version || null;
} catch (_err) {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q18060
|
hasESLintVersionConflict
|
train
|
function hasESLintVersionConflict(answers) {
// Get the local ESLint version.
const localESLintVersion = getLocalESLintVersion();
if (!localESLintVersion) {
return false;
}
// Get the required range of ESLint version.
const configName = getStyleGuideName(answers);
const moduleName = `eslint-config-${configName}@latest`;
const peerDependencies = getPeerDependencies(moduleName) || {};
const requiredESLintVersionRange = peerDependencies.eslint;
if (!requiredESLintVersionRange) {
return false;
}
answers.localESLintVersion = localESLintVersion;
answers.requiredESLintVersionRange = requiredESLintVersionRange;
// Check the version.
if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
answers.installESLint = false;
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q18061
|
isInFinally
|
train
|
function isInFinally(node) {
for (
let currentNode = node;
currentNode && currentNode.parent && !astUtils.isFunction(currentNode);
currentNode = currentNode.parent
) {
if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q18062
|
getUselessReturns
|
train
|
function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) {
const traversedSegments = providedTraversedSegments || new WeakSet();
for (const segment of prevSegments) {
if (!segment.reachable) {
if (!traversedSegments.has(segment)) {
traversedSegments.add(segment);
getUselessReturns(
uselessReturns,
segment.allPrevSegments.filter(isReturned),
traversedSegments
);
}
continue;
}
uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns);
}
return uselessReturns;
}
|
javascript
|
{
"resource": ""
}
|
q18063
|
markReturnStatementsOnSegmentAsUsed
|
train
|
function markReturnStatementsOnSegmentAsUsed(segment) {
if (!segment.reachable) {
usedUnreachableSegments.add(segment);
segment.allPrevSegments
.filter(isReturned)
.filter(prevSegment => !usedUnreachableSegments.has(prevSegment))
.forEach(markReturnStatementsOnSegmentAsUsed);
return;
}
const info = segmentInfoMap.get(segment);
for (const node of info.uselessReturns) {
remove(scopeInfo.uselessReturns, node);
}
info.uselessReturns = [];
}
|
javascript
|
{
"resource": ""
}
|
q18064
|
parseOptions
|
train
|
function parseOptions(options = {}) {
const before = options.before !== false;
const after = options.after !== false;
const defaultValue = {
before: before ? expectSpaceBefore : unexpectSpaceBefore,
after: after ? expectSpaceAfter : unexpectSpaceAfter
};
const overrides = (options && options.overrides) || {};
const retv = Object.create(null);
for (let i = 0; i < KEYS.length; ++i) {
const key = KEYS[i];
const override = overrides[key];
if (override) {
const thisBefore = ("before" in override) ? override.before : before;
const thisAfter = ("after" in override) ? override.after : after;
retv[key] = {
before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter
};
} else {
retv[key] = defaultValue;
}
}
return retv;
}
|
javascript
|
{
"resource": ""
}
|
q18065
|
checkSpacingBefore
|
train
|
function checkSpacingBefore(token, pattern) {
checkMethodMap[token.value].before(token, pattern || PREV_TOKEN);
}
|
javascript
|
{
"resource": ""
}
|
q18066
|
checkSpacingAfter
|
train
|
function checkSpacingAfter(token, pattern) {
checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN);
}
|
javascript
|
{
"resource": ""
}
|
q18067
|
checkSpacingAroundFirstToken
|
train
|
function checkSpacingAroundFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingAround(firstToken);
}
}
|
javascript
|
{
"resource": ""
}
|
q18068
|
checkSpacingBeforeFirstToken
|
train
|
function checkSpacingBeforeFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingBefore(firstToken);
}
}
|
javascript
|
{
"resource": ""
}
|
q18069
|
checkSpacingAroundTokenBefore
|
train
|
function checkSpacingAroundTokenBefore(node) {
if (node) {
const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken);
checkSpacingAround(token);
}
}
|
javascript
|
{
"resource": ""
}
|
q18070
|
checkSpacingForFunction
|
train
|
function checkSpacingForFunction(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken &&
((firstToken.type === "Keyword" && firstToken.value === "function") ||
firstToken.value === "async")
) {
checkSpacingBefore(firstToken);
}
}
|
javascript
|
{
"resource": ""
}
|
q18071
|
checkSpacingForTryStatement
|
train
|
function checkSpacingForTryStatement(node) {
checkSpacingAroundFirstToken(node);
checkSpacingAroundFirstToken(node.handler);
checkSpacingAroundTokenBefore(node.finalizer);
}
|
javascript
|
{
"resource": ""
}
|
q18072
|
checkSpacingForForOfStatement
|
train
|
function checkSpacingForForOfStatement(node) {
if (node.await) {
checkSpacingBefore(sourceCode.getFirstToken(node, 0));
checkSpacingAfter(sourceCode.getFirstToken(node, 1));
} else {
checkSpacingAroundFirstToken(node);
}
checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken));
}
|
javascript
|
{
"resource": ""
}
|
q18073
|
checkSpacingForModuleDeclaration
|
train
|
function checkSpacingForModuleDeclaration(node) {
const firstToken = sourceCode.getFirstToken(node);
checkSpacingBefore(firstToken, PREV_TOKEN_M);
checkSpacingAfter(firstToken, NEXT_TOKEN_M);
if (node.type === "ExportDefaultDeclaration") {
checkSpacingAround(sourceCode.getTokenAfter(firstToken));
}
if (node.source) {
const fromToken = sourceCode.getTokenBefore(node.source);
checkSpacingBefore(fromToken, PREV_TOKEN_M);
checkSpacingAfter(fromToken, NEXT_TOKEN_M);
}
}
|
javascript
|
{
"resource": ""
}
|
q18074
|
checkSpacingForProperty
|
train
|
function checkSpacingForProperty(node) {
if (node.static) {
checkSpacingAroundFirstToken(node);
}
if (node.kind === "get" ||
node.kind === "set" ||
(
(node.method || node.type === "MethodDefinition") &&
node.value.async
)
) {
const token = sourceCode.getTokenBefore(
node.key,
tok => {
switch (tok.value) {
case "get":
case "set":
case "async":
return true;
default:
return false;
}
}
);
if (!token) {
throw new Error("Failed to find token get, set, or async beside method name");
}
checkSpacingAround(token);
}
}
|
javascript
|
{
"resource": ""
}
|
q18075
|
hashOfConfigFor
|
train
|
function hashOfConfigFor(configHelper, filename) {
const config = configHelper.getConfig(filename);
if (!configHashCache.has(config)) {
configHashCache.set(config, hash(`${pkg.version}_${stringify(config)}`));
}
return configHashCache.get(config);
}
|
javascript
|
{
"resource": ""
}
|
q18076
|
isPossibleConstructor
|
train
|
function isPossibleConstructor(node) {
if (!node) {
return false;
}
switch (node.type) {
case "ClassExpression":
case "FunctionExpression":
case "ThisExpression":
case "MemberExpression":
case "CallExpression":
case "NewExpression":
case "YieldExpression":
case "TaggedTemplateExpression":
case "MetaProperty":
return true;
case "Identifier":
return node.name !== "undefined";
case "AssignmentExpression":
return isPossibleConstructor(node.right);
case "LogicalExpression":
return (
isPossibleConstructor(node.left) ||
isPossibleConstructor(node.right)
);
case "ConditionalExpression":
return (
isPossibleConstructor(node.alternate) ||
isPossibleConstructor(node.consequent)
);
case "SequenceExpression": {
const lastExpression = node.expressions[node.expressions.length - 1];
return isPossibleConstructor(lastExpression);
}
default:
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q18077
|
checkPropertyAccess
|
train
|
function checkPropertyAccess(node, objectName, propertyName) {
if (propertyName === null) {
return;
}
const matchedObject = restrictedProperties.get(objectName);
const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName);
const globalMatchedProperty = globallyRestrictedProperties.get(propertyName);
if (matchedObjectProperty) {
const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}",
data: {
objectName,
propertyName,
message
}
});
} else if (globalMatchedProperty) {
const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{propertyName}}' is restricted from being used.{{message}}",
data: {
propertyName,
message
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18078
|
enterBreakableStatement
|
train
|
function enterBreakableStatement(node) {
scopeInfo = {
label: node.parent.type === "LabeledStatement" ? node.parent.label : null,
breakable: true,
upper: scopeInfo
};
}
|
javascript
|
{
"resource": ""
}
|
q18079
|
enterLabeledStatement
|
train
|
function enterLabeledStatement(node) {
if (!astUtils.isBreakableStatement(node.body)) {
scopeInfo = {
label: node.label,
breakable: false,
upper: scopeInfo
};
}
}
|
javascript
|
{
"resource": ""
}
|
q18080
|
reportIfUnnecessary
|
train
|
function reportIfUnnecessary(node) {
if (!node.label) {
return;
}
const labelNode = node.label;
for (let info = scopeInfo; info !== null; info = info.upper) {
if (info.breakable || info.label && info.label.name === labelNode.name) {
if (info.breakable && info.label && info.label.name === labelNode.name) {
context.report({
node: labelNode,
messageId: "unexpected",
data: labelNode,
fix: fixer => fixer.removeRange([sourceCode.getFirstToken(node).range[1], labelNode.range[1]])
});
}
return;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q18081
|
getState
|
train
|
function getState(name, isStatic) {
const stateMap = stack[stack.length - 1];
const key = `$${name}`; // to avoid "__proto__".
if (!stateMap[key]) {
stateMap[key] = {
nonStatic: { init: false, get: false, set: false },
static: { init: false, get: false, set: false }
};
}
return stateMap[key][isStatic ? "static" : "nonStatic"];
}
|
javascript
|
{
"resource": ""
}
|
q18082
|
needsParens
|
train
|
function needsParens(node, sourceCode) {
const parent = node.parent;
switch (parent.type) {
case "VariableDeclarator":
case "ArrayExpression":
case "ReturnStatement":
case "CallExpression":
case "Property":
return false;
case "AssignmentExpression":
return parent.left === node && !isParenthesised(sourceCode, node);
default:
return !isParenthesised(sourceCode, node);
}
}
|
javascript
|
{
"resource": ""
}
|
q18083
|
getParenTokens
|
train
|
function getParenTokens(node, leftArgumentListParen, sourceCode) {
const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)];
let leftNext = sourceCode.getTokenBefore(node);
let rightNext = sourceCode.getTokenAfter(node);
// Note: don't include the parens of the argument list.
while (
leftNext &&
rightNext &&
leftNext.range[0] > leftArgumentListParen.range[0] &&
isOpeningParenToken(leftNext) &&
isClosingParenToken(rightNext)
) {
parens.push(leftNext, rightNext);
leftNext = sourceCode.getTokenBefore(leftNext);
rightNext = sourceCode.getTokenAfter(rightNext);
}
return parens.sort((a, b) => a.range[0] - b.range[0]);
}
|
javascript
|
{
"resource": ""
}
|
q18084
|
defineFixer
|
train
|
function defineFixer(node, sourceCode) {
return function *(fixer) {
const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken);
const rightParen = sourceCode.getLastToken(node);
// Remove the callee `Object.assign`
yield fixer.remove(node.callee);
// Replace the parens of argument list to braces.
if (needsParens(node, sourceCode)) {
yield fixer.replaceText(leftParen, "({");
yield fixer.replaceText(rightParen, "})");
} else {
yield fixer.replaceText(leftParen, "{");
yield fixer.replaceText(rightParen, "}");
}
// Process arguments.
for (const argNode of node.arguments) {
const innerParens = getParenTokens(argNode, leftParen, sourceCode);
const left = innerParens.shift();
const right = innerParens.pop();
if (argNode.type === "ObjectExpression") {
const maybeTrailingComma = sourceCode.getLastToken(argNode, 1);
const maybeArgumentComma = sourceCode.getTokenAfter(right);
/*
* Make bare this object literal.
* And remove spaces inside of the braces for better formatting.
*/
for (const innerParen of innerParens) {
yield fixer.remove(innerParen);
}
const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)];
const rightRange = [
Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap
right.range[1]
];
yield fixer.removeRange(leftRange);
yield fixer.removeRange(rightRange);
// Remove the comma of this argument if it's duplication.
if (
(argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) &&
isCommaToken(maybeArgumentComma)
) {
yield fixer.remove(maybeArgumentComma);
}
} else {
// Make spread.
if (argNeedsParens(argNode, sourceCode)) {
yield fixer.insertTextBefore(left, "...(");
yield fixer.insertTextAfter(right, ")");
} else {
yield fixer.insertTextBefore(left, "...");
}
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q18085
|
getConfigForFunction
|
train
|
function getConfigForFunction(node) {
if (node.type === "ArrowFunctionExpression") {
// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) {
return overrideConfig.asyncArrow || baseConfig;
}
} else if (isNamedFunction(node)) {
return overrideConfig.named || baseConfig;
// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
} else if (!node.generator) {
return overrideConfig.anonymous || baseConfig;
}
return "ignore";
}
|
javascript
|
{
"resource": ""
}
|
q18086
|
checkFunction
|
train
|
function checkFunction(node) {
const functionConfig = getConfigForFunction(node);
if (functionConfig === "ignore") {
return;
}
const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const leftToken = sourceCode.getTokenBefore(rightToken);
const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken);
if (hasSpacing && functionConfig === "never") {
context.report({
node,
loc: leftToken.loc.end,
message: "Unexpected space before function parentheses.",
fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]])
});
} else if (!hasSpacing && functionConfig === "always") {
context.report({
node,
loc: leftToken.loc.end,
message: "Missing space before function parentheses.",
fix: fixer => fixer.insertTextAfter(leftToken, " ")
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18087
|
createRegExpForIgnorePatterns
|
train
|
function createRegExpForIgnorePatterns(normalizedOptions) {
Object.keys(normalizedOptions).forEach(key => {
const ignorePatternStr = normalizedOptions[key].ignorePattern;
if (ignorePatternStr) {
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u");
normalizedOptions[key].ignorePatternRegExp = regExp;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q18088
|
isConsecutiveComment
|
train
|
function isConsecutiveComment(comment) {
const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true });
return Boolean(
previousTokenOrComment &&
["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1
);
}
|
javascript
|
{
"resource": ""
}
|
q18089
|
isCommentValid
|
train
|
function isCommentValid(comment, options) {
// 1. Check for default ignore pattern.
if (DEFAULT_IGNORE_PATTERN.test(comment.value)) {
return true;
}
// 2. Check for custom ignore pattern.
const commentWithoutAsterisks = comment.value
.replace(/\*/gu, "");
if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
return true;
}
// 3. Check for inline comments.
if (options.ignoreInlineComments && isInlineComment(comment)) {
return true;
}
// 4. Is this a consecutive comment (and are we tolerating those)?
if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) {
return true;
}
// 5. Does the comment start with a possible URL?
if (MAYBE_URL.test(commentWithoutAsterisks)) {
return true;
}
// 6. Is the initial word character a letter?
const commentWordCharsOnly = commentWithoutAsterisks
.replace(WHITESPACE, "");
if (commentWordCharsOnly.length === 0) {
return true;
}
const firstWordChar = commentWordCharsOnly[0];
if (!LETTER_PATTERN.test(firstWordChar)) {
return true;
}
// 7. Check the case of the initial word character.
const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(),
isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase();
if (capitalize === "always" && isLowercase) {
return false;
}
if (capitalize === "never" && isUppercase) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q18090
|
processComment
|
train
|
function processComment(comment) {
const options = normalizedOptions[comment.type],
commentValid = isCommentValid(comment, options);
if (!commentValid) {
const messageId = capitalize === "always"
? "unexpectedLowercaseComment"
: "unexpectedUppercaseComment";
context.report({
node: null, // Intentionally using loc instead
loc: comment.loc,
messageId,
fix(fixer) {
const match = comment.value.match(LETTER_PATTERN);
return fixer.replaceTextRange(
// Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)
[comment.range[0] + match.index + 2, comment.range[0] + match.index + 3],
capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase()
);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q18091
|
isClassConstructor
|
train
|
function isClassConstructor(node) {
return node.type === "FunctionExpression" &&
node.parent &&
node.parent.type === "MethodDefinition" &&
node.parent.kind === "constructor";
}
|
javascript
|
{
"resource": ""
}
|
q18092
|
checkLastSegment
|
train
|
function checkLastSegment(node) {
let loc, name;
/*
* Skip if it expected no return value or unreachable.
* When unreachable, all paths are returned or thrown.
*/
if (!funcInfo.hasReturnValue ||
funcInfo.codePath.currentSegments.every(isUnreachable) ||
astUtils.isES5Constructor(node) ||
isClassConstructor(node)
) {
return;
}
// Adjust a location and a message.
if (node.type === "Program") {
// The head of program.
loc = { line: 1, column: 0 };
name = "program";
} else if (node.type === "ArrowFunctionExpression") {
// `=>` token
loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
} else if (
node.parent.type === "MethodDefinition" ||
(node.parent.type === "Property" && node.parent.method)
) {
// Method name.
loc = node.parent.key.loc.start;
} else {
// Function name or `function` keyword.
loc = (node.id || node).loc.start;
}
if (!name) {
name = astUtils.getFunctionNameWithKind(node);
}
// Reports.
context.report({
node,
loc,
messageId: "missingReturn",
data: { name }
});
}
|
javascript
|
{
"resource": ""
}
|
q18093
|
countClassAttributes
|
train
|
function countClassAttributes(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
case "attribute":
case "field":
case "nth-child":
case "nth-last-child":
return 1;
default:
return 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q18094
|
countIdentifiers
|
train
|
function countIdentifiers(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
case "identifier":
return 1;
default:
return 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q18095
|
compareSpecificity
|
train
|
function compareSpecificity(selectorA, selectorB) {
return selectorA.attributeCount - selectorB.attributeCount ||
selectorA.identifierCount - selectorB.identifierCount ||
(selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
}
|
javascript
|
{
"resource": ""
}
|
q18096
|
reportFirstExtraStatementAndClear
|
train
|
function reportFirstExtraStatementAndClear() {
if (firstExtraStatement) {
context.report({
node: firstExtraStatement,
messageId: "exceed",
data: {
numberOfStatementsOnThisLine,
maxStatementsPerLine,
statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements"
}
});
}
firstExtraStatement = null;
}
|
javascript
|
{
"resource": ""
}
|
q18097
|
enterStatement
|
train
|
function enterStatement(node) {
const line = node.loc.start.line;
/*
* Skip to allow non-block statements if this is direct child of control statements.
* `if (a) foo();` is counted as 1.
* But `if (a) foo(); else foo();` should be counted as 2.
*/
if (SINGLE_CHILD_ALLOWED.test(node.parent.type) &&
node.parent.alternate !== node
) {
return;
}
// Update state.
if (line === lastStatementLine) {
numberOfStatementsOnThisLine += 1;
} else {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
// Reports if the node violated this rule.
if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) {
firstExtraStatement = firstExtraStatement || node;
}
}
|
javascript
|
{
"resource": ""
}
|
q18098
|
leaveStatement
|
train
|
function leaveStatement(node) {
const line = getActualLastToken(node).loc.end.line;
// Update state.
if (line !== lastStatementLine) {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
}
|
javascript
|
{
"resource": ""
}
|
q18099
|
checkSpacingInsideBraces
|
train
|
function checkSpacingInsideBraces(node) {
// Gets braces and the first/last token of content.
const openBrace = getOpenBrace(node);
const closeBrace = sourceCode.getLastToken(node);
const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true });
const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true });
// Skip if the node is invalid or empty.
if (openBrace.type !== "Punctuator" ||
openBrace.value !== "{" ||
closeBrace.type !== "Punctuator" ||
closeBrace.value !== "}" ||
firstToken === closeBrace
) {
return;
}
// Skip line comments for option never
if (!always && firstToken.type === "Line") {
return;
}
// Check.
if (!isValid(openBrace, firstToken)) {
context.report({
node,
loc: openBrace.loc.start,
messageId,
data: {
location: "after",
token: openBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextBefore(firstToken, " ");
}
return fixer.removeRange([openBrace.range[1], firstToken.range[0]]);
}
});
}
if (!isValid(lastToken, closeBrace)) {
context.report({
node,
loc: closeBrace.loc.start,
messageId,
data: {
location: "before",
token: closeBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextAfter(lastToken, " ");
}
return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.