Skip to content

Commit

Permalink
Fix completion record for variable declarations (babel#13596)
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax authored and nicolo-ribaudo committed Jul 30, 2021
1 parent ee696b9 commit cd3aeac
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 5 deletions.
18 changes: 13 additions & 5 deletions packages/babel-traverse/src/path/family.ts
Expand Up @@ -193,11 +193,19 @@ function getStatementListCompletion(
}
} else if (paths.length) {
// When we are in a context where `break` must not exist, we can skip linear
// search on statement lists and assume that the last statement determines
// the completion
completions = completions.concat(
_getCompletionRecords(paths[paths.length - 1], context),
);
// search on statement lists and assume that the last
// non-variable-declaration statement determines the completion.
for (let i = paths.length - 1; i >= 0; i--) {
const pathCompletions = _getCompletionRecords(paths[i], context);
if (
pathCompletions.length > 1 ||
(pathCompletions.length === 1 &&
!pathCompletions[0].path.isVariableDeclaration())
) {
completions = completions.concat(pathCompletions);
break;
}
}
}
return completions;
}
Expand Down
38 changes: 38 additions & 0 deletions packages/babel-traverse/test/family.js
Expand Up @@ -109,6 +109,44 @@ describe("path/family", function () {
expect(consequentHasScope).toBe(true);
});
});
describe("getCompletionRecords", function () {
it("should skip variable declarations", function () {
const ast = parse("'foo' + 'bar'; var a = 10; let b = 20; const c = 30;");
let records = [];
traverse(ast, {
Program(path) {
records = path.getCompletionRecords();
},
});
expect(records).toHaveLength(1);
expect(records[0].node.type).toBe("ExpressionStatement");
expect(records[0].node.expression.type).toBe("BinaryExpression");
});

it("should skip variable declarations in a BlockStatement", function () {
const ast = parse("'foo' + 'bar'; { var a = 10; }");
let records = [];
traverse(ast, {
Program(path) {
records = path.getCompletionRecords();
},
});
expect(records).toHaveLength(1);
expect(records[0].node.type).toBe("ExpressionStatement");
expect(records[0].node.expression.type).toBe("BinaryExpression");
});

it("should be empty if there are only variable declarations", function () {
const ast = parse("var a = 10; let b = 20; const c = 30;");
let records = [];
traverse(ast, {
Program(path) {
records = path.getCompletionRecords();
},
});
expect(records).toHaveLength(0);
});
});
});

function hop(o, key) {
Expand Down

0 comments on commit cd3aeac

Please sign in to comment.