_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18100 | convertToStarredBlock | train | function convertToStarredBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
return `\n${starredLines.join("\n")}\n${initialOffset} `;
} | javascript | {
"resource": ""
} |
q18101 | convertToSeparateLines | train | function convertToSeparateLines(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
return separateLines.join(`\n${initialOffset}`);
} | javascript | {
"resource": ""
} |
q18102 | convertToBlock | train | function convertToBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const blockLines = commentLinesList.map(line => line.trim());
return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
} | javascript | {
"resource": ""
} |
q18103 | isJSDoc | train | function isJSDoc(commentGroup) {
const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
return commentGroup[0].type === "Block" &&
/^\*\s*$/u.test(lines[0]) &&
lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
/^\s*$/u.test(lines[lines.length - 1]);
} | javascript | {
"resource": ""
} |
q18104 | isIdentifierReference | train | function isIdentifierReference(node) {
const parent = node.parent;
switch (parent.type) {
case "LabeledStatement":
case "BreakStatement":
case "ContinueStatement":
case "ArrayPattern":
case "RestElement":
case "ImportSpecifier":
case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier":
case "CatchClause":
return false;
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
case "ClassDeclaration":
case "ClassExpression":
case "VariableDeclarator":
return parent.id !== node;
case "Property":
case "MethodDefinition":
return (
parent.key !== node ||
parent.computed ||
parent.shorthand
);
case "AssignmentPattern":
return parent.key !== node;
default:
return true;
}
} | javascript | {
"resource": ""
} |
q18105 | leaveFromCurrentSegment | train | function leaveFromCurrentSegment(analyzer, node) {
const state = CodePath.getState(analyzer.codePath);
const currentSegments = state.currentSegments;
for (let i = 0; i < currentSegments.length; ++i) {
const currentSegment = currentSegments[i];
debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`);
if (currentSegment.reachable) {
analyzer.emitter.emit(
"onCodePathSegmentEnd",
currentSegment,
node
);
}
}
state.currentSegments = [];
} | javascript | {
"resource": ""
} |
q18106 | preprocess | train | function preprocess(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
const parent = node.parent;
switch (parent.type) {
case "LogicalExpression":
if (
parent.right === node &&
isHandledLogicalOperator(parent.operator)
) {
state.makeLogicalRight();
}
break;
case "ConditionalExpression":
case "IfStatement":
/*
* Fork if this node is at `consequent`/`alternate`.
* `popForkContext()` exists at `IfStatement:exit` and
* `ConditionalExpression:exit`.
*/
if (parent.consequent === node) {
state.makeIfConsequent();
} else if (parent.alternate === node) {
state.makeIfAlternate();
}
break;
case "SwitchCase":
if (parent.consequent[0] === node) {
state.makeSwitchCaseBody(false, !parent.test);
}
break;
case "TryStatement":
if (parent.handler === node) {
state.makeCatchBlock();
} else if (parent.finalizer === node) {
state.makeFinallyBlock();
}
break;
case "WhileStatement":
if (parent.test === node) {
state.makeWhileTest(getBooleanValueIfSimpleConstant(node));
} else {
assert(parent.body === node);
state.makeWhileBody();
}
break;
case "DoWhileStatement":
if (parent.body === node) {
state.makeDoWhileBody();
} else {
assert(parent.test === node);
state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node));
}
break;
case "ForStatement":
if (parent.test === node) {
state.makeForTest(getBooleanValueIfSimpleConstant(node));
} else if (parent.update === node) {
state.makeForUpdate();
} else if (parent.body === node) {
state.makeForBody();
}
break;
case "ForInStatement":
case "ForOfStatement":
if (parent.left === node) {
state.makeForInOfLeft();
} else if (parent.right === node) {
state.makeForInOfRight();
} else {
assert(parent.body === node);
state.makeForInOfBody();
}
break;
case "AssignmentPattern":
/*
* Fork if this node is at `right`.
* `left` is executed always, so it uses the current path.
* `popForkContext()` exists at `AssignmentPattern:exit`.
*/
if (parent.right === node) {
state.pushForkContext();
state.forkBypassPath();
state.forkPath();
}
break;
default:
break;
}
} | javascript | {
"resource": ""
} |
q18107 | processCodePathToEnter | train | function processCodePathToEnter(analyzer, node) {
let codePath = analyzer.codePath;
let state = codePath && CodePath.getState(codePath);
const parent = node.parent;
switch (node.type) {
case "Program":
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
if (codePath) {
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
}
// Create the code path of this scope.
codePath = analyzer.codePath = new CodePath(
analyzer.idGenerator.next(),
codePath,
analyzer.onLooped
);
state = CodePath.getState(codePath);
// Emits onCodePathStart events.
debug.dump(`onCodePathStart ${codePath.id}`);
analyzer.emitter.emit("onCodePathStart", codePath, node);
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.pushChoiceContext(
node.operator,
isForkingByTrueOrFalse(node)
);
}
break;
case "ConditionalExpression":
case "IfStatement":
state.pushChoiceContext("test", false);
break;
case "SwitchStatement":
state.pushSwitchContext(
node.cases.some(isCaseNode),
astUtils.getLabel(node)
);
break;
case "TryStatement":
state.pushTryContext(Boolean(node.finalizer));
break;
case "SwitchCase":
/*
* Fork if this node is after the 2st node in `cases`.
* It's similar to `else` blocks.
* The next `test` node is processed in this path.
*/
if (parent.discriminant !== node && parent.cases[0] !== node) {
state.forkPath();
}
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.pushLoopContext(node.type, astUtils.getLabel(node));
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.pushBreakContext(false, node.label.name);
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
} | javascript | {
"resource": ""
} |
q18108 | processCodePathToExit | train | function processCodePathToExit(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
let dontForward = false;
switch (node.type) {
case "IfStatement":
case "ConditionalExpression":
state.popChoiceContext();
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.popChoiceContext();
}
break;
case "SwitchStatement":
state.popSwitchContext();
break;
case "SwitchCase":
/*
* This is the same as the process at the 1st `consequent` node in
* `preprocess` function.
* Must do if this `consequent` is empty.
*/
if (node.consequent.length === 0) {
state.makeSwitchCaseBody(true, !node.test);
}
if (state.forkContext.reachable) {
dontForward = true;
}
break;
case "TryStatement":
state.popTryContext();
break;
case "BreakStatement":
forwardCurrentToHead(analyzer, node);
state.makeBreak(node.label && node.label.name);
dontForward = true;
break;
case "ContinueStatement":
forwardCurrentToHead(analyzer, node);
state.makeContinue(node.label && node.label.name);
dontForward = true;
break;
case "ReturnStatement":
forwardCurrentToHead(analyzer, node);
state.makeReturn();
dontForward = true;
break;
case "ThrowStatement":
forwardCurrentToHead(analyzer, node);
state.makeThrow();
dontForward = true;
break;
case "Identifier":
if (isIdentifierReference(node)) {
state.makeFirstThrowablePathInTryBlock();
dontForward = true;
}
break;
case "CallExpression":
case "MemberExpression":
case "NewExpression":
state.makeFirstThrowablePathInTryBlock();
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.popLoopContext();
break;
case "AssignmentPattern":
state.popForkContext();
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.popBreakContext();
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
if (!dontForward) {
forwardCurrentToHead(analyzer, node);
}
debug.dumpState(node, state, true);
} | javascript | {
"resource": ""
} |
q18109 | getOperatorToken | train | function getOperatorToken(node) {
return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
} | javascript | {
"resource": ""
} |
q18110 | verify | train | function verify(node) {
if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
return;
}
const left = node.left;
const expr = node.right;
const operator = expr.operator;
if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
if (same(left, expr.left)) {
context.report({
node,
messageId: "replaced",
fix(fixer) {
if (canBeFixed(left)) {
const equalsToken = getOperatorToken(node);
const operatorToken = getOperatorToken(expr);
const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
}
return null;
}
});
} else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
/*
* This case can't be fixed safely.
* If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
* change the execution order of the valueOf() functions.
*/
context.report({
node,
messageId: "replaced"
});
}
}
} | javascript | {
"resource": ""
} |
q18111 | prohibit | train | function prohibit(node) {
if (node.operator !== "=") {
context.report({
node,
messageId: "unexpected",
fix(fixer) {
if (canBeFixed(node.left)) {
const operatorToken = getOperatorToken(node);
const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
const newOperator = node.operator.slice(0, -1);
let rightText;
// If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
if (
astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
!astUtils.isParenthesised(sourceCode, node.right)
) {
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
} else {
rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
}
return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
}
return null;
}
});
}
} | javascript | {
"resource": ""
} |
q18112 | validateArguments | train | function validateArguments(parens, elements) {
const leftParen = parens.leftParen;
const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
for (let i = 0; i <= elements.length - 2; i++) {
const currentElement = elements[i];
const nextElement = elements[i + 1];
const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;
if (!hasNewLine && needsNewlines) {
context.report({
node: currentElement,
messageId: "expectedBetween",
fix: fixer => fixer.insertTextBefore(nextElement, "\n")
});
}
}
} | javascript | {
"resource": ""
} |
q18113 | getParenTokens | train | function getParenTokens(node) {
switch (node.type) {
case "NewExpression":
if (!node.arguments.length && !(
astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
astUtils.isClosingParenToken(sourceCode.getLastToken(node))
)) {
// If the NewExpression does not have parens (e.g. `new Foo`), return null.
return null;
}
// falls through
case "CallExpression":
return {
leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
rightParen: sourceCode.getLastToken(node)
};
case "FunctionDeclaration":
case "FunctionExpression": {
const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const rightParen = node.params.length
? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
: sourceCode.getTokenAfter(leftParen);
return { leftParen, rightParen };
}
case "ArrowFunctionExpression": {
const firstToken = sourceCode.getFirstToken(node);
if (!astUtils.isOpeningParenToken(firstToken)) {
// If the ArrowFunctionExpression has a single param without parens, return null.
return null;
}
return {
leftParen: firstToken,
rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
};
}
default:
throw new TypeError(`unexpected node with type ${node.type}`);
}
} | javascript | {
"resource": ""
} |
q18114 | validateNode | train | function validateNode(node) {
const parens = getParenTokens(node);
if (parens) {
validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
if (multilineArgumentsOption) {
validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments);
}
}
} | javascript | {
"resource": ""
} |
q18115 | getDefinedMessage | train | function getDefinedMessage(unusedVar) {
const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
let type;
let pattern;
if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
type = "args";
pattern = config.caughtErrorsIgnorePattern.toString();
} else if (defType === "Parameter" && config.argsIgnorePattern) {
type = "args";
pattern = config.argsIgnorePattern.toString();
} else if (defType !== "Parameter" && config.varsIgnorePattern) {
type = "vars";
pattern = config.varsIgnorePattern.toString();
}
const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : "";
return `'{{name}}' is defined but never used.${additional}`;
} | javascript | {
"resource": ""
} |
q18116 | hasRestSpreadSibling | train | function hasRestSpreadSibling(variable) {
if (config.ignoreRestSiblings) {
return variable.defs.some(def => {
const propertyNode = def.name.parent;
const patternNode = propertyNode.parent;
return (
propertyNode.type === "Property" &&
patternNode.type === "ObjectPattern" &&
REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type)
);
});
}
return false;
} | javascript | {
"resource": ""
} |
q18117 | isSelfReference | train | function isSelfReference(ref, nodes) {
let scope = ref.from;
while (scope) {
if (nodes.indexOf(scope.block) >= 0) {
return true;
}
scope = scope.upper;
}
return false;
} | javascript | {
"resource": ""
} |
q18118 | getFunctionDefinitions | train | function getFunctionDefinitions(variable) {
const functionDefinitions = [];
variable.defs.forEach(def => {
const { type, node } = def;
// FunctionDeclarations
if (type === "FunctionName") {
functionDefinitions.push(node);
}
// FunctionExpressions
if (type === "Variable" && node.init &&
(node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
functionDefinitions.push(node.init);
}
});
return functionDefinitions;
} | javascript | {
"resource": ""
} |
q18119 | isInside | train | function isInside(inner, outer) {
return (
inner.range[0] >= outer.range[0] &&
inner.range[1] <= outer.range[1]
);
} | javascript | {
"resource": ""
} |
q18120 | getRhsNode | train | function getRhsNode(ref, prevRhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
const refScope = ref.from.variableScope;
const varScope = ref.resolved.scope.variableScope;
const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
/*
* Inherits the previous node if this reference is in the node.
* This is for `a = a + a`-like code.
*/
if (prevRhsNode && isInside(id, prevRhsNode)) {
return prevRhsNode;
}
if (parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
id === parent.left &&
!canBeUsedLater
) {
return parent.right;
}
return null;
} | javascript | {
"resource": ""
} |
q18121 | isReadForItself | train | function isReadForItself(ref, rhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
return ref.isRead() && (
// self update. e.g. `a += 1`, `a++`
(// in RHS of an assignment for itself. e.g. `a = a + 1`
((
parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
parent.left === id
) ||
(
parent.type === "UpdateExpression" &&
granpa.type === "ExpressionStatement"
) || rhsNode &&
isInside(id, rhsNode) &&
!isInsideOfStorableFunction(id, rhsNode)))
);
} | javascript | {
"resource": ""
} |
q18122 | isForInRef | train | function isForInRef(ref) {
let target = ref.identifier.parent;
// "for (var ...) { return; }"
if (target.type === "VariableDeclarator") {
target = target.parent.parent;
}
if (target.type !== "ForInStatement") {
return false;
}
// "for (...) { return; }"
if (target.body.type === "BlockStatement") {
target = target.body.body[0];
// "for (...) return;"
} else {
target = target.body;
}
// For empty loop body
if (!target) {
return false;
}
return target.type === "ReturnStatement";
} | javascript | {
"resource": ""
} |
q18123 | isAfterLastUsedArg | train | function isAfterLastUsedArg(variable) {
const def = variable.defs[0];
const params = context.getDeclaredVariables(def.node);
const posteriorParams = params.slice(params.indexOf(variable) + 1);
// If any used parameters occur after this parameter, do not report.
return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
} | javascript | {
"resource": ""
} |
q18124 | report | train | function report(node, loc, otherNode) {
context.report({
node,
fix(fixer) {
if (options[loc]) {
if (loc === "before") {
return fixer.insertTextBefore(node, " ");
}
return fixer.insertTextAfter(node, " ");
}
let start, end;
const newText = "";
if (loc === "before") {
start = otherNode.range[1];
end = node.range[0];
} else {
start = node.range[1];
end = otherNode.range[0];
}
return fixer.replaceTextRange([start, end], newText);
},
messageId: options[loc] ? "missing" : "unexpected",
data: {
loc
}
});
} | javascript | {
"resource": ""
} |
q18125 | validateCommaItemSpacing | train | function validateCommaItemSpacing(tokens, reportItem) {
if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) &&
(options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma))
) {
report(reportItem, "before", tokens.left);
}
if (tokens.right && astUtils.isClosingParenToken(tokens.right)) {
return;
}
if (tokens.right && !options.after && tokens.right.type === "Line") {
return;
}
if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) &&
(options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right))
) {
report(reportItem, "after", tokens.right);
}
} | javascript | {
"resource": ""
} |
q18126 | addNullElementsToIgnoreList | train | function addNullElementsToIgnoreList(node) {
let previousToken = sourceCode.getFirstToken(node);
node.elements.forEach(element => {
let token;
if (element === null) {
token = sourceCode.getTokenAfter(previousToken);
if (astUtils.isCommaToken(token)) {
commaTokensToIgnore.push(token);
}
} else {
token = sourceCode.getTokenAfter(element);
}
previousToken = token;
});
} | javascript | {
"resource": ""
} |
q18127 | getEnclosingFunctionScope | train | function getEnclosingFunctionScope(scope) {
let currentScope = scope;
while (currentScope.type !== "function" && currentScope.type !== "global") {
currentScope = currentScope.upper;
}
return currentScope;
} | javascript | {
"resource": ""
} |
q18128 | isLoopAssignee | train | function isLoopAssignee(node) {
return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") &&
node === node.parent.left;
} | javascript | {
"resource": ""
} |
q18129 | getScopeNode | train | function getScopeNode(node) {
for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
if (SCOPE_NODE_TYPE.test(currentNode.type)) {
return currentNode;
}
}
/* istanbul ignore next : unreachable */
return null;
} | javascript | {
"resource": ""
} |
q18130 | isUsedFromOutsideOf | train | function isUsedFromOutsideOf(scopeNode) {
/**
* Checks whether a given reference is inside of the specified scope or not.
*
* @param {eslint-scope.Reference} reference - A reference to check.
* @returns {boolean} `true` if the reference is inside of the specified
* scope.
*/
function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
}
return function(variable) {
return variable.references.some(isOutsideOfScope);
};
} | javascript | {
"resource": ""
} |
q18131 | isOutsideOfScope | train | function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
} | javascript | {
"resource": ""
} |
q18132 | hasReferenceInTDZ | train | function hasReferenceInTDZ(node) {
const initStart = node.range[0];
const initEnd = node.range[1];
return variable => {
const id = variable.defs[0].name;
const idStart = id.range[0];
const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null);
const defaultStart = defaultValue && defaultValue.range[0];
const defaultEnd = defaultValue && defaultValue.range[1];
return variable.references.some(reference => {
const start = reference.identifier.range[0];
const end = reference.identifier.range[1];
return !reference.init && (
start < idStart ||
(defaultValue !== null && start >= defaultStart && end <= defaultEnd) ||
(start >= initStart && end <= initEnd)
);
});
};
} | javascript | {
"resource": ""
} |
q18133 | hasSelfReferenceInTDZ | train | function hasSelfReferenceInTDZ(declarator) {
if (!declarator.init) {
return false;
}
const variables = context.getDeclaredVariables(declarator);
return variables.some(hasReferenceInTDZ(declarator.init));
} | javascript | {
"resource": ""
} |
q18134 | report | train | function report(node) {
context.report({
node,
message: "Unexpected var, use let or const instead.",
fix(fixer) {
const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" });
return canFix(node)
? fixer.replaceText(varToken, "let")
: null;
}
});
} | javascript | {
"resource": ""
} |
q18135 | checkArrowFunc | train | function checkArrowFunc(node) {
const body = node.body;
if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
context.report({
node,
messageId: "confusing",
fix(fixer) {
// if `allowParens` is not set to true dont bother wrapping in parens
return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
}
});
}
} | javascript | {
"resource": ""
} |
q18136 | checkFunction | train | function checkFunction(node) {
const parent = node.parent;
if (parent.type === "CallExpression") {
callbackStack.push(node);
}
if (callbackStack.length > THRESHOLD) {
const opts = { num: callbackStack.length, max: THRESHOLD };
context.report({ node, messageId: "exceed", data: opts });
}
} | javascript | {
"resource": ""
} |
q18137 | isInitialized | train | function isInitialized(node) {
const declaration = node.parent;
const block = declaration.parent;
if (isForLoop(block)) {
if (block.type === "ForStatement") {
return block.init === declaration;
}
return block.left === declaration;
}
return Boolean(node.init);
} | javascript | {
"resource": ""
} |
q18138 | checkArray | train | function checkArray(obj, key, fallback) {
/* istanbul ignore if */
if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
throw new TypeError(`${key}, if provided, must be an Array`);
}
return obj[key] || fallback;
} | javascript | {
"resource": ""
} |
q18139 | calculateCapIsNewExceptions | train | function calculateCapIsNewExceptions(config) {
let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
if (capIsNewExceptions !== CAPS_ALLOWED) {
capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
}
return capIsNewExceptions.reduce(invert, {});
} | javascript | {
"resource": ""
} |
q18140 | getCap | train | function getCap(str) {
const firstChar = str.charAt(0);
const firstCharLower = firstChar.toLowerCase();
const firstCharUpper = firstChar.toUpperCase();
if (firstCharLower === firstCharUpper) {
// char has no uppercase variant, so it's non-alphabetic
return "non-alpha";
}
if (firstChar === firstCharLower) {
return "lower";
}
return "upper";
} | javascript | {
"resource": ""
} |
q18141 | isCapAllowed | train | function isCapAllowed(allowedMap, node, calleeName, pattern) {
const sourceText = sourceCode.getText(node.callee);
if (allowedMap[calleeName] || allowedMap[sourceText]) {
return true;
}
if (pattern && pattern.test(sourceText)) {
return true;
}
if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
// allow if callee is Date.UTC
return node.callee.object.type === "Identifier" &&
node.callee.object.name === "Date";
}
return skipProperties && node.callee.type === "MemberExpression";
} | javascript | {
"resource": ""
} |
q18142 | report | train | function report(node, messageId) {
let callee = node.callee;
if (callee.type === "MemberExpression") {
callee = callee.property;
}
context.report({ node, loc: callee.loc.start, messageId });
} | javascript | {
"resource": ""
} |
q18143 | getVisitorKeys | train | function getVisitorKeys(visitorKeys, node) {
let keys = visitorKeys[node.type];
if (!keys) {
keys = vk.getKeys(node);
debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys);
}
return keys;
} | javascript | {
"resource": ""
} |
q18144 | looksLikeLiteral | train | function looksLikeLiteral(node) {
return (node.type === "UnaryExpression" &&
node.operator === "-" &&
node.prefix &&
node.argument.type === "Literal" &&
typeof node.argument.value === "number");
} | javascript | {
"resource": ""
} |
q18145 | report | train | function report(node, existing, substitute) {
context.report({
node,
message: "Avoid using {{existing}}, instead use {{substitute}}.",
data: {
existing,
substitute
}
});
} | javascript | {
"resource": ""
} |
q18146 | checkRegex | train | function checkRegex(regex, node, uFlag) {
let ast;
try {
ast = parser.parsePattern(regex, 0, regex.length, uFlag);
} catch (_) {
// ignore regex syntax errors
return;
}
regexpp.visitRegExpAST(ast, {
onCapturingGroupEnter(group) {
if (!group.name) {
const locNode = node.type === "Literal" ? node : node.arguments[0];
context.report({
node,
messageId: "required",
loc: {
start: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.start + 1
},
end: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.end + 1
}
},
data: {
group: group.raw
}
});
}
}
});
} | javascript | {
"resource": ""
} |
q18147 | normalizeDirectoryEntries | train | function normalizeDirectoryEntries(entries, directory, supportedConfigs) {
const fileHash = {};
entries.forEach(entry => {
if (supportedConfigs.indexOf(entry) >= 0) {
const resolvedEntry = path.resolve(directory, entry);
if (fs.statSync(resolvedEntry).isFile()) {
fileHash[entry] = resolvedEntry;
}
}
});
return fileHash;
} | javascript | {
"resource": ""
} |
q18148 | getKind | train | function getKind(node) {
const parent = node.parent;
let kind = "";
if (node.type === "ArrowFunctionExpression") {
return "arrowFunctions";
}
// Detects main kind.
if (parent.type === "Property") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
kind = parent.method ? "methods" : "functions";
} else if (parent.type === "MethodDefinition") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
if (parent.kind === "constructor") {
return "constructors";
}
kind = "methods";
} else {
kind = "functions";
}
// Detects prefix.
let prefix = "";
if (node.generator) {
prefix = "generator";
} else if (node.async) {
prefix = "async";
} else {
return kind;
}
return prefix + kind[0].toUpperCase() + kind.slice(1);
} | javascript | {
"resource": ""
} |
q18149 | reportIfEmpty | train | function reportIfEmpty(node) {
const kind = getKind(node);
const name = astUtils.getFunctionNameWithKind(node);
const innerComments = sourceCode.getTokens(node.body, {
includeComments: true,
filter: astUtils.isCommentToken
});
if (allowed.indexOf(kind) === -1 &&
node.body.type === "BlockStatement" &&
node.body.body.length === 0 &&
innerComments.length === 0
) {
context.report({
node,
loc: node.body.loc.start,
messageId: "unexpected",
data: { name }
});
}
} | javascript | {
"resource": ""
} |
q18150 | enterLabeledScope | train | function enterLabeledScope(node) {
scopeInfo = {
label: node.label.name,
used: false,
upper: scopeInfo
};
} | javascript | {
"resource": ""
} |
q18151 | exitLabeledScope | train | function exitLabeledScope(node) {
if (!scopeInfo.used) {
context.report({
node: node.label,
messageId: "unused",
data: node.label,
fix(fixer) {
/*
* Only perform a fix if there are no comments between the label and the body. This will be the case
* when there is exactly one token/comment (the ":") between the label and the body.
*/
if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
sourceCode.getTokenBefore(node.body, { includeComments: true })) {
return fixer.removeRange([node.range[0], node.body.range[0]]);
}
return null;
}
});
}
scopeInfo = scopeInfo.upper;
} | javascript | {
"resource": ""
} |
q18152 | markAsUsed | train | function markAsUsed(node) {
if (!node.label) {
return;
}
const label = node.label.name;
let info = scopeInfo;
while (info) {
if (info.label === label) {
info.used = true;
break;
}
info = info.upper;
}
} | javascript | {
"resource": ""
} |
q18153 | isIIFEStatement | train | function isIIFEStatement(node) {
if (node.type === "ExpressionStatement") {
let call = node.expression;
if (call.type === "UnaryExpression") {
call = call.argument;
}
return call.type === "CallExpression" && astUtils.isFunction(call.callee);
}
return false;
} | javascript | {
"resource": ""
} |
q18154 | isBlockLikeStatement | train | function isBlockLikeStatement(sourceCode, node) {
// do-while with a block is a block-like statement.
if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") {
return true;
}
/*
* IIFE is a block-like statement specially from
* JSCS#disallowPaddingNewLinesAfterBlocks.
*/
if (isIIFEStatement(node)) {
return true;
}
// Checks the last token is a closing brace of blocks.
const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken)
? sourceCode.getNodeByRangeIndex(lastToken.range[0])
: null;
return Boolean(belongingNode) && (
belongingNode.type === "BlockStatement" ||
belongingNode.type === "SwitchStatement"
);
} | javascript | {
"resource": ""
} |
q18155 | isDirective | train | function isDirective(node, sourceCode) {
return (
node.type === "ExpressionStatement" &&
(
node.parent.type === "Program" ||
(
node.parent.type === "BlockStatement" &&
astUtils.isFunction(node.parent.parent)
)
) &&
node.expression.type === "Literal" &&
typeof node.expression.value === "string" &&
!astUtils.isParenthesised(sourceCode, node.expression)
);
} | javascript | {
"resource": ""
} |
q18156 | isDirectivePrologue | train | function isDirectivePrologue(node, sourceCode) {
if (isDirective(node, sourceCode)) {
for (const sibling of node.parent.body) {
if (sibling === node) {
break;
}
if (!isDirective(sibling, sourceCode)) {
return false;
}
}
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q18157 | getActualLastToken | train | function getActualLastToken(sourceCode, node) {
const semiToken = sourceCode.getLastToken(node);
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const isSemicolonLessStyle = Boolean(
prevToken &&
nextToken &&
prevToken.range[0] >= node.range[0] &&
astUtils.isSemicolonToken(semiToken) &&
semiToken.loc.start.line !== prevToken.loc.end.line &&
semiToken.loc.end.line === nextToken.loc.start.line
);
return isSemicolonLessStyle ? prevToken : semiToken;
} | javascript | {
"resource": ""
} |
q18158 | verifyForNever | train | function verifyForNever(context, _, nextNode, paddingLines) {
if (paddingLines.length === 0) {
return;
}
context.report({
node: nextNode,
message: "Unexpected blank line before this statement.",
fix(fixer) {
if (paddingLines.length >= 2) {
return null;
}
const prevToken = paddingLines[0][0];
const nextToken = paddingLines[0][1];
const start = prevToken.range[1];
const end = nextToken.range[0];
const text = context.getSourceCode().text
.slice(start, end)
.replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines);
return fixer.replaceTextRange([start, end], text);
}
});
} | javascript | {
"resource": ""
} |
q18159 | verifyForAlways | train | function verifyForAlways(context, prevNode, nextNode, paddingLines) {
if (paddingLines.length > 0) {
return;
}
context.report({
node: nextNode,
message: "Expected blank line before this statement.",
fix(fixer) {
const sourceCode = context.getSourceCode();
let prevToken = getActualLastToken(sourceCode, prevNode);
const nextToken = sourceCode.getFirstTokenBetween(
prevToken,
nextNode,
{
includeComments: true,
/**
* Skip the trailing comments of the previous node.
* This inserts a blank line after the last trailing comment.
*
* For example:
*
* foo(); // trailing comment.
* // comment.
* bar();
*
* Get fixed to:
*
* foo(); // trailing comment.
*
* // comment.
* bar();
*
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is not a trailing comment.
* @private
*/
filter(token) {
if (astUtils.isTokenOnSameLine(prevToken, token)) {
prevToken = token;
return false;
}
return true;
}
}
) || nextNode;
const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken)
? "\n\n"
: "\n";
return fixer.insertTextAfter(prevToken, insertText);
}
});
} | javascript | {
"resource": ""
} |
q18160 | match | train | function match(node, type) {
let innerStatementNode = node;
while (innerStatementNode.type === "LabeledStatement") {
innerStatementNode = innerStatementNode.body;
}
if (Array.isArray(type)) {
return type.some(match.bind(null, innerStatementNode));
}
return StatementTypes[type].test(innerStatementNode, sourceCode);
} | javascript | {
"resource": ""
} |
q18161 | getPaddingType | train | function getPaddingType(prevNode, nextNode) {
for (let i = configureList.length - 1; i >= 0; --i) {
const configure = configureList[i];
const matched =
match(prevNode, configure.prev) &&
match(nextNode, configure.next);
if (matched) {
return PaddingTypes[configure.blankLine];
}
}
return PaddingTypes.any;
} | javascript | {
"resource": ""
} |
q18162 | getPaddingLineSequences | train | function getPaddingLineSequences(prevNode, nextNode) {
const pairs = [];
let prevToken = getActualLastToken(sourceCode, prevNode);
if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) {
do {
const token = sourceCode.getTokenAfter(
prevToken,
{ includeComments: true }
);
if (token.loc.start.line - prevToken.loc.end.line >= 2) {
pairs.push([prevToken, token]);
}
prevToken = token;
} while (prevToken.range[0] < nextNode.range[0]);
}
return pairs;
} | javascript | {
"resource": ""
} |
q18163 | verify | train | function verify(node) {
const parentType = node.parent.type;
const validParent =
astUtils.STATEMENT_LIST_PARENTS.has(parentType) ||
parentType === "SwitchStatement";
if (!validParent) {
return;
}
// Save this node as the current previous statement.
const prevNode = scopeInfo.prevNode;
// Verify.
if (prevNode) {
const type = getPaddingType(prevNode, node);
const paddingLines = getPaddingLineSequences(prevNode, node);
type.verify(context, prevNode, node, paddingLines);
}
scopeInfo.prevNode = node;
} | javascript | {
"resource": ""
} |
q18164 | checkDotLocation | train | function checkDotLocation(obj, prop, node) {
const dot = sourceCode.getTokenBefore(prop);
const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]);
const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]);
if (dot.type === "Punctuator" && dot.value === ".") {
if (onObject) {
if (!astUtils.isTokenOnSameLine(obj, dot)) {
const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : "";
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotAfterObject",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`)
});
}
} else if (!astUtils.isTokenOnSameLine(dot, prop)) {
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotBeforeProperty",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`)
});
}
}
} | javascript | {
"resource": ""
} |
q18165 | validateStatement | train | function validateStatement(node, keywordName) {
const option = getOption(keywordName);
if (node.type === "BlockStatement" || option === "any") {
return;
}
const tokenBefore = sourceCode.getTokenBefore(node);
if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
context.report({
node,
message: "Expected a linebreak before this statement.",
fix: fixer => fixer.insertTextBefore(node, "\n")
});
} else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
context.report({
node,
message: "Expected no linebreak before this statement.",
fix(fixer) {
if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
return null;
}
return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
}
});
}
} | javascript | {
"resource": ""
} |
q18166 | compareMessagesByFixRange | train | function compareMessagesByFixRange(a, b) {
return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
} | javascript | {
"resource": ""
} |
q18167 | attemptFix | train | function attemptFix(problem) {
const fix = problem.fix;
const start = fix.range[0];
const end = fix.range[1];
// Remain it as a problem if it's overlapped or it's a negative range
if (lastPos >= start || start > end) {
remainingMessages.push(problem);
return false;
}
// Remove BOM.
if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
output = "";
}
// Make output to this fix.
output += text.slice(Math.max(0, lastPos), Math.max(0, start));
output += fix.text;
lastPos = end;
return true;
} | javascript | {
"resource": ""
} |
q18168 | looksLikeExport | train | function looksLikeExport(astNode) {
return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
} | javascript | {
"resource": ""
} |
q18169 | getCommentLineNumbers | train | function getCommentLineNumbers(comments) {
const lines = new Set();
comments.forEach(comment => {
for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
lines.add(i);
}
});
return lines;
} | javascript | {
"resource": ""
} |
q18170 | isOuterVariable | train | function isOuterVariable(variable, reference) {
return (
variable.defs[0].type === "Variable" &&
variable.scope.variableScope !== reference.from.variableScope
);
} | javascript | {
"resource": ""
} |
q18171 | isInRange | train | function isInRange(node, location) {
return node && node.range[0] <= location && location <= node.range[1];
} | javascript | {
"resource": ""
} |
q18172 | isInInitializer | train | function isInInitializer(variable, reference) {
if (variable.scope !== reference.from) {
return false;
}
let node = variable.identifiers[0].parent;
const location = reference.identifier.range[1];
while (node) {
if (node.type === "VariableDeclarator") {
if (isInRange(node.init, location)) {
return true;
}
if (FOR_IN_OF_TYPE.test(node.parent.parent.type) &&
isInRange(node.parent.parent.right, location)
) {
return true;
}
break;
} else if (node.type === "AssignmentPattern") {
if (isInRange(node.right, location)) {
return true;
}
} else if (SENTINEL_TYPE.test(node.type)) {
break;
}
node = node.parent;
}
return false;
} | javascript | {
"resource": ""
} |
q18173 | findVariablesInScope | train | function findVariablesInScope(scope) {
scope.references.forEach(reference => {
const variable = reference.resolved;
/*
* Skips when the reference is:
* - initialization's.
* - referring to an undefined variable.
* - referring to a global environment variable (there're no identifiers).
* - located preceded by the variable (except in initializers).
* - allowed by options.
*/
if (reference.init ||
!variable ||
variable.identifiers.length === 0 ||
(variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) ||
!isForbidden(variable, reference)
) {
return;
}
// Reports.
context.report({
node: reference.identifier,
message: "'{{name}}' was used before it was defined.",
data: reference.identifier
});
});
scope.childScopes.forEach(findVariablesInScope);
} | javascript | {
"resource": ""
} |
q18174 | isLastChild | train | function isLastChild(node) {
const t = node.parent.type;
if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword.
return true;
}
if (t === "DoWhileStatement") { // before `while` keyword.
return true;
}
const nodeList = getChildren(node.parent);
return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc.
} | javascript | {
"resource": ""
} |
q18175 | check | train | function check(semiToken, expected) {
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken);
const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken);
if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) {
context.report({
loc: semiToken.loc,
message: "Expected this semicolon to be at {{pos}}.",
data: {
pos: (expected === "last")
? "the end of the previous line"
: "the beginning of the next line"
},
fix(fixer) {
if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) {
return null;
}
const start = prevToken ? prevToken.range[1] : semiToken.range[0];
const end = nextToken ? nextToken.range[0] : semiToken.range[1];
const text = (expected === "last") ? ";\n" : "\n;";
return fixer.replaceTextRange([start, end], text);
}
});
}
} | javascript | {
"resource": ""
} |
q18176 | ruleApplies | train | function ruleApplies(node) {
if (node.type === "JSXElement" || node.type === "JSXFragment") {
const isSingleLine = node.loc.start.line === node.loc.end.line;
switch (IGNORE_JSX) {
// Exclude this JSX element from linting
case "all":
return false;
// Exclude this JSX element if it is multi-line element
case "multi-line":
return isSingleLine;
// Exclude this JSX element if it is single-line element
case "single-line":
return !isSingleLine;
// Nothing special to be done for JSX elements
case "none":
break;
// no default
}
}
return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
} | javascript | {
"resource": ""
} |
q18177 | isNewExpressionWithParens | train | function isNewExpressionWithParens(newExpression) {
const lastToken = sourceCode.getLastToken(newExpression);
const penultimateToken = sourceCode.getTokenBefore(lastToken);
return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken);
} | javascript | {
"resource": ""
} |
q18178 | requiresLeadingSpace | train | function requiresLeadingSpace(node) {
const leftParenToken = sourceCode.getTokenBefore(node);
const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1);
const firstToken = sourceCode.getFirstToken(node);
return tokenBeforeLeftParen &&
tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
leftParenToken.range[1] === firstToken.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken);
} | javascript | {
"resource": ""
} |
q18179 | requiresTrailingSpace | train | function requiresTrailingSpace(node) {
const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
const rightParenToken = nextTwoTokens[0];
const tokenAfterRightParen = nextTwoTokens[1];
const tokenBeforeRightParen = sourceCode.getLastToken(node);
return rightParenToken && tokenAfterRightParen &&
!sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
!astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
} | javascript | {
"resource": ""
} |
q18180 | doesMemberExpressionContainCallExpression | train | function doesMemberExpressionContainCallExpression(node) {
let currentNode = node.object;
let currentNodeType = node.object.type;
while (currentNodeType === "MemberExpression") {
currentNode = currentNode.object;
currentNodeType = currentNode.type;
}
return currentNodeType === "CallExpression";
} | javascript | {
"resource": ""
} |
q18181 | checkClass | train | function checkClass(node) {
if (!node.superClass) {
return;
}
/*
* If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
* Otherwise, parentheses are needed.
*/
const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
? hasExcessParens(node.superClass)
: hasDoubleExcessParens(node.superClass);
if (hasExtraParens) {
report(node.superClass);
}
} | javascript | {
"resource": ""
} |
q18182 | checkSpreadOperator | train | function checkSpreadOperator(node) {
const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR
? hasExcessParens(node.argument)
: hasDoubleExcessParens(node.argument);
if (hasExtraParens) {
report(node.argument);
}
} | javascript | {
"resource": ""
} |
q18183 | checkExpressionOrExportStatement | train | function checkExpressionOrExportStatement(node) {
const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
if (
astUtils.isOpeningParenToken(firstToken) &&
(
astUtils.isOpeningBraceToken(secondToken) ||
secondToken.type === "Keyword" && (
secondToken.value === "function" ||
secondToken.value === "class" ||
secondToken.value === "let" &&
tokenAfterClosingParens &&
(
astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
tokenAfterClosingParens.type === "Identifier"
)
) ||
secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
)
) {
tokensToIgnore.add(secondToken);
}
if (hasExcessParens(node)) {
report(node);
}
} | javascript | {
"resource": ""
} |
q18184 | checkDestructured | train | function checkDestructured(node) {
if (ignoreDestructuring) {
return;
}
const properties = node.properties;
for (let i = 0; i < properties.length; i++) {
if (properties[i].shorthand) {
continue;
}
/**
* If an ObjectPattern property is computed, we have no idea
* if a rename is useless or not. If an ObjectPattern property
* lacks a key, it is likely an ExperimentalRestProperty and
* so there is no "renaming" occurring here.
*/
if (properties[i].computed || !properties[i].key) {
continue;
}
if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name ||
properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) {
reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment");
}
}
} | javascript | {
"resource": ""
} |
q18185 | checkImport | train | function checkImport(node) {
if (ignoreImport) {
return;
}
if (node.imported.name === node.local.name &&
node.imported.range[0] !== node.local.range[0]) {
reportError(node, node.imported, node.local, "Import");
}
} | javascript | {
"resource": ""
} |
q18186 | checkExport | train | function checkExport(node) {
if (ignoreExport) {
return;
}
if (node.local.name === node.exported.name &&
node.local.range[0] !== node.exported.range[0]) {
reportError(node, node.local, node.exported, "Export");
}
} | javascript | {
"resource": ""
} |
q18187 | checkFunction | train | function checkFunction(node) {
if (node.params.length > numParams) {
context.report({
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
node,
messageId: "exceed",
data: {
name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)),
count: node.params.length,
max: numParams
}
});
}
} | javascript | {
"resource": ""
} |
q18188 | reportBegin | train | function reportBegin(node, message, match, refChar) {
const type = node.type.toLowerCase(),
commentIdentifier = type === "block" ? "/*" : "//";
context.report({
node,
fix(fixer) {
const start = node.range[0];
let end = start + 2;
if (requireSpace) {
if (match) {
end += match[0].length;
}
return fixer.insertTextAfterRange([start, end], " ");
}
end += match[0].length;
return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
},
message,
data: { refChar }
});
} | javascript | {
"resource": ""
} |
q18189 | reportEnd | train | function reportEnd(node, message, match) {
context.report({
node,
fix(fixer) {
if (requireSpace) {
return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
}
const end = node.range[1] - 2,
start = end - match[0].length;
return fixer.replaceTextRange([start, end], "");
},
message
});
} | javascript | {
"resource": ""
} |
q18190 | checkCommentForSpace | train | function checkCommentForSpace(node) {
const type = node.type.toLowerCase(),
rule = styleRules[type],
commentIdentifier = type === "block" ? "/*" : "//";
// Ignores empty comments.
if (node.value.length === 0) {
return;
}
const beginMatch = rule.beginRegex.exec(node.value);
const endMatch = rule.endRegex.exec(node.value);
// Checks.
if (requireSpace) {
if (!beginMatch) {
const hasMarker = rule.markers.exec(node.value);
const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
if (rule.hasExceptions) {
reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker);
} else {
reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker);
}
}
if (balanced && type === "block" && !endMatch) {
reportEnd(node, "Expected space or tab before '*/' in comment.");
}
} else {
if (beginMatch) {
if (!beginMatch[1]) {
reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier);
} else {
reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]);
}
}
if (balanced && type === "block" && endMatch) {
reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch);
}
}
} | javascript | {
"resource": ""
} |
q18191 | isolateBadConfig | train | function isolateBadConfig(text, config, problemType) {
for (const ruleId of Object.keys(config.rules)) {
const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } });
let fixResult;
try {
fixResult = linter.verifyAndFix(text, reducedConfig, {});
} catch (err) {
return reducedConfig;
}
if (fixResult.messages.length === 1 && fixResult.messages[0].fatal && problemType === "autofix") {
return reducedConfig;
}
}
return config;
} | javascript | {
"resource": ""
} |
q18192 | isolateBadAutofixPass | train | function isolateBadAutofixPass(originalText, config) {
let lastGoodText = originalText;
let currentText = originalText;
do {
let messages;
try {
messages = linter.verify(currentText, config);
} catch (err) {
return lastGoodText;
}
if (messages.length === 1 && messages[0].fatal) {
return lastGoodText;
}
lastGoodText = currentText;
currentText = SourceCodeFixer.applyFixes(currentText, messages).output;
} while (lastGoodText !== currentText);
return lastGoodText;
} | javascript | {
"resource": ""
} |
q18193 | getRelativePath | train | function getRelativePath(filepath, baseDir) {
const absolutePath = path.isAbsolute(filepath)
? filepath
: path.resolve(filepath);
if (baseDir) {
if (!path.isAbsolute(baseDir)) {
throw new Error(`baseDir should be an absolute path: ${baseDir}`);
}
return path.relative(baseDir, absolutePath);
}
return absolutePath.replace(/^\//u, "");
} | javascript | {
"resource": ""
} |
q18194 | formatSponsors | train | function formatSponsors(sponsors) {
const nonEmptySponsors = Object.keys(sponsors).filter(tier => sponsors[tier].length > 0);
/* eslint-disable indent*/
return stripIndents`<!--sponsorsstart-->
${
nonEmptySponsors.map(tier => `<h3>${tier[0].toUpperCase()}${tier.slice(1)} Sponsors</h3>
<p>${
sponsors[tier].map(sponsor => `<a href="${sponsor.url}"><img src="${sponsor.image}" alt="${sponsor.name}" height="${heights[tier]}"></a>`).join(" ")
}</p>`).join("")
}
<!--sponsorsend-->`;
/* eslint-enable indent*/
} | javascript | {
"resource": ""
} |
q18195 | computeLineLength | train | function computeLineLength(line, tabWidth) {
let extraCharacterCount = 0;
line.replace(/\t/gu, (match, offset) => {
const totalOffset = offset + extraCharacterCount,
previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
spaceCount = tabWidth - previousTabStopOffset;
extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
});
return Array.from(line).length + extraCharacterCount;
} | javascript | {
"resource": ""
} |
q18196 | stripTrailingComment | train | function stripTrailingComment(line, comment) {
// loc.column is zero-indexed
return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
} | javascript | {
"resource": ""
} |
q18197 | groupByLineNumber | train | function groupByLineNumber(acc, node) {
for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
ensureArrayAndPush(acc, i, node);
}
return acc;
} | javascript | {
"resource": ""
} |
q18198 | checkProgramForMaxLength | train | function checkProgramForMaxLength(node) {
// split (honors line-ending)
const lines = sourceCode.lines,
// list of comments to ignore
comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];
// we iterate over comments in parallel with the lines
let commentsIndex = 0;
const strings = getAllStrings();
const stringsByLine = strings.reduce(groupByLineNumber, {});
const templateLiterals = getAllTemplateLiterals();
const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
const regExpLiterals = getAllRegExpLiterals();
const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
lines.forEach((line, i) => {
// i is zero-indexed, line numbers are one-indexed
const lineNumber = i + 1;
/*
* if we're checking comment length; we need to know whether this
* line is a comment
*/
let lineIsComment = false;
let textToMeasure;
/*
* We can short-circuit the comment checks if we're already out of
* comments to check.
*/
if (commentsIndex < comments.length) {
let comment = null;
// iterate over comments until we find one past the current line
do {
comment = comments[++commentsIndex];
} while (comment && comment.loc.start.line <= lineNumber);
// and step back by one
comment = comments[--commentsIndex];
if (isFullLineComment(line, lineNumber, comment)) {
lineIsComment = true;
textToMeasure = line;
} else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
textToMeasure = stripTrailingComment(line, comment);
} else {
textToMeasure = line;
}
} else {
textToMeasure = line;
}
if (ignorePattern && ignorePattern.test(textToMeasure) ||
ignoreUrls && URL_REGEXP.test(textToMeasure) ||
ignoreStrings && stringsByLine[lineNumber] ||
ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
) {
// ignore this line
return;
}
const lineLength = computeLineLength(textToMeasure, tabWidth);
const commentLengthApplies = lineIsComment && maxCommentLength;
if (lineIsComment && ignoreComments) {
return;
}
if (commentLengthApplies) {
if (lineLength > maxCommentLength) {
context.report({
node,
loc: { line: lineNumber, column: 0 },
messageId: "maxComment",
data: {
lineNumber: i + 1,
maxCommentLength
}
});
}
} else if (lineLength > maxLength) {
context.report({
node,
loc: { line: lineNumber, column: 0 },
messageId: "max",
data: {
lineNumber: i + 1,
maxLength
}
});
}
});
} | javascript | {
"resource": ""
} |
q18199 | isConstant | train | function isConstant(node, name) {
switch (node.type) {
case "Literal":
return node.value === name;
case "TemplateLiteral":
return (
node.expressions.length === 0 &&
node.quasis[0].value.cooked === name
);
default:
return false;
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.