Skip to content
Open
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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,9 @@ def getRunTestsBuildArguments = { taskName ->
if (project.hasProperty("narrowMetadataFields")) {
arguments.add("-PnarrowMetadataFields")
}
if (project.hasProperty("useContentBindings")) {
arguments.add("-PuseContentBindings=${project.property('useContentBindings')}")
}
arguments += ["--warning-mode", "all"]
return arguments
}
Expand Down
152 changes: 152 additions & 0 deletions test-app/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,26 @@
* -PandroidXMaterial=[androidx_material_version]
* -PappPath=[app_path]
* -PappResourcesPath=[app_resources_path]
* -PskipSbgAppClasses //don't show the app's own Java classes to the static binding generator
* -PuseContentBindings //name the classes of JS subclasses of Java classes after their content
*/

import groovy.json.JsonSlurper
import groovy.xml.XmlSlurper
import org.apache.commons.io.FileUtils

import javax.inject.Inject
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.jar.JarEntry
import java.util.jar.JarFile
import javax.tools.Diagnostic
import javax.tools.DiagnosticCollector
import javax.tools.ToolProvider

import static org.gradle.internal.logging.text.StyledTextOutput.Style

Expand Down Expand Up @@ -488,8 +495,134 @@ if (failOnCompilationWarningsEnabled()) {
///////////////////////////// EXECUTION PHASE /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////

def SBG_APP_CLASSES_DIR = layout.buildDirectory.dir("nativescript/sbg-app-classes")
def sbgAppClassesEnabled = { ->
!project.hasProperty("skipSbgAppClasses") || project.property("skipSbgAppClasses").toString() == "false"
}

// The static binding generator runs before javac, so on its own it cannot see the
// classes and interfaces declared in this module's Java sources (App_Resources) and
// leaves every JS subclass of them to be generated on the device. This compiles them
// for it alone. Best-effort: sources that only compile together with the rest of the
// build (Kotlin, annotation processors, generated code) are left out, and any failure
// leaves the generator exactly as it would be without this task.
tasks.register("compileAppClassesForSbg") {
dependsOn "collectAllJars"
onlyIf { sbgAppClassesEnabled() }

def classesDir = SBG_APP_CLASSES_DIR
def dependenciesFile = file("$BUILD_TOOLS_PATH/$SBG_JAVA_DEPENDENCIES")
// The first line of the static binding generator's Generator.AUTO_GENERATED_FILE_PROLOGUE.
// It writes named classes (`extend("a.b.C", ...)`, @JavaProxy) outside com/tns/gen too.
def sbgSourcePrefix = "/* AUTO-GENERATED FILE. DO NOT MODIFY.".getBytes(StandardCharsets.UTF_8)
def sources = fileTree(OUTPUT_JAVA_DIR) {
include "**/*.java"
exclude "com/tns/gen/**"
}.filter { File source ->
try {
!source.withInputStream { Arrays.equals(it.readNBytes(sbgSourcePrefix.length), sbgSourcePrefix) }
} catch (IOException ignored) {
true
}
}
def sourceLevel = provider { android.compileOptions.sourceCompatibility.toString() }
def targetLevel = provider { android.compileOptions.targetCompatibility.toString() }
def sourceEncoding = provider { android.compileOptions.encoding ?: "UTF-8" }

inputs.files(sources).skipWhenEmpty().withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("sources")
inputs.files(provider {
dependenciesFile.exists() ? dependenciesFile.readLines().findAll { it } : []
}).withPropertyName("classpath")
inputs.property("sourceLevel", sourceLevel)
inputs.property("targetLevel", targetLevel)
inputs.property("sourceEncoding", sourceEncoding)
outputs.dir(classesDir).withPropertyName("classes")

doLast {
def outDir = classesDir.get().asFile
outDir.deleteDir()
outDir.mkdirs()

def remaining = sources.files.sort()
def total = remaining.size()
def leftOut = []
def firstError = null
try {
def compiler = ToolProvider.getSystemJavaCompiler()
if (compiler == null) {
logger.warn("compileAppClassesForSbg: ${System.getProperty('java.home')} has no Java compiler, so the app's own classes get no prebuilt bindings")
return
}
def options = ["-proc:none", "-nowarn",
"-source", sourceLevel.get(), "-target", targetLevel.get(),
"-encoding", sourceEncoding.get(),
"-classpath", dependenciesFile.readLines().findAll { it }.join(File.pathSeparator),
"-d", outDir.absolutePath]

// javac writes no class files after its first error, so each failing round
// leaves out the sources that reported errors and compiles the rest again.
// A round that cannot leave any source out ends the loop.
def compiled = false
while (!remaining.isEmpty() && !compiled) {
def diagnostics = new DiagnosticCollector()
def fileManager = compiler.getStandardFileManager(diagnostics, Locale.ROOT, Charset.forName(sourceEncoding.get()))
try {
def units = fileManager.getJavaFileObjectsFromFiles(remaining).toList()
def sourceByUri = [units, remaining].transpose().collectEntries { unit, source -> [(unit.toUri()): source] }
compiled = compiler.getTask(new StringWriter(), fileManager, diagnostics, options, null, units).call()
if (!compiled) {
def errors = diagnostics.diagnostics.findAll { it.kind == Diagnostic.Kind.ERROR }
if (firstError == null && !errors.isEmpty()) {
firstError = errors[0].getMessage(Locale.ROOT).readLines().take(2).join(" ").replaceAll(/\s+/, " ")
}
def failing = errors.collect { it.source == null ? null : sourceByUri[it.source.toUri()] }.toSet()
if (failing.isEmpty() || failing.contains(null)) {
break
}
remaining.removeAll(failing)
leftOut.addAll(failing)
}
} finally {
fileManager.close()
}
if (!compiled) {
outDir.deleteDir()
outDir.mkdirs()
}
}

if (!compiled && !remaining.isEmpty()) {
logger.warn("compileAppClassesForSbg: the app's Java sources did not compile on their own, so the app's own classes get no prebuilt bindings (${firstError})")
} else if (!leftOut.isEmpty()) {
def names = leftOut.collect { it.name }.sort()
logger.info("compileAppClassesForSbg: ${leftOut.size()} of ${total} Java sources get no prebuilt bindings because they only compile with the rest of the build: ${names.take(5).join(', ')}${names.size() > 5 ? ', ...' : ''} (${firstError})")
}
} catch (Exception | LinkageError e) {
outDir.deleteDir()
outDir.mkdirs()
logger.warn("compileAppClassesForSbg: the app's own classes get no prebuilt bindings: ${e}")
}
}
}

// Name the Java classes of JS subclasses of Java classes after what they contain instead
// of where their extend() call is. Off unless the app sets -PuseContentBindings or
// `project.ext.useContentBindings = true` in App_Resources/Android/app.gradle or
// before-plugins.gradle. The runtime follows the class the generator then adds to the app.
def useContentBindings = { ->
if (!project.hasProperty("useContentBindings")) {
return false
}
def value = project.property("useContentBindings").toString()
return value.isEmpty() || value.toBoolean()
}

task runSbg(type: BuildToolTask) {
dependsOn "collectAllJars"
dependsOn "compileAppClassesForSbg"
inputs.files(tasks.named("compileAppClassesForSbg")).withPropertyName("appClasses")
inputs.property("sbgAppClassesEnabled", provider { sbgAppClassesEnabled() })
inputs.property("useContentBindings", provider { useContentBindings() })
def rootPath = ""
if (!findProject(':static-binding-generator').is(null)) {
rootPath = Paths.get(project(':static-binding-generator').projectDir.path, "build/libs").toString()
Expand All @@ -514,8 +647,27 @@ task runSbg(type: BuildToolTask) {

args paramz

def sbgDependenciesFile = file("$BUILD_TOOLS_PATH/$SBG_JAVA_DEPENDENCIES")
def sbgWarningsFile = file("$BUILD_TOOLS_PATH/sbg-warnings.txt")
doFirst {
new File("$OUTPUT_JAVA_DIR/com/tns/gen").deleteDir()

// Not written by collectAllJars: the metadata generator reads the real compiled classes.
def appClassesDir = SBG_APP_CLASSES_DIR.get().asFile
if (sbgAppClassesEnabled() && appClassesDir.isDirectory()) {
sbgDependenciesFile.withWriterAppend { it.println(appClassesDir.absolutePath) }
}

if (useContentBindings()) {
args("-content-keyed-bindings")
}
}
doLast {
// The generator's standard output only reaches runSbg.log, and the
// NativeScript CLI runs gradle with --quiet, which hides the warn level.
if (sbgWarningsFile.isFile()) {
sbgWarningsFile.eachLine { logger.quiet("runSbg: ${it}") }
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions test-app/app/src/main/assets/app/mainpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ require("./tests/testTypedArrayArgs");
require("./tests/dex-interface-implementation");
require("./tests/testClassForNameDiscovery");
require("./tests/testPrebuiltExtendClasses");
require("./tests/testRuntimeGenerationReport");
require("./tests/testInterfaceExtendClasses");
require("./tests/testAppModuleBindings");
require("./tests/testContentKeyedBindings");
require("./tests/testProxyRegistrationGc");
require("./tests/testInterfaceImplementation");
require("./tests/testPrimitiveCallbackReturns");
Expand Down Expand Up @@ -131,5 +135,7 @@ require('./tests/testEsmHttpLoader');
require('./tests/NapiTests');
require('./tests/NapiCoverageTests');
require("./tests/testConcurrentAccess");
// Checks the runtime generation report, so it goes after every spec that implements an interface
require("./tests/testInterfaceProxies");

require("./tests/testESModules.mjs");
3 changes: 2 additions & 1 deletion test-app/app/src/main/assets/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"forceLog": false,
"suppressCallJSMethodExceptions": false,
"enableLineBreakpoints": false,
"enableMultithreadedJavascript": true
"enableMultithreadedJavascript": true,
"interfaceProxies": false
},
"discardUncaughtJsExceptions": false,
"security": {
Expand Down
33 changes: 33 additions & 0 deletions test-app/app/src/main/assets/app/tests/appModuleBindingsWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Entry for testAppModuleBindings: every call is hidden from the static binding
// generator, so this worker's runtime generates the classes.
var ext = "ex" + "tend";
var Target = com.tns.tests.AppModuleBindingTarget.WorkerRuntimeGenerated;
var result = {};

function callFromJava(instance, methodName) {
return String(instance.getClass().getMethod(methodName, []).invoke(instance, []));
}

try {
var Extended = com.tns.tests.Button1[ext]({
toString: function () {
return "worker extend";
},
workerExtendMarker: true
});
var extended = new Extended();
result.extendedClass = String(extended.getClass().getName());
result.extendedCall = callFromJava(extended, "toString");

var implemented = new Target({
describe: function () {
return "worker new";
}
});
result.implementedClass = String(implemented.getClass().getName());
result.implementedIsProxy = java.lang.reflect.Proxy.isProxyClass(implemented.getClass());
result.implementedCall = callFromJava(implemented, "describe");
} catch (e) {
result.error = String(e && e.message || e);
}
postMessage(result);
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Entry for testContentKeyedBindings: the same content as call sites of the main
// runtime, one prebuilt, one generated at runtime, and a named one.
var ext = "ex" + "tend";
var result = {};

function javaToString(instance) {
return String(instance.getClass().getMethod("toString", []).invoke(instance, []));
}

try {
var Prebuilt = java.lang.Object.extend({
toString: function () {
return "worker prebuilt";
},
workerContentMarker: 1
});
var prebuilt = new Prebuilt();
result.prebuiltClass = String(prebuilt.getClass().getName());
result.prebuiltString = javaToString(prebuilt);

var Hidden = java.lang.Object[ext]({
toString: function () {
return "worker hidden";
},
workerHiddenMarker: 1
});
var hidden = new Hidden();
result.hiddenClass = String(hidden.getClass().getName());
result.hiddenString = javaToString(hidden);
result.hiddenCreatedString = javaToString(hidden.getClass().newInstance());

var Owned = java.lang.Object.extend("WorkerOwnedName", {
toString: function () {
return "worker owned";
}
});
var owned = new Owned();
result.ownedClass = String(owned.getClass().getName());
result.ownedString = javaToString(owned);
result.ownedCreatedString = javaToString(owned.getClass().newInstance());
} catch (e) {
result.error = String(e && e.stack || e);
}
postMessage(result);
Loading
Loading