Skip to content

Commit 711b4e7

Browse files
authored
Indirect calls for imported functions (#44624)
* Indirect calls for imported functions * Fix unit tests
1 parent fafe3ff commit 711b4e7

File tree

177 files changed

+460
-311
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

177 files changed

+460
-311
lines changed

Diff for: src/compiler/emitter.ts

+20
Original file line numberDiff line numberDiff line change
@@ -2473,7 +2473,17 @@ namespace ts {
24732473
}
24742474

24752475
function emitCallExpression(node: CallExpression) {
2476+
const indirectCall = getEmitFlags(node) & EmitFlags.IndirectCall;
2477+
if (indirectCall) {
2478+
writePunctuation("(");
2479+
writeLiteral("0");
2480+
writePunctuation(",");
2481+
writeSpace();
2482+
}
24762483
emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess);
2484+
if (indirectCall) {
2485+
writePunctuation(")");
2486+
}
24772487
emit(node.questionDotToken);
24782488
emitTypeArguments(node, node.typeArguments);
24792489
emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments, parenthesizer.parenthesizeExpressionForDisallowedComma);
@@ -2488,7 +2498,17 @@ namespace ts {
24882498
}
24892499

24902500
function emitTaggedTemplateExpression(node: TaggedTemplateExpression) {
2501+
const indirectCall = getEmitFlags(node) & EmitFlags.IndirectCall;
2502+
if (indirectCall) {
2503+
writePunctuation("(");
2504+
writeLiteral("0");
2505+
writePunctuation(",");
2506+
writeSpace();
2507+
}
24912508
emitExpression(node.tag, parenthesizer.parenthesizeLeftSideOfAccess);
2509+
if (indirectCall) {
2510+
writePunctuation(")");
2511+
}
24922512
emitTypeArguments(node, node.typeArguments);
24932513
writeSpace();
24942514
emitExpression(node.template);

Diff for: src/compiler/transformers/module/module.ts

+43
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ namespace ts {
3333
const previousOnEmitNode = context.onEmitNode;
3434
context.onSubstituteNode = onSubstituteNode;
3535
context.onEmitNode = onEmitNode;
36+
context.enableSubstitution(SyntaxKind.CallExpression); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
37+
context.enableSubstitution(SyntaxKind.TaggedTemplateExpression); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
3638
context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers with imported/exported symbols.
3739
context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols.
3840
context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); // Substitutes updates to exported symbols.
@@ -1741,6 +1743,10 @@ namespace ts {
17411743
switch (node.kind) {
17421744
case SyntaxKind.Identifier:
17431745
return substituteExpressionIdentifier(node as Identifier);
1746+
case SyntaxKind.CallExpression:
1747+
return substituteCallExpression(node as CallExpression);
1748+
case SyntaxKind.TaggedTemplateExpression:
1749+
return substituteTaggedTemplateExpression(node as TaggedTemplateExpression);
17441750
case SyntaxKind.BinaryExpression:
17451751
return substituteBinaryExpression(node as BinaryExpression);
17461752
case SyntaxKind.PostfixUnaryExpression:
@@ -1751,6 +1757,43 @@ namespace ts {
17511757
return node;
17521758
}
17531759

1760+
function substituteCallExpression(node: CallExpression) {
1761+
if (isIdentifier(node.expression)) {
1762+
const expression = substituteExpressionIdentifier(node.expression);
1763+
noSubstitution[getNodeId(expression)] = true;
1764+
if (!isIdentifier(expression)) {
1765+
return addEmitFlags(
1766+
factory.updateCallExpression(node,
1767+
expression,
1768+
/*typeArguments*/ undefined,
1769+
node.arguments
1770+
),
1771+
EmitFlags.IndirectCall
1772+
);
1773+
1774+
}
1775+
}
1776+
return node;
1777+
}
1778+
1779+
function substituteTaggedTemplateExpression(node: TaggedTemplateExpression) {
1780+
if (isIdentifier(node.tag)) {
1781+
const tag = substituteExpressionIdentifier(node.tag);
1782+
noSubstitution[getNodeId(tag)] = true;
1783+
if (!isIdentifier(tag)) {
1784+
return addEmitFlags(
1785+
factory.updateTaggedTemplateExpression(node,
1786+
tag,
1787+
/*typeArguments*/ undefined,
1788+
node.template
1789+
),
1790+
EmitFlags.IndirectCall
1791+
);
1792+
}
1793+
}
1794+
return node;
1795+
}
1796+
17541797
/**
17551798
* Substitution for an Identifier expression that may contain an imported or exported
17561799
* symbol.

Diff for: src/compiler/types.ts

+1
Original file line numberDiff line numberDiff line change
@@ -6732,6 +6732,7 @@ namespace ts {
67326732
/*@internal*/ NeverApplyImportHelper = 1 << 26, // Indicates the node should never be wrapped with an import star helper (because, for example, it imports tslib itself)
67336733
/*@internal*/ IgnoreSourceNewlines = 1 << 27, // Overrides `printerOptions.preserveSourceNewlines` to print this node (and all descendants) with default whitespace.
67346734
/*@internal*/ Immutable = 1 << 28, // Indicates a node is a singleton intended to be reused in multiple locations. Any attempt to make further changes to the node will result in an error.
6735+
/*@internal*/ IndirectCall = 1 << 29, // Emit CallExpression as an indirect call: `(0, f)()`
67356736
}
67366737

67376738
export interface EmitHelperBase {

Diff for: src/testRunner/tsconfig.json

+1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
"unittests/evaluation/asyncGenerator.ts",
9494
"unittests/evaluation/awaiter.ts",
9595
"unittests/evaluation/destructuring.ts",
96+
"unittests/evaluation/externalModules.ts",
9697
"unittests/evaluation/forAwaitOf.ts",
9798
"unittests/evaluation/forOf.ts",
9899
"unittests/evaluation/optionalCall.ts",
+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
describe("unittests:: evaluation:: externalModules", () => {
2+
// https://github.com/microsoft/TypeScript/issues/35420
3+
it("Correct 'this' in function exported from external module", async () => {
4+
const result = evaluator.evaluateTypeScript({
5+
files: {
6+
"/.src/output.ts": `
7+
export const output: any[] = [];
8+
`,
9+
"/.src/other.ts": `
10+
import { output } from "./output";
11+
export function f(this: any, expected) {
12+
output.push(this === expected);
13+
}
14+
15+
// 0
16+
f(undefined);
17+
`,
18+
"/.src/main.ts": `
19+
export { output } from "./output";
20+
import { output } from "./output";
21+
import { f } from "./other";
22+
import * as other from "./other";
23+
24+
// 1
25+
f(undefined);
26+
27+
// 2
28+
const obj = {};
29+
f.call(obj, obj);
30+
31+
// 3
32+
other.f(other);
33+
`
34+
},
35+
rootFiles: ["/.src/main.ts"],
36+
main: "/.src/main.ts"
37+
});
38+
assert.equal(result.output[0], true); // `f(undefined)` inside module. Existing behavior is correct.
39+
assert.equal(result.output[1], true); // `f(undefined)` from import. New behavior to match first case.
40+
assert.equal(result.output[2], true); // `f.call(obj, obj)`. Behavior of `.call` (or `.apply`, etc.) should not be affected.
41+
assert.equal(result.output[3], true); // `other.f(other)`. `this` is still namespace because it is left of `.`.
42+
});
43+
44+
it("Correct 'this' in function expression exported from external module", async () => {
45+
const result = evaluator.evaluateTypeScript({
46+
files: {
47+
"/.src/output.ts": `
48+
export const output: any[] = [];
49+
`,
50+
"/.src/other.ts": `
51+
import { output } from "./output";
52+
export const f = function(this: any, expected) {
53+
output.push(this === expected);
54+
}
55+
56+
// 0
57+
f(undefined);
58+
`,
59+
"/.src/main.ts": `
60+
export { output } from "./output";
61+
import { output } from "./output";
62+
import { f } from "./other";
63+
import * as other from "./other";
64+
65+
// 1
66+
f(undefined);
67+
68+
// 2
69+
const obj = {};
70+
f.call(obj, obj);
71+
72+
// 3
73+
other.f(other);
74+
`
75+
},
76+
rootFiles: ["/.src/main.ts"],
77+
main: "/.src/main.ts"
78+
});
79+
assert.equal(result.output[0], true); // `f(undefined)` inside module. Existing behavior is incorrect.
80+
assert.equal(result.output[1], true); // `f(undefined)` from import. New behavior to match first case.
81+
assert.equal(result.output[2], true); // `f.call(obj, obj)`. Behavior of `.call` (or `.apply`, etc.) should not be affected.
82+
assert.equal(result.output[3], true); // `other.f(other)`. `this` is still namespace because it is left of `.`.
83+
});
84+
});

Diff for: src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ exports.fn3 = fn3;`;
5555
content: `"use strict";
5656
exports.__esModule = true;${appendJsText === changeJs ? "\nexports.fn3 = void 0;" : ""}
5757
var fns_1 = require("../decls/fns");
58-
fns_1.fn1();
59-
fns_1.fn2();
58+
(0, fns_1.fn1)();
59+
(0, fns_1.fn2)();
6060
${appendJs}`
6161
}];
6262
}

Diff for: tests/baselines/reference/allowJscheckJsTypeParameterNoCrash.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ exports.__esModule = true;
3030
exports.a = void 0;
3131
var func_1 = require("./func");
3232
// hover on vextend
33-
exports.a = func_1.vextend({
33+
exports.a = (0, func_1.vextend)({
3434
watch: {
3535
data1: function (val) {
3636
this.data2 = 1;

Diff for: tests/baselines/reference/allowSyntheticDefaultImportsCanPaintCrossModuleDeclaration.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ exports.__esModule = true;
2323
exports.__esModule = true;
2424
exports.A = void 0;
2525
var file1_1 = require("./file1");
26-
exports.A = file1_1.styled();
26+
exports.A = (0, file1_1.styled)();
2727

2828

2929
//// [color.d.ts]

Diff for: tests/baselines/reference/ambientDeclarationsPatterns.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ foo(fileText);
3737
exports.__esModule = true;
3838
///<reference path="declarations.d.ts" />
3939
var foobarbaz_1 = require("foobarbaz");
40-
foobarbaz_1.foo(foobarbaz_1.baz);
40+
(0, foobarbaz_1.foo)(foobarbaz_1.baz);
4141
var foosball_1 = require("foosball");
42-
foobarbaz_1.foo(foosball_1.foos);
42+
(0, foobarbaz_1.foo)(foosball_1.foos);
4343
// Works with relative file name
4444
var file_text_1 = require("./file!text");
45-
foobarbaz_1.foo(file_text_1["default"]);
45+
(0, foobarbaz_1.foo)(file_text_1["default"]);

Diff for: tests/baselines/reference/ambientShorthand.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,4 @@ exports.__esModule = true;
2020
var jquery_1 = require("jquery");
2121
var baz = require("fs");
2222
var boom = require("jquery");
23-
jquery_1["default"](jquery_1.bar, baz, boom);
23+
(0, jquery_1["default"])(jquery_1.bar, baz, boom);

Diff for: tests/baselines/reference/ambientShorthand_reExport.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,4 @@ exports.__esModule = true;
4949
var reExportX_1 = require("./reExportX");
5050
var $ = require("./reExportAll");
5151
// '$' is not callable, it is an object.
52-
reExportX_1.x($);
52+
(0, reExportX_1.x)($);

Diff for: tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ define("Class", ["require", "exports", "Configurable"], function (require, expor
7272
return _super !== null && _super.apply(this, arguments) || this;
7373
}
7474
return ActualClass;
75-
}(Configurable_1.Configurable(HiddenClass)));
75+
}((0, Configurable_1.Configurable)(HiddenClass)));
7676
exports.ActualClass = ActualClass;
7777
});
7878

Diff for: tests/baselines/reference/anonClassDeclarationEmitIsAnon.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ var __extends = (this && this.__extends) || (function () {
9696
exports.__esModule = true;
9797
exports.TimestampedUser = exports.User = void 0;
9898
var wrapClass_1 = require("./wrapClass");
99-
exports["default"] = wrapClass_1.wrapClass(0);
99+
exports["default"] = (0, wrapClass_1.wrapClass)(0);
100100
// Simple class
101101
var User = /** @class */ (function () {
102102
function User() {
@@ -112,7 +112,7 @@ var TimestampedUser = /** @class */ (function (_super) {
112112
return _super.call(this) || this;
113113
}
114114
return TimestampedUser;
115-
}(wrapClass_1.Timestamped(User)));
115+
}((0, wrapClass_1.Timestamped)(User)));
116116
exports.TimestampedUser = TimestampedUser;
117117

118118

Diff for: tests/baselines/reference/callbackTagVariadicType.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ exports.x = void 0;
2222
/** @type {Foo} */
2323
var x = function () { return 1; };
2424
exports.x = x;
25-
var res = exports.x('a', 'b');
25+
var res = (0, exports.x)('a', 'b');
2626

2727

2828
//// [callbackTagVariadicType.d.ts]

Diff for: tests/baselines/reference/commentsOnJSXExpressionsArePreserved(jsx=react-jsx,module=commonjs).js

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ var Component = /** @class */ (function () {
2525
function Component() {
2626
}
2727
Component.prototype.render = function () {
28-
return _a.jsx("div", { children: null /* preserved */ }, void 0);
28+
return (0, _a.jsx)("div", { children: null /* preserved */ }, void 0);
2929
};
3030
return Component;
3131
}());

Diff for: tests/baselines/reference/commentsOnJSXExpressionsArePreserved(jsx=react-jsxdev,module=commonjs).js

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ var Component = /** @class */ (function () {
2626
function Component() {
2727
}
2828
Component.prototype.render = function () {
29-
return _a.jsxDEV("div", { children: null /* preserved */ }, void 0, false, { fileName: _jsxFileName, lineNumber: 5, columnNumber: 15 }, this);
29+
return (0, _a.jsxDEV)("div", { children: null /* preserved */ }, void 0, false, { fileName: _jsxFileName, lineNumber: 5, columnNumber: 15 }, this);
3030
};
3131
return Component;
3232
}());

Diff for: tests/baselines/reference/commonjsSafeImport.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ exports.Foo = Foo;
1919
"use strict";
2020
Object.defineProperty(exports, "__esModule", { value: true });
2121
var _10_lib_1 = require("./10_lib");
22-
_10_lib_1.Foo();
22+
(0, _10_lib_1.Foo)();
2323

2424

2525
//// [10_lib.d.ts]

Diff for: tests/baselines/reference/declarationEmitCommonJsModuleReferencedType.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,5 @@ exports.__esModule = true;
3030
exports.y = exports.x = void 0;
3131
var foo_1 = require("foo");
3232
var root_1 = require("root");
33-
exports.x = foo_1.foo();
34-
exports.y = root_1.bar();
33+
exports.x = (0, foo_1.foo)();
34+
exports.y = (0, root_1.bar)();

Diff for: tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ exports.q = void 0;
2323
var a_1 = require("./a");
2424
function q() { }
2525
exports.q = q;
26-
q.val = a_1.f();
26+
q.val = (0, a_1.f)();
2727

2828

2929
//// [a.d.ts]

Diff for: tests/baselines/reference/declarationEmitExpandoWithGenericConstraint.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ var Point = function (x, y) { return ({ x: x, y: y }); };
2222
exports.Point = Point;
2323
var Rect = function (a, b) { return ({ a: a, b: b }); };
2424
exports.Rect = Rect;
25-
exports.Point.zero = function () { return exports.Point(0, 0); };
25+
exports.Point.zero = function () { return (0, exports.Point)(0, 0); };
2626

2727

2828
//// [declarationEmitExpandoWithGenericConstraint.d.ts]

Diff for: tests/baselines/reference/declarationEmitExportAssignedNamespaceNoTripleSlashTypesReference.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ var get_comp_1 = require("./get-comp");
5353
// this shouldn't need any triple-slash references - it should have a direct import to `react` and that's it
5454
// This issue (#35343) _only_ reproduces in the test harness when the file in question is in a subfolder
5555
exports.obj = {
56-
comp: get_comp_1.getComp()
56+
comp: (0, get_comp_1.getComp)()
5757
};
5858
//// [some-other-file.js]
5959
"use strict";

Diff for: tests/baselines/reference/declarationEmitExportDeclaration.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
2626
exports.bar = void 0;
2727
var utils_1 = require("./utils");
2828
Object.defineProperty(exports, "bar", { enumerable: true, get: function () { return utils_1.bar; } });
29-
utils_1.foo();
29+
(0, utils_1.foo)();
3030
var obj;
3131

3232

Diff for: tests/baselines/reference/declarationEmitForGlobalishSpecifierSymlink.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export const a: import("typescript-fsa").A;
3939
exports.__esModule = true;
4040
exports.a = void 0;
4141
var typescript_fsa_1 = require("typescript-fsa");
42-
exports.a = typescript_fsa_1.getA();
42+
exports.a = (0, typescript_fsa_1.getA)();
4343

4444

4545
//// [index.d.ts]

Diff for: tests/baselines/reference/declarationEmitForGlobalishSpecifierSymlink2.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export const a: import("typescript-fsa").A;
2727
exports.__esModule = true;
2828
exports.a = void 0;
2929
var typescript_fsa_1 = require("typescript-fsa");
30-
exports.a = typescript_fsa_1.getA();
30+
exports.a = (0, typescript_fsa_1.getA)();
3131

3232

3333
//// [index.d.ts]

Diff for: tests/baselines/reference/declarationEmitForModuleImportingModuleAugmentationRetainsImport.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ var ParentThing = /** @class */ (function () {
3131
return ParentThing;
3232
}());
3333
exports.ParentThing = ParentThing;
34-
child1_1.child1(ParentThing.prototype);
34+
(0, child1_1.child1)(ParentThing.prototype);
3535
//// [child1.js]
3636
"use strict";
3737
exports.__esModule = true;

Diff for: tests/baselines/reference/declarationEmitForTypesWhichNeedImportTypes.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ exports.createNamed = createNamed;
2525
exports.__esModule = true;
2626
exports.Value = void 0;
2727
var b_1 = require("./b");
28-
exports.Value = b_1.createNamed();
28+
exports.Value = (0, b_1.createNamed)();
2929

3030

3131
//// [b.d.ts]

0 commit comments

Comments
 (0)