Skip to content

Track parameter references errors in resolve name rather than secondary pass #30349

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 48 additions & 70 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,8 @@ namespace ts {
let lastLocation: Node | undefined;
let lastSelfReferenceLocation: Node | undefined;
let propertyWithInvalidInitializer: Node | undefined;
let associatedDeclarationForContainingInitializer: ParameterDeclaration | BindingElement | undefined;
let withinDeferredContext = false;
const errorLocation = location;
let grandparent: Node;
let isInExternalModule = false;
Expand Down Expand Up @@ -1292,6 +1294,7 @@ namespace ts {
}
}
}
withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
switch (location.kind) {
case SyntaxKind.SourceFile:
if (!isExternalOrCommonJsModule(<SourceFile>location)) break;
Expand Down Expand Up @@ -1480,6 +1483,19 @@ namespace ts {
// js type aliases do not resolve names from their host, so skip past it
location = getJSDocHost(location);
break;
case SyntaxKind.Parameter:
if (lastLocation && lastLocation === (location as ParameterDeclaration).initializer) {
associatedDeclarationForContainingInitializer = location as ParameterDeclaration;
}
break;
case SyntaxKind.BindingElement:
if (lastLocation && lastLocation === (location as BindingElement).initializer) {
const root = getRootDeclaration(location);
if (root.kind === SyntaxKind.Parameter) {
associatedDeclarationForContainingInitializer = location as BindingElement;
}
}
break;
}
if (isSelfReferenceLocation(location)) {
lastSelfReferenceLocation = location;
Expand Down Expand Up @@ -1584,10 +1600,42 @@ namespace ts {
error(errorLocation!, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, unescapeLeadingUnderscores(name)); // TODO: GH#18217
}
}

// If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right
if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & SymbolFlags.Value) === SymbolFlags.Value) {
const candidate = getMergedSymbol(getLateBoundSymbol(result));
const root = (getRootDeclaration(associatedDeclarationForContainingInitializer) as ParameterDeclaration);
// A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) {
error(errorLocation, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, declarationNameToString(associatedDeclarationForContainingInitializer.name));
}
// And it cannot refer to any declarations which come after it
else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
error(errorLocation, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(associatedDeclarationForContainingInitializer.name), declarationNameToString(<Identifier>errorLocation));
}
}
}
return result;
}

function getIsDeferredContext(location: Node, lastLocation: Node | undefined): boolean {
if (location.kind !== SyntaxKind.ArrowFunction && location.kind !== SyntaxKind.FunctionExpression) {
// initializers in instance property declaration of class like entities are executed in constructor and thus deferred
return isTypeQueryNode(location) || ((
isFunctionLikeDeclaration(location) ||
(location.kind === SyntaxKind.PropertyDeclaration && !hasModifier(location, ModifierFlags.Static))
) && (!lastLocation || lastLocation !== (location as FunctionLike | PropertyDeclaration).name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
}
if (lastLocation && lastLocation === (location as FunctionExpression | ArrowFunction).name) {
return false;
}
// generator functions and async functions are not inlined in control flow when immediately invoked
if ((location as FunctionExpression | ArrowFunction).asteriskToken || hasModifier(location, ModifierFlags.Async)) {
return true;
}
return !getImmediatelyInvokedFunctionExpression(location);
}

function isSelfReferenceLocation(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
Expand Down Expand Up @@ -26076,74 +26124,6 @@ namespace ts {
}
}

// Check that a parameter initializer contains no references to parameters declared to the right of itself
function checkParameterInitializer(node: HasExpressionInitializer): void {
if (getRootDeclaration(node).kind !== SyntaxKind.Parameter) {
return;
}

const func = getContainingFunction(node);
visit(node.initializer!);

function visit(n: Node): void {
if (isTypeNode(n) || isDeclarationName(n)) {
// do not dive in types
// skip declaration names (i.e. in object literal expressions)
return;
}
if (n.kind === SyntaxKind.PropertyAccessExpression) {
// skip property names in property access expression
return visit((<PropertyAccessExpression>n).expression);
}
else if (n.kind === SyntaxKind.Identifier) {
// check FunctionLikeDeclaration.locals (stores parameters\function local variable)
// if it contains entry with a specified name
const symbol = resolveName(n, (<Identifier>n).escapedText, SymbolFlags.Value | SymbolFlags.Alias, /*nameNotFoundMessage*/undefined, /*nameArg*/undefined, /*isUse*/ false);
if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) {
return;
}
if (symbol.valueDeclaration === node) {
error(n, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, declarationNameToString(node.name));
return;
}
// locals map for function contain both parameters and function locals
// so we need to do a bit of extra work to check if reference is legal
const enclosingContainer = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
if (enclosingContainer === func) {
if (symbol.valueDeclaration.kind === SyntaxKind.Parameter ||
symbol.valueDeclaration.kind === SyntaxKind.BindingElement) {
// it is ok to reference parameter in initializer if either
// - parameter is located strictly on the left of current parameter declaration
if (symbol.valueDeclaration.pos < node.pos) {
return;
}
// - parameter is wrapped in function-like entity
if (findAncestor(
n,
current => {
if (current === node.initializer) {
return "quit";
}
return isFunctionLike(current.parent) ||
// computed property names/initializers in instance property declaration of class like entities
// are executed in constructor and thus deferred
(current.parent.kind === SyntaxKind.PropertyDeclaration &&
!(hasModifier(current.parent, ModifierFlags.Static)) &&
isClassLike(current.parent.parent));
})) {
return;
}
// fall through to report error
}
error(n, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(node.name), declarationNameToString(<Identifier>n));
}
}
else {
return forEachChild(n, visit);
}
}
}

function convertAutoToAny(type: Type) {
return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
}
Expand Down Expand Up @@ -26220,7 +26200,6 @@ namespace ts {
else {
checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
}
checkParameterInitializer(node);
}
return;
}
Expand All @@ -26237,7 +26216,6 @@ namespace ts {
hasEntries(symbol.exports);
if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) {
checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
checkParameterInitializer(node);
}
}
if (symbol.declarations.length > 1) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
tests/cases/compiler/capturedParametersInInitializers1.ts(18,20): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.
tests/cases/compiler/capturedParametersInInitializers1.ts(22,26): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.
tests/cases/compiler/capturedParametersInInitializers1.ts(38,21): error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.


