Skip to content

Commit

Permalink
Track JSX presence per-function, fixing some false negatives (#830)
Browse files Browse the repository at this point in the history
Co-authored-by: fisker <lionkay@gmail.com>
  • Loading branch information
willheslam and fisker committed Sep 27, 2020
1 parent e29d7c0 commit 85d424c
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 9 deletions.
17 changes: 8 additions & 9 deletions rules/consistent-function-scoping.js
Expand Up @@ -153,17 +153,21 @@ const create = context => {
const {scopeManager} = sourceCode;

const functions = [];
let hasJsx = false;

return {
'ArrowFunctionExpression, FunctionDeclaration': node => functions.push(node),
'ArrowFunctionExpression, FunctionDeclaration': () => {
functions.push(false);
},
JSXElement: () => {
// Turn off this rule if we see a JSX element because scope
// references does not include JSXElement nodes.
hasJsx = true;
if (functions.length !== 0) {
functions[functions.length - 1] = true;
}
},
':matches(ArrowFunctionExpression, FunctionDeclaration):exit': node => {
if (!hasJsx && !checkNode(node, scopeManager)) {
const currentFunctionHasJsx = functions.pop();
if (!currentFunctionHasJsx && !checkNode(node, scopeManager)) {
context.report({
node,
loc: getFunctionHeadLocation(node, sourceCode),
Expand All @@ -173,11 +177,6 @@ const create = context => {
}
});
}

functions.pop();
if (functions.length === 0) {
hasJsx = false;
}
}
};
};
Expand Down
68 changes: 68 additions & 0 deletions test/consistent-function-scoping.js
Expand Up @@ -192,6 +192,32 @@ ruleTester.run('consistent-function-scoping', rule, {
return Bar;
};
`,
outdent`
const foo = <JSX/>;
`,
// Functions that could be extracted are conservatively ignored due to JSX masking references
outdent`
function Foo() {
function Bar () {
return <div />
}
return <div>{ Bar() }</div>
}
`,
outdent`
function foo() {
function bar() {
return <JSX a={foo()}/>;
}
}
`,
outdent`
function foo() {
function bar() {
return <JSX/>;
}
}
`,
// `this`
outdent`
function doFoo(Foo) {
Expand Down Expand Up @@ -594,6 +620,48 @@ ruleTester.run('consistent-function-scoping', rule, {
)
`,
errors: [createError('function \'baz\'')]
},
{
code: outdent`
function Foo() {
const Bar = <div />
function doBaz() {
return 42
}
return <div>{ doBaz() }</div>
}
`,
errors: [createError('function \'doBaz\'')]
},
{
code: outdent`
function Foo() {
function Bar () {
return <div />
}
function doBaz() {
return 42
}
return <div>{ doBaz() }</div>
}
`,
errors: [createError('function \'doBaz\'')]
},
// JSX
{
code: outdent`
function fn1() {
function a() {
return <JSX a={b()}/>;
}
function b() {}
function c() {}
}
function fn2() {
function foo() {}
}
`,
errors: ['b', 'c', 'foo'].map(functionName => createError(`function '${functionName}'`))
}
]
});
Expand Down

0 comments on commit 85d424c

Please sign in to comment.