Skip to content

Commit 39bbec1

Browse files
authored
fix: load prebuilt classes for anonymous extends (#2101)
The runtime now asks for anonymous `extend` and `@NativeClass` classes by the same name the static binding generator gives them, so it loads the prebuilt classes instead of generating them on the device at every launch. - Build the file part of the class name exactly like the generator (last three path parts plus a 6-hex MD5). - Skip the CommonJS column offset on line 1 of ES modules. - Write runtime-generated dex files with the content digest `getDexFile` looks up, so they are reused across launches. - The generator now locates the `_super.apply` call of classes without a constructor. - Keep a `$` from the file name when looking up a prebuilt class. - Parse the MessageFormat test's numbers in a fixed locale.
1 parent 06d143b commit 39bbec1

14 files changed

Lines changed: 582 additions & 51 deletions

File tree

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ require("./tests/byte-buffer-test");
6767
require("./tests/shared-array-buffer-test");
6868
require("./tests/dex-interface-implementation");
6969
require("./tests/testClassForNameDiscovery");
70+
require("./tests/testPrebuiltExtendClasses");
7071
require("./tests/testInterfaceImplementation");
7172
require("./tests/testPrimitiveCallbackReturns");
7273
require("./tests/testRuntimeImplementedAPIs");
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
exports.DollarFileObject = java.lang.Object.extend({
2+
toString: function () {
3+
return "dollar file";
4+
}
5+
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const LineOneObject = java.lang.Object.extend({ toString: function () { return "line one"; } });
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
describe("Prebuilt classes of anonymous extends", function () {
2+
3+
// DexFactory writes the classes it generates at runtime to one of these directories
4+
// (see RuntimeHelper). A class the static binding generator built must be loaded from
5+
// the APK and leave nothing here.
6+
var filesDir = __dirname.replace(/\/app\/tests$/, "");
7+
var dataDir = filesDir.replace(/\/files$/, "");
8+
var dexDirs = [dataDir + "/code_cache/secondary-dexes", filesDir + "/secondary-dexes"];
9+
10+
function generatedDexFiles(instance) {
11+
var proxyName = instance.getClass().getName().replace(/^com\.tns\.gen\./, "");
12+
var result = [];
13+
dexDirs.forEach(function (dir) {
14+
var files = new java.io.File(dir).list();
15+
if (!files) {
16+
return;
17+
}
18+
for (var i = 0; i < files.length; i++) {
19+
var file = files[i];
20+
if (file.indexOf(proxyName + "-") === 0 && /\.dex$/.test(file)) {
21+
result.push(file);
22+
}
23+
}
24+
});
25+
return result;
26+
}
27+
28+
it("loads an anonymous extend's class from the APK", function () {
29+
var Anonymous = java.lang.Object.extend({
30+
toString: function () {
31+
return "anonymous";
32+
}
33+
});
34+
var instance = new Anonymous();
35+
36+
expect(instance.toString()).toBe("anonymous");
37+
expect(generatedDexFiles(instance)).toEqual([]);
38+
});
39+
40+
it("loads a TypeScript-compiled native class from the APK", function () {
41+
var CompiledClass = (function (_super) {
42+
__extends(CompiledClass, _super);
43+
function CompiledClass() {
44+
var _this = _super.call(this) || this;
45+
return global.__native(_this);
46+
}
47+
CompiledClass.prototype.toString = function () {
48+
return "compiled";
49+
};
50+
return CompiledClass;
51+
}(java.lang.Object));
52+
var instance = new CompiledClass();
53+
54+
expect(instance.toString()).toBe("compiled");
55+
expect(generatedDexFiles(instance)).toEqual([]);
56+
});
57+
58+
it("loads a TypeScript-compiled native class without a constructor from the APK", function () {
59+
var NoConstructorClass = (function (_super) {
60+
__extends(NoConstructorClass, _super);
61+
function NoConstructorClass() {
62+
return _super !== null && _super.apply(this, arguments) || this;
63+
}
64+
NoConstructorClass.prototype.toString = function () {
65+
return "no constructor";
66+
};
67+
return NoConstructorClass;
68+
}(java.lang.Object));
69+
var instance = new NoConstructorClass();
70+
71+
expect(instance.toString()).toBe("no constructor");
72+
expect(generatedDexFiles(instance)).toEqual([]);
73+
});
74+
75+
it("loads the class of an extend in a file with $ in its name from the APK", function () {
76+
var DollarFileObject = require("./prebuiltExtend$Dollar").DollarFileObject;
77+
var instance = new DollarFileObject();
78+
79+
expect(instance.toString()).toBe("dollar file");
80+
expect(generatedDexFiles(instance)).toEqual([]);
81+
});
82+
83+
it("loads the class of an extend on the first line of an ES module from the APK", function () {
84+
var LineOneObject = require("./prebuiltExtendLineOne.mjs").LineOneObject;
85+
var instance = new LineOneObject();
86+
87+
expect(instance.toString()).toBe("line one");
88+
expect(generatedDexFiles(instance)).toEqual([]);
89+
});
90+
91+
it("caches a class generated at runtime under the name DexFactory looks up", function () {
92+
// A computed member hides the extend from the static binding generator.
93+
var ext = "ex" + "tend";
94+
var RuntimeGenerated = java.lang.Object[ext]({
95+
toString: function () {
96+
return "runtime generated";
97+
}
98+
});
99+
var instance = new RuntimeGenerated();
100+
101+
expect(instance.toString()).toBe("runtime generated");
102+
var files = generatedDexFiles(instance);
103+
expect(files.length).toBe(1);
104+
// <name>-<update time>-<version code>-<content digest>.dex, as DexFactory.getDexFile probes it.
105+
expect(files[0]).toMatch(/-\d+-\d+-[0-9a-f]{10}\.dex$/);
106+
});
107+
});

‎test-app/app/src/main/assets/app/tests/tests.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1625,8 +1625,9 @@ describe("Tests ", function () {
16251625
__log("TEST: TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes");
16261626

16271627
var formats = java.lang.reflect.Array.newInstance(java.text.NumberFormat.class, 2);
1628-
formats[0] = java.text.NumberFormat.getInstance();
1629-
formats[1] = java.text.NumberFormat.getIntegerInstance();
1628+
// The pattern below uses "," as a separator, which is a decimal separator in many locales.
1629+
formats[0] = java.text.NumberFormat.getInstance(java.util.Locale.US);
1630+
formats[1] = java.text.NumberFormat.getIntegerInstance(java.util.Locale.US);
16301631
var mf = new java.text.MessageFormat("{0}, {1}")
16311632
mf.setFormats(formats);
16321633
var arr = mf.parse("123, 4567");
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
var NoConstructor = /** @class */ (function (_super) {
2+
__extends(NoConstructor, _super);
3+
function NoConstructor() {
4+
return _super !== null && _super.apply(this, arguments) || this;
5+
}
6+
NoConstructor.prototype.toString = function () {
7+
return "no constructor";
8+
};
9+
return NoConstructor;
10+
}(java.lang.Object));
11+
var Minified=function(e){__extends(Minified,e);function Minified(){return null!==e&&e.apply(this,arguments)||this}Minified.prototype.toString=function(){return"minified"};return Minified}(java.lang.Object);
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
(function () {
2+
3+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
4+
var c = arguments.length;
5+
var r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6+
7+
if (typeof global.Reflect === "object" && typeof global.Reflect.decorate === "function") {
8+
r = global.Reflect.decorate(decorators, target, key, desc);
9+
}
10+
else {
11+
for (var i = decorators.length - 1; i >= 0; i--) {
12+
if (d = decorators[i]) {
13+
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14+
}
15+
}
16+
}
17+
return c > 3 && r && Object.defineProperty(target, key, r), r;
18+
};
19+
20+
// For backward compatibility.
21+
var __native = function (thiz) {
22+
// we are setting the __container__ property to the base class when the super method is called
23+
// if the constructor returns the __native(this) call we will use the old implementation
24+
// copying all the properties to the result
25+
// otherwise if we are using the result from the super() method call we won't need such logic
26+
// as thiz already contains the parent properties
27+
// this way we now support both implementations in typescript generated constructors:
28+
// 1: super(); return __native(this);
29+
// 2: return super() || this;
30+
if (thiz.__container__) {
31+
var result = thiz.__proto__;
32+
33+
for (var prop in thiz) {
34+
if (thiz.hasOwnProperty(prop)) {
35+
thiz.__proto__[prop] = thiz[prop];
36+
delete thiz[prop];
37+
}
38+
}
39+
40+
thiz.constructor = undefined;
41+
thiz.__proto__ = undefined;
42+
Object.freeze(thiz);
43+
Object.preventExtensions(thiz);
44+
return result;
45+
} else {
46+
return thiz;
47+
}
48+
};
49+
50+
var __extends = function (Child, Parent) {
51+
var extendNativeClass = !!Parent.extend && (Parent.extend.toString().indexOf("[native code]") > -1);
52+
if (!extendNativeClass) {
53+
__extends_ts(Child, Parent);
54+
return;
55+
}
56+
if (Parent.__isPrototypeImplementationObject) {
57+
throw new Error("Can not extend an already extended native object.");
58+
}
59+
60+
function extend(thiz) {
61+
var child = thiz.__proto__.__child;
62+
if (!child.__extended) {
63+
var parent = thiz.__proto__.__parent;
64+
child.__extended = parent.extend(child.name, child.prototype, true);
65+
// This will deal with "i instanceof child"
66+
child[Symbol.hasInstance] = function (instance) {
67+
return instance instanceof this.__extended;
68+
}
69+
}
70+
return child.__extended;
71+
};
72+
73+
Parent.__activityExtend = function (parent, name, implementationObject) {
74+
__log("__activityExtend called");
75+
return parent.extend(name, implementationObject);
76+
};
77+
78+
Parent.call = function (thiz) {
79+
var Extended = extend(thiz);
80+
thiz.__container__ = true;
81+
if (arguments.length > 1) {
82+
thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(Array.prototype.slice.call(arguments, 1))));
83+
}
84+
else {
85+
thiz.__proto__ = new Extended()
86+
}
87+
return thiz.__proto__;
88+
};
89+
90+
Parent.apply = function (thiz, args) {
91+
var Extended = extend(thiz);
92+
thiz.__container__ = true;
93+
if (args && args.length > 0) {
94+
thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(args)));
95+
}
96+
else {
97+
thiz.__proto__ = new Extended();
98+
}
99+
return thiz.__proto__;
100+
};
101+
__extends_ns(Child, Parent);
102+
Child.__isPrototypeImplementationObject = true;
103+
Child.__proto__ = Parent;
104+
Child.prototype.__parent = Parent;
105+
Child.prototype.__child = Child;
106+
}
107+
108+
var __extends_ts = function (child, parent) {
109+
extendStaticFunctions(child, parent);
110+
assignPrototypeFromParentToChild(parent, child);
111+
};
112+
113+
var __extends_ns = function (child, parent) {
114+
if (!parent.extend) {
115+
assignPropertiesFromParentToChild(parent, child);
116+
}
117+
118+
assignPrototypeFromParentToChild(parent, child);
119+
};
120+
121+
var extendStaticFunctions =
122+
Object.setPrototypeOf
123+
|| (hasInternalProtoProperty() && function (child, parent) { child.__proto__ = parent; })
124+
|| assignPropertiesFromParentToChild;
125+
126+
function hasInternalProtoProperty() {
127+
return { __proto__: [] } instanceof Array;
128+
}
129+
130+
function assignPropertiesFromParentToChild(parent, child) {
131+
for (var property in parent) {
132+
if (parent.hasOwnProperty(property)) {
133+
child[property] = parent[property];
134+
}
135+
}
136+
}
137+
138+
function assignPrototypeFromParentToChild(parent, child) {
139+
function __() {
140+
this.constructor = child;
141+
}
142+
143+
if (parent === null) {
144+
child.prototype = Object.create(null);
145+
} else {
146+
__.prototype = parent.prototype;
147+
child.prototype = new __();
148+
}
149+
}
150+
151+
152+
function JavaProxy(className) {
153+
return function (target) {
154+
var extended = target.extend(className, target.prototype)
155+
extended.name = className;
156+
return extended;
157+
};
158+
}
159+
160+
function Interfaces(interfacesArr) {
161+
return function (target) {
162+
if (interfacesArr instanceof Array) {
163+
// attach interfaces: [] to the object
164+
target.prototype.interfaces = interfacesArr;
165+
}
166+
}
167+
}
168+
169+
Object.defineProperty(global, "__native", { value: __native });
170+
Object.defineProperty(global, "__extends", { value: __extends });
171+
Object.defineProperty(global, "__decorate", { value: __decorate });
172+
173+
global.JavaProxy = JavaProxy;
174+
global.Interfaces = Interfaces;
175+
})()

