diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index 9e4dfc56c..ff48fe958 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -84,6 +84,7 @@ require("./tests/testTypedArrayArgs"); require("./tests/dex-interface-implementation"); require("./tests/testClassForNameDiscovery"); require("./tests/testPrebuiltExtendClasses"); +require("./tests/testPrebuiltInterfaceAliases"); require("./tests/testRuntimeGenerationReport"); require("./tests/testInterfaceExtendClasses"); require("./tests/testAppModuleBindings"); diff --git a/test-app/app/src/main/assets/app/tests/testPrebuiltInterfaceAliases.js b/test-app/app/src/main/assets/app/tests/testPrebuiltInterfaceAliases.js new file mode 100644 index 000000000..a130d4c05 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testPrebuiltInterfaceAliases.js @@ -0,0 +1,141 @@ +describe("Interfaces of prebuilt classes", function () { + var RunnableAlias = java.lang.Runnable; + + // With -PuseContentBindings a class the generator saw only part of asks for another name, + // so no prebuilt class answers it and nothing is rejected. + var contentKeyed = (function () { + try { + java.lang.Class.forName("com.tns.gen.ContentKeyedBindings", false, com.tns.Runtime.class.getClassLoader()); + return true; + } catch (e) { + return false; + } + }()); + + function expectRejectedPrebuilt(instance, className, reason) { + // A content-keyed name may also be the name of another class with the same content. + if (contentKeyed) { + return; + } + var name = String(instance.getClass().getName()); + expect(runtimeGeneratedEntries(name).length).toBe(1); + expect(name).toMatch(new RegExp("_" + className + "_runtime$")); + var prebuiltName = "com.tns.gen." + name.replace(/_runtime$/, ""); + expect(com.tns.tests.LogcatUtil.countJsWarnings(prebuiltName, reason)).toBe(1); + } + + function runtimeGeneratedEntries(loadedName) { + var lines = com.tns.DexFactory.getRuntimeGeneratedClasses(); + var result = []; + for (var i = 0; i < lines.length; i++) { + var fields = String(lines[i]).split(" "); + if (fields[2] === loadedName) { + result.push({ source: fields[0], loaded: fields[2], requested: fields[3] }); + } + } + return result; + } + + function runFromJava(instance) { + java.util.concurrent.Executors.callable(instance).call(); + } + + it("loads a class whose interface is listed through a local alias from the APK", function () { + var runs = 0; + var Aliased = (function (_super) { + __extends(Aliased, _super); + function Aliased() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + Aliased.prototype.run = function () { + runs++; + }; + Aliased = __decorate([ + Interfaces([RunnableAlias]) + ], Aliased); + return Aliased; + }(java.lang.Object)); + var instance = new Aliased(); + + expect(java.lang.Runnable.class.isAssignableFrom(instance.getClass())).toBe(true); + runFromJava(instance); + expect(runs).toBe(1); + expect(runtimeGeneratedEntries(instance.getClass().getName())).toEqual([]); + }); + + it("generates a class whose interface the static binding generator cannot name at runtime", function () { + function runnableType() { + return java.lang.Runnable; + } + var runs = 0; + var Unnamed = (function (_super) { + __extends(Unnamed, _super); + function Unnamed() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + Unnamed.prototype.run = function () { + runs++; + }; + Unnamed = __decorate([ + Interfaces([runnableType()]) + ], Unnamed); + return Unnamed; + }(java.lang.Object)); + var instance = new Unnamed(); + + expect(java.lang.Runnable.class.isAssignableFrom(instance.getClass())).toBe(true); + runFromJava(instance); + expect(runs).toBe(1); + expect(runtimeGeneratedEntries(instance.getClass().getName()).length).toBe(1); + }); + + it("generates a class in place of a prebuilt one built without a method added after the class body, and warns", function () { + var LateMember = (function (_super) { + __extends(LateMember, _super); + function LateMember() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + LateMember.prototype.run = function () { + }; + return LateMember; + }(java.lang.Object)); + LateMember.prototype.toString = function () { + return "late member"; + }; + var instance = new LateMember(); + + expect(String(java.lang.String.valueOf(instance))).toBe("late member"); + expectRejectedPrebuilt(instance, "LateMember", "was built without toString"); + }); + + it("generates a class in place of a prebuilt one that lacks a listed interface, and warns", function () { + var runs = 0; + var LateInterface = (function (_super) { + __extends(LateInterface, _super); + function LateInterface() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + LateInterface.prototype.run = function () { + runs++; + }; + return LateInterface; + }(java.lang.Object)); + // The generator builds the class from the class body, without the interface. + LateInterface.prototype.interfaces = [java.lang.Runnable]; + var instance = new LateInterface(); + + expect(java.lang.Runnable.class.isAssignableFrom(instance.getClass())).toBe(true); + runFromJava(instance); + expect(runs).toBe(1); + + // Java creates an instance by the generated class alone. + runFromJava(com.tns.tests.JavaCreated.newInstance(instance.getClass())); + expect(runs).toBe(2); + + expectRejectedPrebuilt(instance, "LateInterface", "does not implement java.lang.Runnable"); + }); +}); diff --git a/test-app/build-tools/jsparser/tests/cases/content_members/app/members.js b/test-app/build-tools/jsparser/tests/cases/content_members/app/members.js index de1e87aee..c7b1f4928 100644 --- a/test-app/build-tools/jsparser/tests/cases/content_members/app/members.js +++ b/test-app/build-tools/jsparser/tests/cases/content_members/app/members.js @@ -9,8 +9,6 @@ var LiteralMembers = java.lang.Object.extend("LiteralMembers", { dataMember: 1, get getterMember() { return 1; }, set setterMember(value) {}, - [computedName]: function () {}, - ...other, 42: function () {}, __proto__: null, identifierMember: function () {}, @@ -18,6 +16,12 @@ var LiteralMembers = java.lang.Object.extend("LiteralMembers", { run: function () {} }); +var UnnamedMembers = java.lang.Object.extend("UnnamedMembers", { + [computedName]: function () {}, + ...other, + run: function () {} +}); + var AccessorMembers = java.lang.Object.extend("AccessorMembers", { get getOnly() { return 1; }, set setOnly(value) {}, diff --git a/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/app/interface_aliases.js b/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/app/interface_aliases.js new file mode 100644 index 000000000..9e356114e --- /dev/null +++ b/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/app/interface_aliases.js @@ -0,0 +1,135 @@ +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +const Observer = java.util.Observer; +var util = java.util; +var Formattable = util.Formattable; +const Runnable = java.lang.Runnable; +var _imported__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); + +var AliasedObject = (function (_super) { + __extends(AliasedObject, _super); + function AliasedObject() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + AliasedObject_1 = AliasedObject; + AliasedObject.prototype.update = function () { + }; + AliasedObject.prototype.formatTo = function () { + }; + var AliasedObject_1; + AliasedObject = AliasedObject_1 = __decorate([ + Interfaces([Observer, Formattable]) + ], AliasedObject); + return AliasedObject; +}(java.lang.Object)); + +var ImportedInterfaceObject = (function (_super) { + __extends(ImportedInterfaceObject, _super); + function ImportedInterfaceObject() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + ImportedInterfaceObject.prototype.update = function () { + }; + ImportedInterfaceObject = __decorate([ + Interfaces([_imported__WEBPACK_IMPORTED_MODULE_0__.Observer]) + ], ImportedInterfaceObject); + return ImportedInterfaceObject; +}(java.lang.Object)); + +var AliasedExtend = java.lang.Object.extend({ + run: function () { + }, + interfaces: [Runnable] +}); + +var NamedImportedInterfaceObject = (function (_super) { + __extends(NamedImportedInterfaceObject, _super); + function NamedImportedInterfaceObject() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + NamedImportedInterfaceObject.prototype.update = function () { + }; + NamedImportedInterfaceObject = __decorate([ + JavaProxy("org.nativescript.aliases.NamedImported"), + Interfaces([_imported__WEBPACK_IMPORTED_MODULE_0__.Observer]) + ], NamedImportedInterfaceObject); + return NamedImportedInterfaceObject; +}(java.lang.Object)); + +var NamedCalledExtend = java.lang.Object.extend("org.nativescript.aliases.NamedCalled", { + run: function () { + }, + interfaces: getInterfaces() +}); + +var mixin = { hashCode: function () { return 1; } }; +var SpreadExtend = java.lang.Object.extend({ + ...mixin, + toString: function () { + } +}); + +var memberName = "equals"; +var ComputedExtend = java.lang.Object.extend({ + [memberName]: function () { + }, + finalize: function () { + } +}); + +var ComputedMember = (function (_super) { + __extends(ComputedMember, _super); + function ComputedMember() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + ComputedMember.prototype.update = function () { + }; + ComputedMember.prototype[memberName] = function () { + }; + return ComputedMember; +}(java.lang.Object)); + +const { Closeable } = java.io; +const { Observer: ObserverMember } = java.util; +const { Formattable: DefaultedFormattable = null } = java.util; + +var DestructuredObject = (function (_super) { + __extends(DestructuredObject, _super); + function DestructuredObject() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + DestructuredObject.prototype.close = function () { + }; + DestructuredObject = __decorate([ + Interfaces([Closeable, ObserverMember]) + ], DestructuredObject); + return DestructuredObject; +}(java.lang.Object)); + +var DefaultedDestructuredObject = (function (_super) { + __extends(DefaultedDestructuredObject, _super); + function DefaultedDestructuredObject() { + var _this = _super.call(this) || this; + return global.__native(_this); + } + DefaultedDestructuredObject.prototype.formatTo = function () { + }; + DefaultedDestructuredObject = __decorate([ + Interfaces([DefaultedFormattable]) + ], DefaultedDestructuredObject); + return DefaultedDestructuredObject; +}(java.lang.Object)); diff --git a/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/internal/ts_helpers.js b/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/internal/ts_helpers.js new file mode 100644 index 000000000..1a0625f45 --- /dev/null +++ b/test-app/build-tools/jsparser/tests/cases/extends_with_interface_aliases/internal/ts_helpers.js @@ -0,0 +1,175 @@ +(function () { + + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length; + var r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + + if (typeof global.Reflect === "object" && typeof global.Reflect.decorate === "function") { + r = global.Reflect.decorate(decorators, target, key, desc); + } + else { + for (var i = decorators.length - 1; i >= 0; i--) { + if (d = decorators[i]) { + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + } + } + } + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + // For backward compatibility. + var __native = function (thiz) { + // we are setting the __container__ property to the base class when the super method is called + // if the constructor returns the __native(this) call we will use the old implementation + // copying all the properties to the result + // otherwise if we are using the result from the super() method call we won't need such logic + // as thiz already contains the parent properties + // this way we now support both implementations in typescript generated constructors: + // 1: super(); return __native(this); + // 2: return super() || this; + if (thiz.__container__) { + var result = thiz.__proto__; + + for (var prop in thiz) { + if (thiz.hasOwnProperty(prop)) { + thiz.__proto__[prop] = thiz[prop]; + delete thiz[prop]; + } + } + + thiz.constructor = undefined; + thiz.__proto__ = undefined; + Object.freeze(thiz); + Object.preventExtensions(thiz); + return result; + } else { + return thiz; + } + }; + + var __extends = function (Child, Parent) { + var extendNativeClass = !!Parent.extend && (Parent.extend.toString().indexOf("[native code]") > -1); + if (!extendNativeClass) { + __extends_ts(Child, Parent); + return; + } + if (Parent.__isPrototypeImplementationObject) { + throw new Error("Can not extend an already extended native object."); + } + + function extend(thiz) { + var child = thiz.__proto__.__child; + if (!child.__extended) { + var parent = thiz.__proto__.__parent; + child.__extended = parent.extend(child.name, child.prototype, true); + // This will deal with "i instanceof child" + child[Symbol.hasInstance] = function (instance) { + return instance instanceof this.__extended; + } + } + return child.__extended; + }; + + Parent.__activityExtend = function (parent, name, implementationObject) { + __log("__activityExtend called"); + return parent.extend(name, implementationObject); + }; + + Parent.call = function (thiz) { + var Extended = extend(thiz); + thiz.__container__ = true; + if (arguments.length > 1) { + thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(Array.prototype.slice.call(arguments, 1)))); + } + else { + thiz.__proto__ = new Extended() + } + return thiz.__proto__; + }; + + Parent.apply = function (thiz, args) { + var Extended = extend(thiz); + thiz.__container__ = true; + if (args && args.length > 0) { + thiz.__proto__ = new (Function.prototype.bind.apply(Extended, [null].concat(args))); + } + else { + thiz.__proto__ = new Extended(); + } + return thiz.__proto__; + }; + __extends_ns(Child, Parent); + Child.__isPrototypeImplementationObject = true; + Child.__proto__ = Parent; + Child.prototype.__parent = Parent; + Child.prototype.__child = Child; + } + + var __extends_ts = function (child, parent) { + extendStaticFunctions(child, parent); + assignPrototypeFromParentToChild(parent, child); + }; + + var __extends_ns = function (child, parent) { + if (!parent.extend) { + assignPropertiesFromParentToChild(parent, child); + } + + assignPrototypeFromParentToChild(parent, child); + }; + + var extendStaticFunctions = + Object.setPrototypeOf + || (hasInternalProtoProperty() && function (child, parent) { child.__proto__ = parent; }) + || assignPropertiesFromParentToChild; + + function hasInternalProtoProperty() { + return { __proto__: [] } instanceof Array; + } + + function assignPropertiesFromParentToChild(parent, child) { + for (var property in parent) { + if (parent.hasOwnProperty(property)) { + child[property] = parent[property]; + } + } + } + + function assignPrototypeFromParentToChild(parent, child) { + function __() { + this.constructor = child; + } + + if (parent === null) { + child.prototype = Object.create(null); + } else { + __.prototype = parent.prototype; + child.prototype = new __(); + } + } + + + function JavaProxy(className) { + return function (target) { + var extended = target.extend(className, target.prototype) + extended.name = className; + return extended; + }; + } + + function Interfaces(interfacesArr) { + return function (target) { + if (interfacesArr instanceof Array) { + // attach interfaces: [] to the object + target.prototype.interfaces = interfacesArr; + } + } + } + + Object.defineProperty(global, "__native", { value: __native }); + Object.defineProperty(global, "__extends", { value: __extends }); + Object.defineProperty(global, "__decorate", { value: __decorate }); + + global.JavaProxy = JavaProxy; + global.Interfaces = Interfaces; +})() \ No newline at end of file diff --git a/test-app/build-tools/jsparser/tests/specs/ast-parser-tests.spec.js b/test-app/build-tools/jsparser/tests/specs/ast-parser-tests.spec.js index 7e57ca8ef..fcb2844c4 100644 --- a/test-app/build-tools/jsparser/tests/specs/ast-parser-tests.spec.js +++ b/test-app/build-tools/jsparser/tests/specs/ast-parser-tests.spec.js @@ -206,6 +206,46 @@ describe("parser/js_parser tests", function () { }); }); + it("Generate bindings for interfaces listed through local aliases, and none for classes it cannot fully describe", function (done) { + let input = path.normalize(path.join(prefix, "extends_with_interface_aliases", "app")), + generatedJavaClassesRoot = path.normalize(path.join(prefix, "extends_with_interface_aliases", "src", "main", "java")); + + clearOutput(); + + execGradle(input, generatedJavaClassesRoot, function (error, stdout, stderr) { + if (error) { + console.error(`exec error: ${error}`); + return done.fail(error); + } + + logExecResult(stdout, stderr); + + let lines = fs.readFileSync(sbgBindingOutoutFile, "utf-8").toString().trim().split('\n'); + // ******** + let interfacesOf = function (predicate) { + let line = lines.find(l => predicate(l.split('*'))); + return line === undefined ? undefined : line.split('*')[8].split(','); + }; + + expect(interfacesOf(parts => parts[4] === "AliasedObject")).toEqual(["java.util.Observer", "java.util.Formattable"]); + expect(interfacesOf(parts => parts[5].split(',').indexOf("run") > -1)).toEqual(["java.lang.Runnable"]); + expect(interfacesOf(parts => parts[4] === "ImportedInterfaceObject")).toBeUndefined(); + // A destructured binding names the member, not the object it is taken from. + expect(interfacesOf(parts => parts[4] === "DestructuredObject")).toEqual(["java.io.Closeable", "java.util.Observer"]); + expect(interfacesOf(parts => parts[4] === "DefaultedDestructuredObject")).toBeUndefined(); + expect(stdout + stderr).toContain("cannot determine the Java interface(s) _imported__WEBPACK_IMPORTED_MODULE_0__.Observer of class ImportedInterfaceObject"); + expect(lines.filter(l => l.indexOf("org.nativescript.aliases.") > -1)).toEqual([]); + + // Classes with members the parser cannot name are left to the runtime. + let methodsOf = l => (l.split('*')[5] || "").split(','); + expect(lines.filter(l => methodsOf(l).indexOf("toString") > -1)).toEqual([]); + expect(lines.filter(l => methodsOf(l).indexOf("finalize") > -1)).toEqual([]); + expect(interfacesOf(parts => parts[4] === "ComputedMember")).toBeUndefined(); + + done(); + }); + }); + it("Generated metadata for bindings should return proper JavaClass name despite emitted TS ES5 code", function (done) { let input = path.normalize(path.join(prefix, "decorated_extends_ts", "app")), generatedJavaClassesRoot = path.normalize(path.join(prefix, "decorated_extends_ts", "src", "main", "java")); @@ -329,6 +369,8 @@ describe("parser/js_parser tests", function () { expect(rows["LiteralMembers"][5]).toBe("identifierMember,quotedMember,shorthandMember,dataMember,~getterMember,~setterMember,run"); expect(rows["LiteralMembers"][8]).toBe("java.lang.Runnable"); + // The runtime finds this class by call site, so a list missing members would be wrong. + expect(rows["UnnamedMembers"]).toBeUndefined(); // Accessors are marked with `~`; a redefined name keeps its first // position and the kind of its last definition. diff --git a/test-app/build-tools/jsparser/visitors/es5-visitors.js b/test-app/build-tools/jsparser/visitors/es5-visitors.js index 8def5f912..e705b39c2 100644 --- a/test-app/build-tools/jsparser/visitors/es5-visitors.js +++ b/test-app/build-tools/jsparser/visitors/es5-visitors.js @@ -119,15 +119,20 @@ var es5_visitors = (function() { } var decorateNodes = traverseForDecorate(path, config, 3); + var decorateScope = decorateNodes ? _getParent(path, 3, config).scope : null; var isDecoratedWithExtend = false, customExtendDecoratorName, customExtendDecoratorValue, - implementedInterfaces = []; + implementedInterfaces = [], + unresolvedInterfaces = []; if (!decorateNodes) { // 7 -> Takes 7 levels up to get to the scope where the class is declared decorateNodes = traverseForDecorateSpecial(path, config, 7); + if (decorateNodes) { + decorateScope = _getParent(path, 7, config).parentPath.scope; + } } if (decorateNodes) { @@ -138,12 +143,9 @@ var es5_visitors = (function() { if (currentDecorator.callee.name === config.interfacesDecoratorName) { currentDecorator.callee.skipMeOnVisit = true; - var interfaces = currentDecorator.arguments[0].elements; - - for (var i in interfaces) { - var interfaceName = _getWholeInterfaceNameFromInterfacesNode(interfaces[i]); - implementedInterfaces.push(interfaceName); - } + var interfaceList = _resolveInterfaceList(currentDecorator.arguments[0], decorateScope); + implementedInterfaces = implementedInterfaces.concat(interfaceList.names); + unresolvedInterfaces = unresolvedInterfaces.concat(interfaceList.unresolved); } // JavaProxy @@ -159,6 +161,18 @@ var es5_visitors = (function() { } } + if (unresolvedInterfaces.length) { + _warnUnresolvedInterfaces(unresolvedInterfaces, "class " + (isDecoratedWithExtend ? customExtendDecoratorValue : declaredClassName || extendClass), config); + return; + } + + // The runtime looks an anonymous class up by its call site alone, so its prebuilt class + // has to list every member. A named class keeps the members the parser can name. + if (overriddenMethodNames.hasUnnamedMembers && !isDecoratedWithExtend) { + _skipIncompleteClass(config, "a computed prototype member"); + return; + } + if (isDecoratedWithExtend) { traverseJavaProxyExtend(customExtendDecoratorValue, config, customExtendDecoratorName, extendClass, overriddenMethodNames, implementedInterfaces); } else { @@ -514,9 +528,10 @@ var es5_visitors = (function() { className = arg0.value ? arg0.value : ""; // Get all methods from the implementation object - var methodsAndInterfaces = _getOverridenMethodsAndImplementedInterfaces(arg1, config); + var methodsAndInterfaces = _getOverridenMethodsAndImplementedInterfaces(arg1, config, path.scope); var overriddenMethodNames = methodsAndInterfaces[0]; var implementedInterfaces = methodsAndInterfaces[1]; + var unresolvedInterfaces = methodsAndInterfaces[2]; var isCorrectExtendClassName = _testJavaProxyName(className); var isCorrectClassName = _testClassName(className); @@ -527,6 +542,21 @@ var es5_visitors = (function() { } } + // The runtime looks an anonymous class up by its call site alone, so its prebuilt + // class has to list every member. Vendor code calls `.extend({ ...spread })` too, + // so this is not worth a warning. + if (methodsAndInterfaces[3] && !isCorrectExtendClassName) { + _skipIncompleteClass(config, "a spread or computed member"); + return; + } + + if (unresolvedInterfaces.length) { + var extendDescription = (className ? "class " + className + ", " : "") + + "the extend of " + extendClass.slice().reverse().join(".") + " at line " + path.node.property.loc.start.line; + _warnUnresolvedInterfaces(unresolvedInterfaces, extendDescription, config); + return; + } + var lineToWrite = ""; if (isCorrectExtendClassName) { if (config.logger) { @@ -643,10 +673,12 @@ var es5_visitors = (function() { // NOTE: It's a near-identical method to _getOverridenMethods for optimisation reasons // we do not want to check for interfaces while creating an interface // and likewise, we do not want to iterate twice through the impl. object's properties to read the interfaces - function _getOverridenMethodsAndImplementedInterfaces(node, config) { + function _getOverridenMethodsAndImplementedInterfaces(node, config, scope) { var result = []; var overriddenMethodNames = []; var implementedInterfaces = []; + var unresolvedInterfaces = []; + var hasUnnamedMembers = false; var interfacesFound = false; @@ -668,7 +700,12 @@ var es5_visitors = (function() { will get 'method1' and 'method3' */ for (var index in objectProperties) { - var keyName = _getMemberKeyName(objectProperties[index]); + var property = objectProperties[index]; + if (types.isSpreadElement(property) || property.computed) { + hasUnnamedMembers = true; + continue; + } + var keyName = _getMemberKeyName(property); // Without this guard, valid (non-NS) `.extend({ ...other, foo })` // calls in bundled vendor code (e.g. Zod schemas) would crash the parser. if (keyName === null) { @@ -678,51 +715,164 @@ var es5_visitors = (function() { // if the user has declared interfaces that he is implementing if (!interfacesFound && keyName.toLowerCase() === "interfaces" && - types.isArrayExpression(objectProperties[index].value)) { + types.isObjectProperty(property)) { interfacesFound = true; - var interfaces = objectProperties[index].value.elements; - - for (var i in interfaces) { - var interfaceName = _getWholeInterfaceNameFromInterfacesNode(interfaces[i]); - implementedInterfaces.push(interfaceName); - } + var interfaceList = _resolveInterfaceList(property.value, scope); + implementedInterfaces = interfaceList.names; + unresolvedInterfaces = interfaceList.unresolved; } else { - _addLiteralMember(overriddenMethodNames, keyName, _isAccessor(objectProperties[index])); + _addLiteralMember(overriddenMethodNames, keyName, _isAccessor(property)); } } } result.push(overriddenMethodNames); result.push(implementedInterfaces); + result.push(unresolvedInterfaces); + result.push(hasUnnamedMembers); return result; } - function _getWholeInterfaceNameFromInterfacesNode(node) { - var interfaceName = ""; + var MAX_ALIAS_DEPTH = 32; - if (types.isMemberExpression(node)) { - interfaceName += _resolveInterfacePath(node.object); - interfaceName += node.property.name; + /* + * What a variable that is never reassigned stands for, or null: the initializer of + * `const name = init`, or for `const { member } = init` and `const { member: name } = init` + * the member of it. Any other pattern binds something the parser cannot tell. + */ + function _constantValue(binding, name) { + if (!binding || !binding.constant || !binding.path.isVariableDeclarator() || !binding.path.node.init) { + return null; } - - return interfaceName; + var declarator = binding.path.node; + if (types.isIdentifier(declarator.id)) { + return { init: declarator.init, member: null }; + } + if (types.isObjectPattern(declarator.id)) { + var properties = declarator.id.properties; + for (var i = 0; i < properties.length; i++) { + var property = properties[i]; + if (types.isObjectProperty(property) && !property.computed && + types.isIdentifier(property.value, { name: name })) { + if (types.isIdentifier(property.key)) { + return { init: declarator.init, member: property.key.name }; + } + if (types.isStringLiteral(property.key)) { + return { init: declarator.init, member: property.key.value }; + } + } + } + } + return null; } - function _resolveInterfacePath(node) { - var subNode = ""; + /* + * The dotted Java name an expression stands for, following local aliases such as + * `const IMarker = com.example.IMarker`, or null when only running the script could tell: + * an import, a parameter, a reassigned variable, a call. + */ + function _resolveJavaTypeName(node, scope, depth) { + depth = depth || 0; + if (!node || depth > MAX_ALIAS_DEPTH) { + return null; + } if (types.isMemberExpression(node)) { - if (types.isMemberExpression(node.object)) { - subNode += _resolveInterfacePath(node.object); - subNode += node.property.name + "."; + var propertyName; + if (!node.computed && types.isIdentifier(node.property)) { + propertyName = node.property.name; + } else if (node.computed && types.isStringLiteral(node.property)) { + propertyName = node.property.value; } else { - subNode += node.object.name + "."; - subNode += node.property.name + "."; + return null; + } + + // `global.com.example.IMarker` names the same type as `com.example.IMarker`. + if (types.isIdentifier(node.object) && + (node.object.name === "global" || node.object.name === "globalThis") && + !(scope && scope.getBinding(node.object.name))) { + return propertyName; + } + + var owner = _resolveJavaTypeName(node.object, scope, depth + 1); + return owner === null ? null : owner + "." + propertyName; + } + + if (types.isIdentifier(node)) { + var binding = scope && scope.getBinding(node.name); + if (!binding) { + // A global, such as the `com` or `android` package roots. + return node.name; + } + var value = _constantValue(binding, node.name); + var owner = value ? _resolveJavaTypeName(value.init, binding.path.scope, depth + 1) : null; + if (owner === null) { + return null; + } + return value.member === null ? owner : owner + "." + value.member; + } + + return null; + } + + function _describeNode(node) { + if (types.isIdentifier(node)) { + return node.name; + } + if (types.isMemberExpression(node) && !node.computed && types.isIdentifier(node.property)) { + return _describeNode(node.object) + "." + node.property.name; + } + return node ? "<" + node.type + ">" : ""; + } + + /* + * The Java names in an interfaces list (`@Interfaces([...])` or extend's `interfaces: [...]`). + * `unresolved` lists the entries that could not be named statically: a class built from the + * rest would not implement them. + */ + function _resolveInterfaceList(node, scope, depth) { + depth = depth || 0; + var result = { names: [], unresolved: [] }; + + if (types.isArrayExpression(node)) { + node.elements.forEach(function (element) { + var name = types.isSpreadElement(element) ? null : _resolveJavaTypeName(element, scope); + // A Java interface always has a package; a bare name is an unknown global. + if (name && name.indexOf(".") > 0) { + result.names.push(name); + } else { + result.unresolved.push(_describeNode(element)); + } + }); + return result; + } + + if (types.isIdentifier(node) && depth < MAX_ALIAS_DEPTH) { + var binding = scope && scope.getBinding(node.name); + var value = _constantValue(binding, node.name); + if (value && value.member === null) { + return _resolveInterfaceList(value.init, binding.path.scope, depth + 1); } } - return subNode; + result.unresolved.push(_describeNode(node)); + return result; + } + + // A class built from part of its members would never call the others from Java; the + // runtime generates the class from all of them instead. + function _skipIncompleteClass(config, reason) { + if (config.logger) { + config.logger.info("Not prebuilding a class in " + config.fullPathName + ": it has " + reason); + } + } + + // No class is better than one missing interfaces: printed whatever the parser's log settings. + function _warnUnresolvedInterfaces(unresolved, classDescription, config) { + console.warn("WARNING: the static binding generator cannot determine the Java interface(s) " + + unresolved.join(", ") + " of " + classDescription + " in " + config.fullPathName + + ", so it does not prebuild that class. List the interfaces by their full Java name to prebuild it."); } function _getWholeName(node) { @@ -825,6 +975,8 @@ var es5_visitors = (function() { name = left.property.name; } else if (left.computed && types.isStringLiteral(left.property)) { name = left.property.value; + } else { + overriddenMethods.hasUnnamedMembers = true; } return name !== null && MEMBER_NAME_PATTERN.test(name) ? name : null; } diff --git a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java index 802b37c73..ef29f6d27 100644 --- a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java +++ b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/Generator.java @@ -276,6 +276,8 @@ private Binding generateBinding(DataRow dataRow, Set interfaceNames, Set List methods = contentKeyed ? ContentKey.memberNames(parsedMethods) : Arrays.asList(parsedMethods); List interfaces = contentKeyed ? ContentKey.interfaceNames(dataRow.getInterfaces()) : Arrays.asList(dataRow.getInterfaces()); + // The runtime finds a class named after its call site by that name alone. + boolean callSiteNamed = false; if (hasSpecifiedName) { name = getSimpleClassname(dataRow.getFilename()); } else { @@ -284,6 +286,7 @@ private Binding generateBinding(DataRow dataRow, Set interfaceNames, Set } else if (contentKeyed && !locationNamedRows.contains(dataRow)) { name = getContentClassSimpleName(dataRow, clazz, interfaces, methods); } else { + callSiteNamed = true; name = getSimpleClassname(clazz.getClassName().replace("$", "_")) + "_"; // Generate a unique identifier that prevents naming collisions // especially with .mjs files and complex structures @@ -303,7 +306,8 @@ private Binding generateBinding(DataRow dataRow, Set interfaceNames, Set Writer w = new Writer(); - writeBinding(w, dataRow, clazz, packageName, name, methods, interfaces); + String[] jsMembers = callSiteNamed ? dataRow.getMethods(true) : null; + writeBinding(w, dataRow, clazz, packageName, name, methods, interfaces, jsMembers); String classname = dataRow.getFilename(); String source = describeSite(dataRow); boolean involvesAppClasses = involvesAppClasses(dataRow); @@ -803,7 +807,7 @@ private String generateUniqueFileIdentifier(String filePath) { return identifier.toString(); } - private void writeBinding(Writer w, DataRow dataRow, JavaClass clazz, String packageName, String name, List methods, List interfaces) { + private void writeBinding(Writer w, DataRow dataRow, JavaClass clazz, String packageName, String name, List methods, List interfaces, String[] jsMembers) { GenericsAwareClassHierarchyParser genericsAwareClassHierarchyParser = new GenericsAwareClassHierarchyParserImpl(new GenericSignatureReader(), classes); List userImplementedInterfaces = getInterfacesFromCache(interfaces); @@ -818,7 +822,7 @@ private void writeBinding(Writer w, DataRow dataRow, JavaClass clazz, String pac writePackageNameToWriter(w, packageName); writeImportsToWriter(w, clazz, packageName); writeClassBeginningToWriter(w, clazz, userImplementedInterfaces, name, dataRow, genView, interfaceGenericHierarchyViews); - writeFieldsToWriter(w, clazz); + writeFieldsToWriter(w, clazz, jsMembers); writeConstructorsToWriter(w, clazz, methods, name, genView); writeMethodsToWriter(w, genView, interfaceGenericHierarchyViews, clazz, methods, userImplementedInterfaces, packageName); writeClassEndToWriter(w); @@ -916,7 +920,7 @@ private void writePackageNameToWriter(Writer writer, String packageName) { packageNameWriter.writePackageName(packageName); } - private void writeFieldsToWriter(Writer writer, JavaClass clazz) { + private void writeFieldsToWriter(Writer writer, JavaClass clazz, String[] jsMembers) { FieldsWriter fieldsWriter = new FieldsWriterImpl(writer); boolean isApplicationClass = androidClassChecker.isApplicationClass(clazz); @@ -926,6 +930,9 @@ private void writeFieldsToWriter(Writer writer, JavaClass clazz) { } fieldsWriter.writeRuntimeTagField(); + if (jsMembers != null) { + fieldsWriter.writeJsMembersField(jsMembers); + } } private void writeConstructorsToWriter(Writer writer, JavaClass clazz, List implObjectMethods, String generatedClassName, GenericHierarchyView genericHierarchyView) { diff --git a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java index 4f4bd8869..587442c3d 100644 --- a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java +++ b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/FieldsWriter.java @@ -3,4 +3,5 @@ public interface FieldsWriter extends JavaCodeWriter { void writeStaticThizField(String className); void writeRuntimeTagField(); + void writeJsMembersField(String[] memberNames); } diff --git a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java index af7928025..895704f4b 100644 --- a/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java +++ b/test-app/build-tools/static-binding-generator/src/main/java/org/nativescript/staticbindinggenerator/generating/writing/impl/FieldsWriterImpl.java @@ -9,6 +9,8 @@ public class FieldsWriterImpl implements FieldsWriter { private static final String THIZ_KEYWORD = "thiz"; private static final String RUNTIME_TAG_FIELD_DECLARATION = "private volatile int runtimeTag__ns;"; private static final String OBJECT_ID_FIELD_DECLARATION = "private int objectId__ns;"; + // DexFactory reads it to tell whether this class was built from every member its JS class has. + private static final String JS_MEMBERS_FIELD_NAME = "members__ns"; private final Writer writer; @@ -25,6 +27,20 @@ public void writeRuntimeTagField() { writer.writeln(); } + @Override + public void writeJsMembersField(String[] memberNames) { + writer.write(TABULATION_LITERAL); + writer.write("private static final String[] " + JS_MEMBERS_FIELD_NAME + " = {"); + for (int i = 0; i < memberNames.length; i++) { + if (i > 0) { + writer.write(", "); + } + writer.write("\"" + memberNames[i].replace("\\", "\\\\").replace("\"", "\\\"") + "\""); + } + writer.writeln("};"); + writer.writeln(); + } + @Override public void writeStaticThizField(String className) { writer.write(TABULATION_LITERAL); diff --git a/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java b/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java index 53fe395c2..2b3bc42da 100644 --- a/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java +++ b/test-app/build-tools/static-binding-generator/src/test/java/org/nativescript/staticbindinggenerator/test/GeneratorTest.java @@ -182,6 +182,25 @@ public void testAnInterfaceImplementationWithExtraInterfacesGetsItsCallSiteClass Assert.assertFalse(Arrays.asList(sharedClass.getInterfaces()).contains(java.util.Observer.class)); } + @Test + public void testACallSiteClassListsTheMembersTheParserSaw() throws Exception { + Generator generator = new Generator(null, new ArrayList()); + Iterable options = new ArrayList(Arrays.asList("-cp", dependenciesDir)); + + Binding callSite = generator.generateBinding(new DataRow("java.lang.Object*app_main*9*29*Members*toString,helper,~accessor***")); + String callSiteName = callSite.getFile().getName(); + Class callSiteClass = InMemoryJavaCompiler.compile("com.tns.gen.java.lang." + callSiteName.substring(0, callSiteName.length() - ".java".length()), callSite.getContent(), options); + java.lang.reflect.Field members = callSiteClass.getDeclaredField("members__ns"); + members.setAccessible(true); + Assert.assertArrayEquals(new String[]{"toString", "helper", "accessor"}, (String[]) members.get(null)); + + Binding named = generator.generateBinding(new DataRow(Utils.getDataRowsFromResource("datarow-named-extend.txt").get(0))); + Class namedClass = InMemoryJavaCompiler.compile(named.getClassname(), named.getContent(), options); + for (java.lang.reflect.Field field : namedClass.getDeclaredFields()) { + Assert.assertNotEquals("members__ns", field.getName()); + } + } + @Test public void testCanCompileBindingClassExtendingAnExtendedClassWithMethodsWithTheSameSignature() throws Exception { URL u = ListView.class.getResource('/' + ListView.class.getName().replace('.', '/') + ".class"); diff --git a/test-app/runtime/src/main/java/com/tns/DexFactory.java b/test-app/runtime/src/main/java/com/tns/DexFactory.java index dd094e0a3..73bddfd73 100644 --- a/test-app/runtime/src/main/java/com/tns/DexFactory.java +++ b/test-app/runtime/src/main/java/com/tns/DexFactory.java @@ -30,6 +30,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -45,6 +46,14 @@ public class DexFactory { static final String COM_TNS_GEN_PREFIX = "com.tns.gen."; + // Appended to the name of a class generated in place of a prebuilt one that does not match. + static final String MISMATCHED_PREBUILT_SUFFIX = "_runtime"; + // The static binding generator lists in it the members it saw of a call site's JS class. + private static final String PREBUILT_JS_MEMBERS_FIELD = "members__ns"; + // Functions __extends puts on a TypeScript class's prototype, which no Java method overrides. + private static final Set TS_HELPER_MEMBERS = new HashSet(Arrays.asList("constructor", "__parent", "__child")); + + private static final HashSet warnedPrebuiltMismatches = new HashSet(); private final Logger logger; private final File dexDir; @@ -234,6 +243,17 @@ public Class resolveClass(String baseClassName, String name, String className if (overridesDefaults && pregeneratedClass != null && generatedClassNames.contains(pregeneratedClass.getName())) { pregeneratedClass = null; } + // An anonymous class's prebuilt counterpart is found by call site alone, so it is only + // used when it was built from everything the script defines. The class generated instead + // needs a name of its own: the APK's class would answer the prebuilt one first. + if (pregeneratedClass != null && !hasExplicitName && !isNamedProxy) { + String mismatch = describePrebuiltMismatch(pregeneratedClass, methodOverrides, implementedInterfaces); + if (mismatch != null) { + warnPrebuiltClassMismatch(pregeneratedClass.getName(), mismatch); + pregeneratedClass = null; + fullClassName += MISMATCHED_PREBUILT_SUFFIX; + } + } if (pregeneratedClass != null) { return pregeneratedClass; } @@ -454,6 +474,103 @@ private void writeJar(File dexFile, File jarFile) throws IOException { } } + // Why prebuiltClass cannot stand for the JS class, or null when it can. + private static String describePrebuiltMismatch(Class prebuiltClass, String[] methodOverrides, String[] implementedInterfaces) { + String missing = missingInterfaces(prebuiltClass, implementedInterfaces); + if (missing != null) { + return "does not implement " + missing + ", which its JavaScript class lists"; + } + String unseen = unseenMembers(prebuiltClass, methodOverrides); + if (unseen != null) { + return "was built without " + unseen + " of its JavaScript class (defined outside the class body, or by a getter)"; + } + return null; + } + + // The JS functions the static binding generator did not see when it built prebuiltClass, + // joined, or null. Java could never call them through it. + private static String unseenMembers(Class prebuiltClass, String[] methodOverrides) { + if (methodOverrides == null || methodOverrides.length == 0) { + return null; + } + String[] seen; + try { + Field field = prebuiltClass.getDeclaredField(PREBUILT_JS_MEMBERS_FIELD); + field.setAccessible(true); + seen = (String[]) field.get(null); + } catch (NoSuchFieldException e) { + return null; + } catch (IllegalAccessException e) { + return null; + } + HashSet seenMembers = new HashSet(Arrays.asList(seen)); + StringBuilder unseen = null; + for (String member : methodOverrides) { + if (seenMembers.contains(member) || TS_HELPER_MEMBERS.contains(member) || !isJavaIdentifier(member)) { + continue; + } + if (unseen == null) { + unseen = new StringBuilder(member); + } else { + unseen.append(", ").append(member); + } + } + return unseen == null ? null : unseen.toString(); + } + + // No Java method can have any other name. + private static boolean isJavaIdentifier(String name) { + if (name.isEmpty() || !Character.isJavaIdentifierStart(name.charAt(0))) { + return false; + } + for (int i = 1; i < name.length(); i++) { + if (!Character.isJavaIdentifierPart(name.charAt(i))) { + return false; + } + } + return true; + } + + // The interfaces in implementedInterfaces that prebuiltClass does not implement, joined, or + // null if it implements them all. + private static String missingInterfaces(Class prebuiltClass, String[] implementedInterfaces) { + if (implementedInterfaces == null) { + return null; + } + StringBuilder missing = null; + for (String implementedInterface : implementedInterfaces) { + if (implementedInterface == null || implementedInterface.isEmpty()) { + continue; + } + boolean implemented; + try { + implemented = Class.forName(implementedInterface).isAssignableFrom(prebuiltClass); + } catch (ClassNotFoundException e) { + // Generating the class reports it. + implemented = false; + } + if (!implemented) { + if (missing == null) { + missing = new StringBuilder(implementedInterface); + } else { + missing.append(", ").append(implementedInterface); + } + } + } + return missing == null ? null : missing.toString(); + } + + private static void warnPrebuiltClassMismatch(String prebuiltClassName, String mismatch) { + synchronized (warnedPrebuiltMismatches) { + if (!warnedPrebuiltMismatches.add(prebuiltClassName)) { + return; + } + } + Log.w("JS", "The prebuilt class " + prebuiltClassName + " " + mismatch + + ", so the class is generated at runtime instead. Rebuild the app if its JavaScript" + + " changed since; otherwise, please report this with the class's source."); + } + private static boolean hasImplementedInterfaces(String[] implementedInterfaces) { if (implementedInterfaces != null) { for (String implementedInterface : implementedInterfaces) {