Skip to content
Draft
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
75 changes: 55 additions & 20 deletions tsc/internal/transformers/estransforms/optionalchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>)`. 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 {
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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<T>(...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<string>)?.();
obj.gen<string>?.();
(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)();
(<any>obj?.fn)();
(obj?.gen<string>)();
(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);
}
}
Original file line number Diff line number Diff line change
@@ -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<T>(...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<string>)?.();
obj.gen<string>?.();
(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)();
(<any>obj?.fn)();
(obj?.gen<string>)();
(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?.();
}
}
Original file line number Diff line number Diff line change
@@ -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<T>(...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<string>)?.();
obj.gen<string>?.();
(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)();
(<any>obj?.fn)();
(obj?.gen<string>)();
(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)?.();
}
}