Skip to content

Commit

Permalink
wasm gc: support exporting Java classes to JavaScript
Browse files Browse the repository at this point in the history
  • Loading branch information
konsoletyper committed Sep 30, 2024
1 parent 0897a1b commit ed1cf44
Show file tree
Hide file tree
Showing 39 changed files with 932 additions and 231 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public class Renderer implements RenderingManager {

private final SourceWriter writer;
private final ListableClassReaderSource classSource;
private final ClassReaderSource originalClassSource;
private final ClassLoader classLoader;
private final Properties properties = new Properties();
private final ServiceRepository services;
Expand All @@ -103,6 +104,7 @@ public Renderer(SourceWriter writer, Set<MethodReference> asyncMethods, Renderin
List<ExportedDeclaration> exports, String entryPoint) {
this.writer = writer;
this.classSource = context.getClassSource();
this.originalClassSource = context.getInitialClassSource();
this.classLoader = context.getClassLoader();
this.services = context.getServices();
this.asyncMethods = new HashSet<>(asyncMethods);
Expand Down Expand Up @@ -152,6 +154,11 @@ public ListableClassReaderSource getClassSource() {
return classSource;
}

@Override
public ClassReaderSource getOriginalClassSource() {
return originalClassSource;
}

@Override
public ClassLoader getClassLoader() {
return classLoader;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.Properties;
import org.teavm.backend.javascript.codegen.SourceWriter;
import org.teavm.common.ServiceRepository;
import org.teavm.model.ClassReaderSource;
import org.teavm.model.ListableClassReaderSource;
import org.teavm.model.MethodReference;

Expand All @@ -32,6 +33,8 @@ public interface RenderingManager extends ServiceRepository {

ListableClassReaderSource getClassSource();

ClassReaderSource getOriginalClassSource();

ClassLoader getClassLoader();

Properties getProperties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ public void emit(ListableClassHolderSource classes, BuildTarget buildTarget, Str
var declarationsGenerator = new WasmGCDeclarationsGenerator(
module,
classes,
controller.getUnprocessedClassSource(),
controller.getClassLoader(),
controller.getClassInitializerInfo(),
controller.getDependencyInfo(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.teavm.dependency.DependencyInfo;
import org.teavm.diagnostics.Diagnostics;
import org.teavm.model.ClassHierarchy;
import org.teavm.model.ClassReaderSource;
import org.teavm.model.ListableClassHolderSource;
import org.teavm.model.MethodReference;
import org.teavm.model.analysis.ClassInitializerInfo;
Expand All @@ -52,6 +53,7 @@ public class WasmGCDeclarationsGenerator {
public WasmGCDeclarationsGenerator(
WasmModule module,
ListableClassHolderSource classes,
ClassReaderSource originalClasses,
ClassLoader classLoader,
ClassInitializerInfo classInitializerInfo,
DependencyInfo dependencyInfo,
Expand Down Expand Up @@ -87,6 +89,7 @@ public WasmGCDeclarationsGenerator(
classGenerator = new WasmGCClassGenerator(
module,
classes,
originalClasses,
hierarchy,
dependencyInfo,
functionTypes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public class WasmGCClassGenerator implements WasmGCClassInfoProvider, WasmGCInit

private final WasmModule module;
private ClassReaderSource classSource;
private ClassReaderSource originalClassSource;
private ClassHierarchy hierarchy;
private WasmFunctionTypes functionTypes;
private TagRegistry tagRegistry;
Expand Down Expand Up @@ -158,14 +159,15 @@ public class WasmGCClassGenerator implements WasmGCClassInfoProvider, WasmGCInit
private boolean hasLoadServices;

public WasmGCClassGenerator(WasmModule module, ClassReaderSource classSource,
ClassHierarchy hierarchy, DependencyInfo dependencyInfo,
ClassReaderSource originalClassSource, ClassHierarchy hierarchy, DependencyInfo dependencyInfo,
WasmFunctionTypes functionTypes, TagRegistry tagRegistry,
ClassMetadataRequirements metadataRequirements, WasmGCVirtualTableProvider virtualTables,
BaseWasmFunctionRepository functionProvider, WasmGCNameProvider names,
ClassInitializerInfo classInitializerInfo,
List<WasmGCCustomTypeMapperFactory> customTypeMapperFactories) {
this.module = module;
this.classSource = classSource;
this.originalClassSource = originalClassSource;
this.hierarchy = hierarchy;
this.functionTypes = functionTypes;
this.tagRegistry = tagRegistry;
Expand Down Expand Up @@ -195,6 +197,11 @@ public WasmGCClassGenerator(WasmModule module, ClassReaderSource classSource,

private WasmGCCustomTypeMapperFactoryContext customTypeMapperFactoryContext() {
return new WasmGCCustomTypeMapperFactoryContext() {
@Override
public ClassReaderSource originalClasses() {
return originalClassSource;
}

@Override
public ClassReaderSource classes() {
return classSource;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
public interface WasmGCCustomTypeMapperFactoryContext {
ClassReaderSource classes();

ClassReaderSource originalClasses();

WasmModule module();

WasmGCClassInfoProvider classInfoProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -433,5 +433,10 @@ public Diagnostics diagnostics() {
public WasmGCStringProvider strings() {
return context.strings();
}

@Override
public void addToInitializer(Consumer<WasmFunction> initializerContributor) {
context.addToInitializer(initializerContributor);
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
*/
package org.teavm.backend.wasm.generators.gc;

import java.util.function.Consumer;
import org.teavm.backend.wasm.BaseWasmFunctionRepository;
import org.teavm.backend.wasm.WasmFunctionTypes;
import org.teavm.backend.wasm.generate.gc.WasmGCNameProvider;
import org.teavm.backend.wasm.generate.gc.classes.WasmGCClassInfoProvider;
import org.teavm.backend.wasm.generate.gc.classes.WasmGCTypeMapper;
import org.teavm.backend.wasm.generate.gc.strings.WasmGCStringProvider;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmModule;
import org.teavm.backend.wasm.model.WasmTag;
import org.teavm.diagnostics.Diagnostics;
Expand Down Expand Up @@ -48,4 +50,6 @@ public interface WasmGCCustomGeneratorContext {
Diagnostics diagnostics();

WasmGCStringProvider strings();

void addToInitializer(Consumer<WasmFunction> initializerContributor);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright 2024 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.backend.wasm.model.expression;

public class WasmExternConversion {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2024 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.backend.wasm.model.expression;

public enum WasmExternConversionType {
EXTERN_TO_OBJECT,
OBJECT_TO_EXTERN
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,8 @@ let $rt_apply = (instance, method, args) => instance[method].apply(instance, arg

let $rt_apply_topLevel = (method, args) => method.apply(null, args);

let $rt_skip = (array, count) => count === 0 ? array : Array.prototype.slice.call(array, count);
let $rt_skip = (array, count) => count === 0 ? array : Array.prototype.slice.call(array, count);

let $rt_callWithReceiver = f => function() {
return f.apply(null, [this].concat(Array.prototype.slice.call(arguments)));
}
105 changes: 71 additions & 34 deletions core/src/main/resources/org/teavm/backend/wasm/wasm-gc-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ TeaVM.wasm = function() {
let getGlobalName = function(name) {
return eval(name);
}
let javaObjectSymbol = Symbol("javaObject");
let javaWrappers = new WeakMap();
function defaults(imports) {
let stderr = "";
let stdout = "";
Expand All @@ -32,42 +34,28 @@ TeaVM.wasm = function() {
exports.reportGarbageCollectedString(heldValue);
});
imports.teavmDate = {
currentTimeMillis() {
return new Date().getTime();
},
dateToString(timestamp) {
return stringToJava(new Date(timestamp).toString());
},
getYear(timestamp) {
return new Date(timestamp).getFullYear();
},
currentTimeMillis: () => new Date().getTime(),
dateToString: timestamp => stringToJava(new Date(timestamp).toString()),
getYear: timestamp =>new Date(timestamp).getFullYear(),
setYear(timestamp, year) {
let date = new Date(timestamp);
date.setFullYear(year);
return date.getTime();
},
getMonth(timestamp) {
return new Date(timestamp).getMonth();
},
getMonth: timestamp =>new Date(timestamp).getMonth(),
setMonth(timestamp, month) {
let date = new Date(timestamp);
date.setMonth(month);
return date.getTime();
},
getDate(timestamp) {
return new Date(timestamp).getDate();
},
getDate: timestamp =>new Date(timestamp).getDate(),
setDate(timestamp, value) {
let date = new Date(timestamp);
date.setDate(value);
return date.getTime();
},
create(year, month, date, hrs, min, sec) {
return new Date(year, month, date, hrs, min, sec).getTime();
},
createFromUTC(year, month, date, hrs, min, sec) {
return Date.UTC(year, month, date, hrs, min, sec);
}
create: (year, month, date, hrs, min, sec) => new Date(year, month, date, hrs, min, sec).getTime(),
createFromUTC: (year, month, date, hrs, min, sec) => Date.UTC(year, month, date, hrs, min, sec)
};
imports.teavmConsole = {
putcharStderr(c) {
Expand Down Expand Up @@ -106,6 +94,22 @@ TeaVM.wasm = function() {
function identity(value) {
return value;
}
function sanitizeName(str) {
let result = "";
let firstChar = str.charAt(0);
result += isIdentifierStart(firstChar) ? firstChar : '_';
for (let i = 1; i < str.length; ++i) {
let c = str.charAt(i)
result += isIdentifierPart(c) ? c : '_';
}
return result;
}
function isIdentifierStart(s) {
return s >= 'A' && s <= 'Z' || s >= 'a' && s <= 'z' || s === '_' || s === '$';
}
function isIdentifierPart(s) {
return isIdentifierStart(s) || s >= '0' && s <= '9';
}
imports.teavmJso = {
emptyString: () => "",
stringFromCharCode: code => String.fromCharCode(code),
Expand All @@ -120,25 +124,58 @@ TeaVM.wasm = function() {
getPropertyPure: (obj, prop) => obj[prop],
setProperty: (obj, prop, value) => obj[prop] = value,
setPropertyPure: (obj, prop) => obj[prop] = value,
global: getGlobalName
global: getGlobalName,
createClass(name) {
let fn = new Function(
"javaObjectSymbol",
"return function JavaClass_" + sanitizeName(name)
+ "(javaObject) { this[javaObjectSymbol] = javaObject; };"
);
return fn(javaObjectSymbol);
},
defineMethod(cls, name, fn) {
cls.prototype[name] = function(...args) {
return fn(this, ...args);
}
},
defineProperty(cls, name, getFn, setFn) {
let descriptor = {
get() {
return getFn(this);
}
};
if (setFn !== null) {
descriptor.set = function(value) {
setFn(this, value);
}
}
Object.defineProperty(cls.prototype, name, descriptor);
},
javaObjectToJS(instance, cls) {
let existing = javaWrappers.get(instance);
if (typeof existing != "undefined") {
let result = existing.deref();
if (typeof result !== "undefined") {
return result;
}
}
let obj = new cls(instance);
javaWrappers.set(instance, new WeakRef(obj));
return obj;
},
unwrapJavaObject(instance) {
return instance[javaObjectSymbol];
}
};
for (let name of ["wrapByte", "wrapShort", "wrapChar", "wrapInt", "wrapFloat", "wrapDouble", "unwrapByte",
"unwrapShort", "unwrapChar", "unwrapInt", "unwrapFloat", "unwrapDouble"]) {
imports.teavmJso[name] = identity;
}
for (let i = 0; i < 32; ++i) {
imports.teavmJso["createFunction" + i] = function() {
return new Function(...arguments);
};
imports.teavmJso["callFunction" + i] = function(fn, ...args) {
return fn(...args);
};
imports.teavmJso["callMethod" + i] = function(instance, method, ...args) {
return instance[method](...args);
};
imports.teavmJso["construct" + i] = function(constructor, ...args) {
return new constructor(...args);
};
imports.teavmJso["createFunction" + i] = (...args) => new Function(...args);
imports.teavmJso["callFunction" + i] = (fn, ...args) => fn(...args);
imports.teavmJso["callMethod" + i] = (instance, method, ...args) => instance[method](...args);
imports.teavmJso["construct" + i] = (constructor, ...args) => new constructor(...args);
}
imports.teavmMath = Math;
}
Expand Down
Loading

0 comments on commit ed1cf44

Please sign in to comment.