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 29, 2024
1 parent 0897a1b commit f960b4f
Show file tree
Hide file tree
Showing 31 changed files with 807 additions and 211 deletions.
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
Expand Up @@ -27,6 +27,7 @@
import org.teavm.backend.wasm.runtime.gc.WasmGCResources;
import org.teavm.backend.wasm.runtime.gc.WasmGCSupport;
import org.teavm.common.ServiceRepository;
import org.teavm.model.ClassHierarchy;
import org.teavm.model.ClassReaderSource;
import org.teavm.model.MethodReference;

Expand Down
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
}
80 changes: 58 additions & 22 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,7 +124,39 @@ 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] = fn;
},
defineProperty(cls, name, get, set) {
Object.defineProperty(cls.prototype, name, {
get: get,
set: set !== null ? set : void 0
});
},
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"]) {
Expand Down
129 changes: 129 additions & 0 deletions jso/impl/src/main/java/org/teavm/jso/impl/AliasCollector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* 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.jso.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.teavm.model.ClassReader;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;

public class AliasCollector {
private AliasCollector() {
}

public static boolean isStaticMember(MethodReader method) {
return !isInstanceMember(method);
}

public static boolean isInstanceMember(MethodReader method) {
return method.getAnnotations().get(JSInstanceExpose.class.getName()) != null;
}

public static Members collectMembers(ClassReader classReader, Predicate<MethodReader> filter) {
var methods = new HashMap<String, MethodReference>();
var properties = new HashMap<String, PropertyInfo>();
MethodReference constructor = null;
for (var method : classReader.getMethods()) {
if (!filter.test(method)) {
continue;
}
var methodAlias = getPublicAlias(method);
if (methodAlias != null) {
switch (methodAlias.kind) {
case METHOD:
methods.put(methodAlias.name, method.getReference());
break;
case GETTER: {
var propInfo = properties.computeIfAbsent(methodAlias.name, k -> new PropertyInfo());
propInfo.getter = method.getReference();
break;
}
case SETTER: {
var propInfo = properties.computeIfAbsent(methodAlias.name, k -> new PropertyInfo());
propInfo.setter = method.getReference();
break;
}
case CONSTRUCTOR:
constructor = method.getReference();
break;
}
}
}
return new Members(methods, properties, constructor);
}

public static Alias getPublicAlias(MethodReader method) {
var annot = method.getAnnotations().get(JSMethodToExpose.class.getName());
if (annot != null) {
return new Alias(annot.getValue("name").getString(), AliasKind.METHOD);
}

annot = method.getAnnotations().get(JSGetterToExpose.class.getName());
if (annot != null) {
return new Alias(annot.getValue("name").getString(), AliasKind.GETTER);
}

annot = method.getAnnotations().get(JSSetterToExpose.class.getName());
if (annot != null) {
return new Alias(annot.getValue("name").getString(), AliasKind.SETTER);
}

annot = method.getAnnotations().get(JSConstructorToExpose.class.getName());
if (annot != null) {
return new Alias(null, AliasKind.CONSTRUCTOR);
}

return null;
}

public static class Members {
public final Map<String, MethodReference> methods;
public final Map<String, PropertyInfo> properties;
public final MethodReference constructor;

Members(Map<String, MethodReference> methods, Map<String, PropertyInfo> properties,
MethodReference constructor) {
this.methods = methods;
this.properties = properties;
this.constructor = constructor;
}
}


public static class PropertyInfo {
public MethodReference getter;
public MethodReference setter;
}

public static class Alias {
public final String name;
public final AliasKind kind;

Alias(String name, AliasKind kind) {
this.name = name;
this.kind = kind;
}
}

public enum AliasKind {
METHOD,
GETTER,
SETTER,
CONSTRUCTOR
}
}
Loading

0 comments on commit f960b4f

Please sign in to comment.