==== tests/cases/compiler/capturedParametersInInitializers1.ts (3 errors) ====
// ok - usage is deferred
function foo1(y = class {c = x}, x = 1) {
new y().c;
}

// ok - used in file
function foo2(y = function(x: typeof z) {}, z = 1) {

}

// ok -used in type
let a;
function foo3(y = { x: <typeof z>a }, z = 1) {

}

// error - used before declaration
function foo4(y = {z}, z = 1) {
~
!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.
}

// error - used before declaration, IIFEs are inlined
function foo5(y = (() => z)(), z = 1) {
~
!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.
}

// ok - IIFE inside another function
function foo6(y = () => (() => z)(), z = 1) {
}

// ok - used inside immediately invoked generator function
function foo7(y = (function*() {yield z})(), z = 1) {
}

// ok - used inside immediately invoked async function
function foo8(y = (async () => z)(), z = 1) {
}

// error - used as computed name of method
function foo9(y = {[z]() { return z; }}, z = 1) {
~
!!! error TS2373: Initializer of parameter 'y' cannot reference identifier 'z' declared after it.
}

76 changes: 60 additions & 16 deletions tests/baselines/reference/capturedParametersInInitializers1.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,72 @@ function foo2(y = function(x: typeof z) {}, z = 1) {
let a;
function foo3(y = { x: <typeof z>a }, z = 1) {

}
}

// error - used before declaration
function foo4(y = {z}, z = 1) {
}

// error - used before declaration, IIFEs are inlined
function foo5(y = (() => z)(), z = 1) {
}

// ok - IIFE inside another function
function foo6(y = () => (() => z)(), z = 1) {
}

// ok - used inside immediately invoked generator function
function foo7(y = (function*() {yield z})(), z = 1) {
}

// ok - used inside immediately invoked async function
function foo8(y = (async () => z)(), z = 1) {
}

// error - used as computed name of method
function foo9(y = {[z]() { return z; }}, z = 1) {
}


//// [capturedParametersInInitializers1.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
// ok - usage is deferred
function foo1(y, x) {
if (y === void 0) { y = /** @class */ (function () {
function class_1() {
this.c = x;
}
return class_1;
}()); }
if (x === void 0) { x = 1; }
function foo1(y = class {
constructor() {
this.c = x;
}
}, x = 1) {
new y().c;
}
// ok - used in file
function foo2(y, z) {
if (y === void 0) { y = function (x) { }; }
if (z === void 0) { z = 1; }
function foo2(y = function (x) { }, z = 1) {
}
// ok -used in type
var a;
function foo3(y, z) {
if (y === void 0) { y = { x: a }; }
if (z === void 0) { z = 1; }
let a;
function foo3(y = { x: a }, z = 1) {
}
// error - used before declaration
function foo4(y = { z }, z = 1) {
}
// error - used before declaration, IIFEs are inlined
function foo5(y = (() => z)(), z = 1) {
}
// ok - IIFE inside another function
function foo6(y = () => (() => z)(), z = 1) {
}
// ok - used inside immediately invoked generator function
function foo7(y = (function* () { yield z; })(), z = 1) {
}
// ok - used inside immediately invoked async function
function foo8(y = (() => __awaiter(this, void 0, void 0, function* () { return z; }))(), z = 1) {
}
// error - used as computed name of method
function foo9(y = { [z]() { return z; } }, z = 1) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,54 @@ function foo3(y = { x: <typeof z>a }, z = 1) {
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 12, 37))

}

// error - used before declaration
function foo4(y = {z}, z = 1) {
>foo4 : Symbol(foo4, Decl(capturedParametersInInitializers1.ts, 14, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 17, 14))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 17, 19))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 17, 22))
}

// error - used before declaration, IIFEs are inlined
function foo5(y = (() => z)(), z = 1) {
>foo5 : Symbol(foo5, Decl(capturedParametersInInitializers1.ts, 18, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 21, 14))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 21, 30))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 21, 30))
}

// ok - IIFE inside another function
function foo6(y = () => (() => z)(), z = 1) {
>foo6 : Symbol(foo6, Decl(capturedParametersInInitializers1.ts, 22, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 25, 14))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 25, 36))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 25, 36))
}

// ok - used inside immediately invoked generator function
function foo7(y = (function*() {yield z})(), z = 1) {
>foo7 : Symbol(foo7, Decl(capturedParametersInInitializers1.ts, 26, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 29, 14))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 29, 44))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 29, 44))
}

// ok - used inside immediately invoked async function
function foo8(y = (async () => z)(), z = 1) {
>foo8 : Symbol(foo8, Decl(capturedParametersInInitializers1.ts, 30, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 33, 14))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 33, 36))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 33, 36))
}

// error - used as computed name of method
function foo9(y = {[z]() { return z; }}, z = 1) {
>foo9 : Symbol(foo9, Decl(capturedParametersInInitializers1.ts, 34, 1))
>y : Symbol(y, Decl(capturedParametersInInitializers1.ts, 37, 14))
>[z] : Symbol([z], Decl(capturedParametersInInitializers1.ts, 37, 19))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40))
>z : Symbol(z, Decl(capturedParametersInInitializers1.ts, 37, 40))
}

Loading