diff --git a/tsc/internal/transformers/estransforms/optionalchain.go b/tsc/internal/transformers/estransforms/optionalchain.go index 33b269280f594..39eef6b2de187 100644 --- a/tsc/internal/transformers/estransforms/optionalchain.go +++ b/tsc/internal/transformers/estransforms/optionalchain.go @@ -26,45 +26,78 @@ func (ch *optionalChainTransformer) visit(node *ast.Node) *ast.Node { return ch.Visitor().VisitEachChild(node) case ast.KindDeleteExpression: return ch.visitDeleteExpression(node.AsDeleteExpression()) + case ast.KindTaggedTemplateExpression: + return ch.visitTaggedTemplateExpression(node.AsTaggedTemplateExpression()) default: return ch.Visitor().VisitEachChild(node) } } +// Determines whether `node` is an optional chain wrapped in parentheses or erased type syntax, such as +// `(a?.b)`, `(a?.b!)`, `(a?.b as T)`, or `(a?.b)`. Calling such an expression, or using it as a +// template tag, must preserve the `this` binding of the inner property or element access. +func isWrappedOptionalChain(node *ast.Expression) bool { + unwrapped := ast.SkipOuterExpressions(node, ast.OEKAll) + return unwrapped != node && unwrapped.Flags&ast.NodeFlagsOptionalChain != 0 +} + func (ch *optionalChainTransformer) visitCallExpression(node *ast.CallExpression, captureThisArg bool) *ast.Node { if node.Flags&ast.NodeFlagsOptionalChain != 0 { // If `node` is an optional chain, then it is the outermost chain of an optional expression. return ch.visitOptionalExpression(node.AsNode(), captureThisArg, false) } - if ast.IsParenthesizedExpression(node.Expression) { - unwrapped := ast.SkipParentheses(node.Expression) - if unwrapped.Flags&ast.NodeFlagsOptionalChain != 0 { - // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` - expression := ch.visitParenthesizedExpression(node.Expression.AsParenthesizedExpression(), true, false) - args := ch.Visitor().VisitNodes(node.Arguments) - if ast.IsSyntheticReferenceExpression(expression) { - res := ch.Factory().NewFunctionCallCall(expression.AsSyntheticReferenceExpression().Expression, expression.AsSyntheticReferenceExpression().ThisArg, args.Nodes) - res.Loc = node.Loc - ch.EmitContext().SetOriginal(res, node.AsNode()) - return res - } - return ch.Factory().UpdateCallExpression(node, expression, nil /*questionDotToken*/, nil /*typeArguments*/, args, node.Flags) + if isWrappedOptionalChain(node.Expression) { + // capture thisArg for calls of parenthesized optional chains like `(foo?.bar)()` + expression := ch.visitNonOptionalExpression(node.Expression, true, false) + args := ch.Visitor().VisitNodes(node.Arguments) + if ast.IsSyntheticReferenceExpression(expression) { + res := ch.Factory().NewFunctionCallCall(expression.AsSyntheticReferenceExpression().Expression, expression.AsSyntheticReferenceExpression().ThisArg, args.Nodes) + res.Loc = node.Loc + ch.EmitContext().SetOriginal(res, node.AsNode()) + return res + } + return ch.Factory().UpdateCallExpression(node, expression, nil /*questionDotToken*/, nil /*typeArguments*/, args, node.Flags) + } + return ch.Visitor().VisitEachChild(node.AsNode()) +} + +func (ch *optionalChainTransformer) visitTaggedTemplateExpression(node *ast.TaggedTemplateExpression) *ast.Node { + if node.Flags&ast.NodeFlagsOptionalChain == 0 && isWrappedOptionalChain(node.Tag) { + // capture thisArg for tags of parenthesized optional chains like ``(foo?.bar)`x` `` + tag := ch.visitNonOptionalExpression(node.Tag, true, false) + if ast.IsSyntheticReferenceExpression(tag) { + synth := tag.AsSyntheticReferenceExpression() + tag = ch.Factory().NewFunctionBindCall(synth.Expression, synth.ThisArg, nil) } + return ch.Factory().UpdateTaggedTemplateExpression(node, tag, nil /*questionDotToken*/, nil /*typeArguments*/, ch.Visitor().VisitNode(node.Template), node.Flags) } return ch.Visitor().VisitEachChild(node.AsNode()) } -func (ch *optionalChainTransformer) visitParenthesizedExpression(node *ast.ParenthesizedExpression, captureThisArg bool, isDelete bool) *ast.Node { - expr := ch.visitNonOptionalExpression(node.Expression, captureThisArg, isDelete) +func (ch *optionalChainTransformer) visitOuterExpression(node *ast.Expression, captureThisArg bool, isDelete bool) *ast.Node { + expr := ch.visitNonOptionalExpression(node.Expression(), captureThisArg, isDelete) if ast.IsSyntheticReferenceExpression(expr) { // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` } // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` } synth := expr.AsSyntheticReferenceExpression() - res := ch.Factory().NewSyntheticReferenceExpression(ch.Factory().UpdateParenthesizedExpression(node, synth.Expression), synth.ThisArg) - ch.EmitContext().SetOriginal(res, node.AsNode()) + res := ch.Factory().NewSyntheticReferenceExpression(ch.updateOuterExpression(node, synth.Expression), synth.ThisArg) + ch.EmitContext().SetOriginal(res, node) return res } - return ch.Factory().UpdateParenthesizedExpression(node, expr) + return ch.updateOuterExpression(node, expr) +} + +func (ch *optionalChainTransformer) updateOuterExpression(node *ast.Expression, expression *ast.Expression) *ast.Expression { + switch node.Kind { + case ast.KindParenthesizedExpression: + return ch.Factory().UpdateParenthesizedExpression(node.AsParenthesizedExpression(), expression) + case ast.KindPartiallyEmittedExpression: + return ch.Factory().UpdatePartiallyEmittedExpression(node.AsPartiallyEmittedExpression(), expression) + case ast.KindExpressionWithTypeArguments: + return ch.Factory().UpdateExpressionWithTypeArguments(node.AsExpressionWithTypeArguments(), expression, ch.Visitor().VisitNodes(node.TypeArgumentList())) + default: + panic("Unexpected outer expression kind: " + node.Kind.String()) + } } func (ch *optionalChainTransformer) visitPropertyOrElementAccessExpression(node *ast.Expression, captureThisArg bool, isDelete bool) *ast.Expression { @@ -112,8 +145,10 @@ func (ch *optionalChainTransformer) visitDeleteExpression(node *ast.DeleteExpres func (ch *optionalChainTransformer) visitNonOptionalExpression(node *ast.Expression, captureThisArg bool, isDelete bool) *ast.Expression { switch node.Kind { - case ast.KindParenthesizedExpression: - return ch.visitParenthesizedExpression(node.AsParenthesizedExpression(), captureThisArg, isDelete) + case ast.KindParenthesizedExpression, + ast.KindPartiallyEmittedExpression, + ast.KindExpressionWithTypeArguments: + return ch.visitOuterExpression(node, captureThisArg, isDelete) case ast.KindElementAccessExpression, ast.KindPropertyAccessExpression: return ch.visitPropertyOrElementAccessExpression(node, captureThisArg, isDelete) case ast.KindCallExpression: diff --git a/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2019).js b/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2019).js new file mode 100644 index 0000000000000..5db43d6a1ebb0 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2019).js @@ -0,0 +1,91 @@ +//// [tests/cases/compiler/optionalChainThisArgWithOuterExpressions.ts] //// + +//// [optionalChainThisArgWithOuterExpressions.ts] +// https://github.com/microsoft/TypeScript/issues/65597 + +interface Fns { + fn(...args: unknown[]): unknown; + gen(...args: unknown[]): T; +} + +declare const obj: Fns & { nested: Fns }; + +// optional calls of wrapped callees +(obj?.fn!)?.(); +(obj.fn!)?.(); +(obj?.fn as any)?.(); +(obj.fn as any)?.(); +(obj.gen)?.(); +obj.gen?.(); +(obj?.["fn"]!)?.(1); +(obj.nested?.fn!)?.(1); + +// plain calls of wrapped optional chains +(obj?.fn)(); +(obj?.fn!)(); +(obj?.fn as any)(); +(obj?.fn)!(); +(obj?.fn satisfies unknown)(); +(obj?.fn)(); +(obj?.gen)(); +(obj?.["fn"]!)(1); +(obj.nested?.fn!)(1); + +// tagged templates with wrapped optional chain tags +(obj?.fn)`x`; +(obj?.["fn"])`x${1}`; +(obj?.fn!)`x`; +(obj?.fn as any)`x`; +(obj.nested?.fn)`x`; + +class Base { + fn(...args: unknown[]): unknown { return this; } +} + +class Derived extends Base { + method() { + (super.fn!)?.(); + (super.fn as any)?.(); + } +} + + +//// [optionalChainThisArgWithOuterExpressions.js] +"use strict"; +// https://github.com/microsoft/TypeScript/issues/65597 +var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; +// optional calls of wrapped callees +(_a = (obj === null || obj === void 0 ? void 0 : obj.fn)) === null || _a === void 0 ? void 0 : _a.call(obj); +(_b = (obj.fn)) === null || _b === void 0 ? void 0 : _b.call(obj); +(_c = obj === null || obj === void 0 ? void 0 : obj.fn) === null || _c === void 0 ? void 0 : _c.call(obj); +(_d = obj.fn) === null || _d === void 0 ? void 0 : _d.call(obj); +(_e = (obj.gen)) === null || _e === void 0 ? void 0 : _e.call(obj); +(_f = obj.gen) === null || _f === void 0 ? void 0 : _f.call(obj); +(_g = (obj === null || obj === void 0 ? void 0 : obj["fn"])) === null || _g === void 0 ? void 0 : _g.call(obj, 1); +(_j = ((_h = obj.nested) === null || _h === void 0 ? void 0 : _h.fn)) === null || _j === void 0 ? void 0 : _j.call(_h, 1); +// plain calls of wrapped optional chains +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +(obj === null || obj === void 0 ? void 0 : obj.fn).call(obj); +((obj === null || obj === void 0 ? void 0 : obj.gen)).call(obj); +(obj === null || obj === void 0 ? void 0 : obj["fn"]).call(obj, 1); +((_k = obj.nested) === null || _k === void 0 ? void 0 : _k.fn).call(_k, 1); +// tagged templates with wrapped optional chain tags +(obj === null || obj === void 0 ? void 0 : obj.fn).bind(obj) `x`; +(obj === null || obj === void 0 ? void 0 : obj["fn"]).bind(obj) `x${1}`; +(obj === null || obj === void 0 ? void 0 : obj.fn).bind(obj) `x`; +(obj === null || obj === void 0 ? void 0 : obj.fn).bind(obj) `x`; +((_l = obj.nested) === null || _l === void 0 ? void 0 : _l.fn).bind(_l) `x`; +class Base { + fn(...args) { return this; } +} +class Derived extends Base { + method() { + var _a, _b; + (_a = (super.fn)) === null || _a === void 0 ? void 0 : _a.call(this); + (_b = super.fn) === null || _b === void 0 ? void 0 : _b.call(this); + } +} diff --git a/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2020).js b/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2020).js new file mode 100644 index 0000000000000..0df9b445e6b9e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/optionalChainThisArgWithOuterExpressions(target=es2020).js @@ -0,0 +1,89 @@ +//// [tests/cases/compiler/optionalChainThisArgWithOuterExpressions.ts] //// + +//// [optionalChainThisArgWithOuterExpressions.ts] +// https://github.com/microsoft/TypeScript/issues/65597 + +interface Fns { + fn(...args: unknown[]): unknown; + gen(...args: unknown[]): T; +} + +declare const obj: Fns & { nested: Fns }; + +// optional calls of wrapped callees +(obj?.fn!)?.(); +(obj.fn!)?.(); +(obj?.fn as any)?.(); +(obj.fn as any)?.(); +(obj.gen)?.(); +obj.gen?.(); +(obj?.["fn"]!)?.(1); +(obj.nested?.fn!)?.(1); + +// plain calls of wrapped optional chains +(obj?.fn)(); +(obj?.fn!)(); +(obj?.fn as any)(); +(obj?.fn)!(); +(obj?.fn satisfies unknown)(); +(obj?.fn)(); +(obj?.gen)(); +(obj?.["fn"]!)(1); +(obj.nested?.fn!)(1); + +// tagged templates with wrapped optional chain tags +(obj?.fn)`x`; +(obj?.["fn"])`x${1}`; +(obj?.fn!)`x`; +(obj?.fn as any)`x`; +(obj.nested?.fn)`x`; + +class Base { + fn(...args: unknown[]): unknown { return this; } +} + +class Derived extends Base { + method() { + (super.fn!)?.(); + (super.fn as any)?.(); + } +} + + +//// [optionalChainThisArgWithOuterExpressions.js] +"use strict"; +// https://github.com/microsoft/TypeScript/issues/65597 +// optional calls of wrapped callees +(obj?.fn)?.(); +(obj.fn)?.(); +obj?.fn?.(); +obj.fn?.(); +(obj.gen)?.(); +obj.gen?.(); +(obj?.["fn"])?.(1); +(obj.nested?.fn)?.(1); +// plain calls of wrapped optional chains +(obj?.fn)(); +(obj?.fn)(); +(obj?.fn)(); +(obj?.fn)(); +(obj?.fn)(); +(obj?.fn)(); +((obj?.gen))(); +(obj?.["fn"])(1); +(obj.nested?.fn)(1); +// tagged templates with wrapped optional chain tags +(obj?.fn) `x`; +(obj?.["fn"]) `x${1}`; +(obj?.fn) `x`; +(obj?.fn) `x`; +(obj.nested?.fn) `x`; +class Base { + fn(...args) { return this; } +} +class Derived extends Base { + method() { + (super.fn)?.(); + super.fn?.(); + } +} diff --git a/tsc/testdata/tests/cases/compiler/optionalChainThisArgWithOuterExpressions.ts b/tsc/testdata/tests/cases/compiler/optionalChainThisArgWithOuterExpressions.ts new file mode 100644 index 0000000000000..ed8015c3a6e3b --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/optionalChainThisArgWithOuterExpressions.ts @@ -0,0 +1,51 @@ +// @target: es2019,es2020 +// @strict: true +// @noTypesAndSymbols: true + +// https://github.com/microsoft/TypeScript/issues/65597 + +interface Fns { + fn(...args: unknown[]): unknown; + gen(...args: unknown[]): T; +} + +declare const obj: Fns & { nested: Fns }; + +// optional calls of wrapped callees +(obj?.fn!)?.(); +(obj.fn!)?.(); +(obj?.fn as any)?.(); +(obj.fn as any)?.(); +(obj.gen)?.(); +obj.gen?.(); +(obj?.["fn"]!)?.(1); +(obj.nested?.fn!)?.(1); + +// plain calls of wrapped optional chains +(obj?.fn)(); +(obj?.fn!)(); +(obj?.fn as any)(); +(obj?.fn)!(); +(obj?.fn satisfies unknown)(); +(obj?.fn)(); +(obj?.gen)(); +(obj?.["fn"]!)(1); +(obj.nested?.fn!)(1); + +// tagged templates with wrapped optional chain tags +(obj?.fn)`x`; +(obj?.["fn"])`x${1}`; +(obj?.fn!)`x`; +(obj?.fn as any)`x`; +(obj.nested?.fn)`x`; + +class Base { + fn(...args: unknown[]): unknown { return this; } +} + +class Derived extends Base { + method() { + (super.fn!)?.(); + (super.fn as any)?.(); + } +}