‎test-app/build-tools/jsparser/tests/specs/ast-parser-tests.spec.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,34 @@ describe("parser/js_parser tests", function () {
243243
});
244244
});
245245

246+
it("Generated metadata for a transpiled typescript class without a constructor should contain the super call location", function (done) {
247+
let input = path.normalize(path.join(prefix, "extends_ts_no_constructor", "app")),
248+
generatedJavaClassesRoot = path.normalize(path.join(prefix, "extends_ts_no_constructor", "src", "main", "java"));
249+
250+
clearOutput();
251+
252+
execGradle(input, generatedJavaClassesRoot, function (error, stdout, stderr) {
253+
if (error) {
254+
console.error(`exec error: ${error}`);
255+
return done.fail(error);
256+
}
257+
258+
logExecResult(stdout, stderr)
259+
260+
let bindingsContent = fs.readFileSync(sbgBindingOutoutFile, "utf-8").toString().trim().split('\n');
261+
262+
// JavaClass*file*line*column*NewClass*...: the runtime names the class from
263+
// the location of the `_super.apply` call (the column of `apply`, 1-based).
264+
let locations = bindingsContent.map(line => line.split("*").slice(1, 5).join("*")).sort();
265+
expect(locations).toEqual([
266+
"no_constructor*11*87*Minified",
267+
"no_constructor*4*42*NoConstructor"
268+
]);
269+
270+
done();
271+
});
272+
});
273+
246274
it("Generated metadata for bindings should return proper JavaClass name when there is a static property and double assignment", function (done) {
247275
let input = path.normalize(path.join(prefix, "decorated_double_assignment_ts", "app")),
248276
generatedJavaClassesRoot = path.normalize(path.join(prefix, "decorated_double_assignment_ts", "src", "main", "java"));

0 commit comments

Comments
 (0)