Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,6 @@
# tools/teavm-patches
- TeaVM's code under its Apache 2.0 header. Change only what a fix needs; describe it in README.md.
- Never put Incari code in `src/main`; it's excluded from formatting and lint. The tests in
`src/test` are Incari code, formatted and linted as usual.
- Test class library fixes against the JDK's behaviour: `./gradlew :tools:teavm-patches:check`.
@@ -0,0 +1,79 @@
# tools/teavm-patches: fixes to TeaVM
Fixes to TeaVM 0.16.0 the browser build needs before a TeaVM release has them. Each file is TeaVM's
own source (Apache-2.0, header kept), with the change described in its header. `tools/webbuild`
puts this module ahead of TeaVM on its class path, and checks at start-up that these classes won.
Nothing here ships except through TeaVM's compiler.
## Fixes
All are worth reporting upstream (konsoletyper/teavm). Probes run with `app-web/probes/run.sh <Name>`;
tests run on the JVM.
| Class | Bug | What it broke | Check |
| --- | --- | --- | --- |
| `CoroutineTransformation` | Blocks around suspensions used non-null types for values restored as nullable | Module failed to validate (`BanListEntry.serialize`) | — |
| `CoroutineTransformation` | Non-nullable locals read before any set on the save path | "uninitialized non-defaultable local" in reflection callers | `SuspendingReflectionProbe` |
| `ClassInitializerInsertionTransformer` | Subclass initialized before its superclass (against JLS 12.4.2) | "Duplicate id value" creating the player | `InitOrderProbe` |
| `TObject` | Interrupted `wait()` didn't retake the monitor | Crash when joining a world (sound thread) | `InterruptedWaitProbe` |
| `TArrayDeque` | Iterator `remove()` skipped the shifted element; removal shifted in a loop | Crash on the first expired particle; slow removals | `ArrayDequeProbe` |
| `TZipFile` | Inflater got no trailing byte at an entry's end | 638 textures lost from a community pack | `ZipFileProbe` |
| `TTemplateCollections` | Empty immutable map divided by zero in `get()` | Crash entering the End | `EmptyTemplateMapTest` |
| `TTemplateCollections` | `Set.of`/`Map.of` lookups compared every element | Slow lookups (ADR 0034) | `ImmutableCollectionsProbe` |
| `TCollections` | `unmodifiableCollection` scanned every element for `contains` | Slow model discovery (sets and maps fixed in 0.16.0) | `UnmodifiableViewsTest` |
| `StringConcatFactorySubstitutor` | Concatenation called `toString` virtually | Every concatenation, so every exception, became a coroutine | — |
| `WasmGCReferenceQueueDependency` | Polled references typed as plain `WeakReference` | Null trap in Guava's weak maps (Optimize World) | `WeakQueueProbe` |
| `WeakReferenceIntrinsic` | `new WeakReference<>(null)` reached `new WeakRef(null)` | Uncatchable `TypeError` | — |
| `TPath` | `Path.of(URI)` failed for any `file:` URI but `file:///` | The game couldn't find its built-in packs | — |
| `ClassInitElimination` | Interface method calls counted as initializing the interface | A `catch` saw null for an interface constant | — |
| `TDefaultPath` | `resolve` from an empty path, or after the root | Listing resource packs | — |
| `TByteBufferImpl`, `TByteBufferNative` | Absolute `getLong(int)` moved the position | Every PNG read skipped 8 bytes | — |
| `TByteBuffer` | Absolute bulk `put` copied nothing when the source had no bytes after its position | Zero projection matrix; blank sprites | `AbsoluteBulkPutTest` |
| `TByteBuffer` | `allocateDirect` memory not zeroed | Region files read chunks from garbage offsets | — |
| `TFormatter` | `%%` and `%n` consumed arguments; `MIN_VALUE` printed `--` | F3 screen crashed | `FormatterTest` |
| `TSortedStreamImpl`, `TSimpleStreamImpl` | Sorted stream kept the source's size estimate | Tab list crashed in multiplayer | `StreamToArrayTest` |
| `WasmGCJsoCommonGenerator` | Functions given to JavaScript weren't exported | Binaryen's `--closed-world` deleted `main` (ADR 0034) | — |
| `WasmGCSupertypeFunctionGenerator` | `instanceof` and casts walked every tag range of a widely implemented interface | Slow type checks at start-up (ADR 0026) | — |
| `CoroutineFunctions`, `WasmGCDependencies` | 0.16.0's coroutines check the fiber with static `isPresentAndSuspending(fiber)`, twice the code of 0.15's `isSuspending()` and called after every call that may suspend; V8 then inlined less of the game | Compatible build 17% slower in the lobby at 4x throttle (ADR 0064) | — |
| `ReflectionMetadataGenerator`, `WasmGCModuleGenerator` | Reflection setup and start function were single huge functions | V8's optimizer ran out of memory and Chrome killed the tab (ADR 0042) | — |
## JSPI: the Fast build
Not a fix, but a second way to run threads (ADR 0036). TeaVM compiles 81% of this program as
coroutines, which run about 1.5x slower (`CoroutineCostProbe`). JSPI lets the browser keep the
suspended stack instead.
- `AsyncMethodFinder`: with `incari.jspi` set (only in a `--jspi` build), finds no async methods,
so nothing is compiled as a coroutine.
- `Fiber`: adds `Fiber.Jspi`. Each fiber runs through `WebAssembly.promising`; `suspend` awaits a
promise through a `WebAssembly.Suspending` import (`app-web`'s `jspi.ts`). `tools/webbuild`'s
`JspiTransformer` routes `Fiber.suspend` and `Fiber.start` there.
Differences from coroutines:
- A woken thread resumes from a microtask, not inside the call that woke it.
- A JavaScript callback into Java still must not suspend (JSPI traps).
- V8 never frees a suspended stack. So on `pagehide`, `jspi.ts` resumes each waiting fiber with an
order to end, and it unwinds by trapping, with no Java code run. Without this, every reload
leaked the whole game.
`JspiProbe` checks threads behave the same in both builds.
## Fixed upstream
TeaVM 0.16.0 has these, so the patches went (ADR 0064): `WasmTypeInference`; `CoroutineTransformation`'s
type after a suspending `c ? a : b`; `TThrowable`'s suppressed array; `Heap` growth; `instanceof Item[]`
(`WasmGCInstructionGenerationVisitor`, `WasmGCSupertypeFunctionGenerator`); the absolute bulk `put` in
`TByteBufferImpl` and `TByteBufferNative`; `TCollections`' set and map views; `TDefaultPath`'s
`iterator` and `equals`. Their probes still run.
## Invariants
- One class per fix, as close to upstream as possible, the change described here and in the file.
- Drop a patch when the pinned TeaVM has the fix.
## Tests
```sh
./gradlew :tools:teavm-patches:check
```
@@ -0,0 +1,37 @@
import net.ltgt.gradle.errorprone.errorprone
plugins {
`java-library`
}
// Fixes to TeaVM classes, shadowing TeaVM's own on the web build's class path (README.md).
// TeaVM's code (Apache License 2.0), kept in its own style: not reformatted, not linted.
// The tests are Incari code and follow the usual rules.
dependencies {
compileOnly(libs.teavm.core)
compileOnly(libs.teavm.classlib)
compileOnly(libs.teavm.jso)
compileOnly(libs.teavm.jso.impl)
// The JSO generator's JavaScript bodies are Rhino trees (TeaVM's relocated copy).
compileOnly("org.teavm:teavm-relocated-libs-rhino:${libs.versions.teavm.get()}")
// Class library fixes run on the JVM in the tests, checked against the JDK's own behaviour.
testImplementation(libs.teavm.classlib)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testRuntimeOnly(libs.junit.launcher)
}
tasks.named<JavaCompile>("compileJava") {
options.compilerArgs.removeAll { it.startsWith("-Xlint") || it == "-Werror" }
options.errorprone.enabled = false
}
configure<com.diffplug.gradle.spotless.SpotlessExtension> {
java {
// Third-party code keeps its upstream formatting.
targetExclude("src/main/**/*.java")
}
}
@@ -0,0 +1,141 @@
/*
* 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the start function, teavm@initializer,
* is split where its operand stack is empty into functions of about CHUNK_INSTRUCTIONS
* instructions each, which it calls in turn (5 MB of code in the game's build, run once by each
* instance; V8 sent it to its optimizing compiler once enough instances had, which took gigabytes
* of memory on it: ADR 0042).
*/
package org.teavm.backend.wasm;
import org.teavm.backend.wasm.generate.WasmGCDeclarationsGenerator;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmGlobal;
import org.teavm.backend.wasm.model.instruction.WasmBranch;
import org.teavm.backend.wasm.model.instruction.WasmBreak;
import org.teavm.backend.wasm.model.instruction.WasmInstruction;
import org.teavm.backend.wasm.model.instruction.WasmInstructionList;
import org.teavm.backend.wasm.model.instruction.WasmIntBinaryOperation;
import org.teavm.backend.wasm.model.instruction.WasmIntType;
import org.teavm.backend.wasm.model.instruction.WasmReturn;
import org.teavm.backend.wasm.model.instruction.WasmSwitch;
import org.teavm.backend.wasm.model.instruction.WasmTypeInference;
import org.teavm.backend.wasm.runtime.StringInternPool;
import org.teavm.interop.Address;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
import org.teavm.runtime.heap.Heap;
public class WasmGCModuleGenerator {
private WasmGCDeclarationsGenerator declarationsGenerator;
private WasmFunction initializer;
private static final int CHUNK_INSTRUCTIONS = 4000;
public WasmGCModuleGenerator(WasmGCDeclarationsGenerator declarationsGenerator) {
this.declarationsGenerator = declarationsGenerator;
}
public void generate() {
declarationsGenerator.generate();
createInitializer();
}
public void initBuffersHeap(WasmGlobal offset, int minSize, WasmGlobal heapLimit) {
var target = declarationsGenerator.functions().forStaticMethod(new MethodReference(Heap.class,
"init", Address.class, int.class, int.class, void.class));
var builder = new WasmInstructionList().builder();
builder
.getGlobal(offset)
.i32Const(minSize)
.getGlobal(heapLimit)
.getGlobal(offset)
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.SUB)
.call(target);
initializer.getBody().transferFrom(builder.list);
}
public WasmFunction generateReportGarbageCollectedStringFunction() {
var entryType = ValueType.object(StringInternPool.class.getName() + "$Entry");
return declarationsGenerator.functions().forStaticMethod(new MethodReference(
StringInternPool.class.getName(),
"remove",
entryType,
ValueType.VOID
));
}
private void createInitializer() {
var functionType = declarationsGenerator.functionTypes.of(null);
initializer = new WasmFunction(functionType);
initializer.setName("teavm@initializer");
declarationsGenerator.module.functions.add(initializer);
declarationsGenerator.module.setStartFunction(initializer);
declarationsGenerator.contributeToInitializer(initializer);
splitInitializer();
}
private void splitInitializer() {
if (!initializer.getLocalVariables().isEmpty()) {
return;
}
// Where to split: after an instruction that leaves the stack empty, once a chunk is full.
var inference = new WasmTypeInference();
var ends = new java.util.HashSet<WasmInstruction>();
int size = 0;
int total = 0;
try {
for (var insn : initializer.getBody()) {
if (insn instanceof WasmReturn || insn instanceof WasmBranch || insn instanceof WasmBreak
|| insn instanceof WasmSwitch) {
return;
}
insn.acceptVisitor(inference);
size++;
total++;
if (size >= CHUNK_INSTRUCTIONS && inference.typeStack.isEmpty()) {
ends.add(insn);
size = 0;
}
}
} catch (RuntimeException e) {
return;
}
if (ends.isEmpty() || !inference.typeStack.isEmpty() || total <= CHUNK_INSTRUCTIONS) {
return;
}
var body = initializer.getBody();
var calls = new java.util.ArrayList<WasmFunction>();
WasmFunction chunk = null;
while (body.getFirst() != null) {
var insn = body.getFirst();
insn.delete();
if (chunk == null) {
chunk = new WasmFunction(declarationsGenerator.functionTypes.of(null));
chunk.setName("teavm@initializer$" + calls.size());
declarationsGenerator.module.functions.add(chunk);
calls.add(chunk);
}
chunk.getBody().add(insn);
if (ends.contains(insn)) {
chunk = null;
}
}
var builder = body.builder();
for (var function : calls) {
builder.call(function);
}
}
}
@@ -0,0 +1,194 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): also links Fiber's instance checks
* isResuming() and isSuspending(), which tools/teavm-patches' CoroutineFunctions has coroutines
* call, as TeaVM 0.15 did.
*/
package org.teavm.backend.wasm.dependencies;
import java.util.Arrays;
import java.util.List;
import org.teavm.backend.wasm.WasmRuntime;
import org.teavm.backend.wasm.runtime.WasmGCSupport;
import org.teavm.dependency.AbstractDependencyListener;
import org.teavm.dependency.DependencyAgent;
import org.teavm.dependency.DependencyAnalyzer;
import org.teavm.interop.Address;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
import org.teavm.runtime.EventQueue;
import org.teavm.runtime.Fiber;
import org.teavm.runtime.heap.Heap;
public class WasmGCDependencies {
private DependencyAnalyzer analyzer;
public WasmGCDependencies(DependencyAnalyzer analyzer) {
this.analyzer = analyzer;
}
public void contribute() {
analyzer.linkClass("java.lang.Class");
contributeWasmRuntime();
contributeMathUtils();
contributeExceptionUtils();
contributeInitializerUtils();
contributeString();
contributeBuffers();
contributeFiber();
analyzer.addDependencyListener(new WasmGCReferenceQueueDependency());
analyzer.addDependencyListener(new WasmGCResourceDependency());
analyzer.addDependencyListener(new SystemArrayCopyDependencySupport());
analyzer.addDependencyListener(new WasmGCSignatureDependencyListener());
analyzer.addDependencyListener(new WasmGCExportDependencyListener());
}
public void contributeStandardExports() {
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "createStringArray", int.class, String[].class))
.use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "createStringBuilder", StringBuilder.class))
.use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "setToStringArray", String[].class,
int.class, String.class, void.class))
.propagate(1, analyzer.getType(ValueType.arrayOf(ValueType.object("java.lang.String"))))
.propagate(3, analyzer.getClassType("java.lang.String"))
.use();
analyzer.linkMethod(new MethodReference(StringBuilder.class, "append", char.class, StringBuilder.class))
.propagate(0, analyzer.getClassType("java.lang.StringBuilder"))
.use();
analyzer.linkMethod(new MethodReference(StringBuilder.class, "toString", String.class))
.propagate(0, analyzer.getClassType("java.lang.StringBuilder"))
.use();
analyzer.linkMethod(new MethodReference(String.class, "length", int.class))
.propagate(0, analyzer.getClassType("java.lang.String"))
.use();
analyzer.linkMethod(new MethodReference(String.class, "charAt", int.class, char.class))
.propagate(0, analyzer.getClassType("java.lang.String"))
.use();
}
private void contributeWasmRuntime() {
for (var cls : List.of(int.class, long.class, float.class, double.class)) {
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "lt", cls, cls, boolean.class)).use();
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "gt", cls, cls, boolean.class)).use();
}
for (var cls : List.of(int.class, long.class)) {
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "ltu", cls, cls, boolean.class)).use();
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "gtu", cls, cls, boolean.class)).use();
}
for (var cls : List.of(float.class, double.class)) {
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "min", cls, cls, cls)).use();
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "max", cls, cls, cls)).use();
}
}
private void contributeMathUtils() {
for (var type : Arrays.asList(int.class, long.class, float.class, double.class)) {
var method = new MethodReference(WasmRuntime.class, "compare", type, type, int.class);
analyzer.linkMethod(method).use();
}
for (var type : Arrays.asList(float.class, double.class)) {
var method = new MethodReference(WasmRuntime.class, "compareLess", type, type, int.class);
analyzer.linkMethod(method).use();
}
for (var type : Arrays.asList(int.class, long.class)) {
var method = new MethodReference(WasmRuntime.class, "compareUnsigned", type, type, int.class);
analyzer.linkMethod(method).use();
}
for (var type : Arrays.asList(float.class, double.class)) {
var method = new MethodReference(WasmRuntime.class, "remainder", type, type, type);
analyzer.linkMethod(method).use();
}
}
private void contributeExceptionUtils() {
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "npe", NullPointerException.class))
.use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "aiiobe", ArrayIndexOutOfBoundsException.class))
.use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "cce", ClassCastException.class)).use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "throwCloneNotSupportedException",
void.class)).use();
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "defaultClone", Object.class, Object.class)).use();
analyzer.linkMethod(new MethodReference(NullPointerException.class, "<init>", void.class)).use();
analyzer.linkMethod(new MethodReference(Throwable.class, "getMessage", String.class))
.propagate(0, Throwable.class).use();
analyzer.addDependencyListener(new AbstractDependencyListener() {
@Override
public void classReached(DependencyAgent agent, String className) {
if (className.equals(Throwable.class.getName())) {
agent.linkMethod(new MethodReference(Throwable.class, "getMessage", String.class))
.propagate(0, Throwable.class)
.use();
}
}
});
}
private void contributeInitializerUtils() {
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "nextCharArray", char[].class)).use();
}
private void contributeString() {
analyzer.addDependencyListener(new StringInternDependencySupport());
}
private void contributeBuffers() {
analyzer.linkMethod(new MethodReference(Heap.class, "init", Address.class, int.class, int.class,
void.class)).use();
}
private void contributeFiber() {
analyzer.linkMethod(new MethodReference(Fiber.class, "isPresentAndResuming", Fiber.class, boolean.class))
.propagate(1, Fiber.class)
.use();
analyzer.linkMethod(new MethodReference(Fiber.class, "isPresentAndSuspending", Fiber.class, boolean.class))
.propagate(1, Fiber.class)
.use();
// Incari: what coroutines call (CoroutineFunctions).
analyzer.linkMethod(new MethodReference(Fiber.class, "isResuming", boolean.class)).use();
analyzer.linkMethod(new MethodReference(Fiber.class, "isSuspending", boolean.class)).use();
analyzer.linkMethod(new MethodReference(Fiber.class, "current", Fiber.class)).use();
analyzer.linkMethod(new MethodReference(Thread.class, "setCurrentThread", Thread.class,
void.class)).use();
var offerMethod = analyzer.linkMethod(new MethodReference(EventQueue.class, "offer", EventQueue.Event.class,
long.class, int.class));
var runEventMethod = analyzer.linkMethod(new MethodReference(EventQueue.class, "run", EventQueue.Event.class,
void.class));
offerMethod.getVariable(1).addConsumer(type -> {
runEventMethod.getVariable(1).propagate(type);
runEventMethod.use();
});
var fiberClass = analyzer.getClassSource().get(Fiber.class.getName());
for (MethodReader method : fiberClass.getMethods()) {
if (method.getName().startsWith("pop")) {
analyzer.linkMethod(method.getReference())
.propagate(0, Fiber.class)
.use();
} else if (method.getName().equals("reversePush")) {
analyzer.linkMethod(method.getReference())
.propagate(2, Fiber.class)
.use();
}
}
}
}
@@ -0,0 +1,84 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): ReferenceQueue.supply, which the
* finalization callback hands every collected reference to, got only WeakReference itself as
* its argument's type, not the subclasses actually made with a queue. The analysis then took
* poll()'s results for plain WeakReferences and left the subclasses' own methods out where
* they're called on them: Guava's weak-value maps (the game's ResourceKey interner) called
* WeakValueReference.getEntry() through an empty vtable slot and the page trapped. The types
* that reach the queue constructor's receiver now flow into supply().
*/
package org.teavm.backend.wasm.dependencies;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import org.teavm.dependency.AbstractDependencyListener;
import org.teavm.dependency.DependencyAgent;
import org.teavm.dependency.DependencyNode;
import org.teavm.dependency.MethodDependency;
import org.teavm.model.MethodReference;
public class WasmGCReferenceQueueDependency extends AbstractDependencyListener {
private DependencyNode valueNode;
// Incari: the classes of references made with a queue, for supply()'s argument.
private DependencyNode queuedReferenceNode;
private boolean supplyLinked;
private boolean refQueuePassedToRef;
private boolean refQueuePoll;
@Override
public void started(DependencyAgent agent) {
valueNode = agent.createNode();
queuedReferenceNode = agent.createNode();
}
@Override
public void methodReached(DependencyAgent agent, MethodDependency method) {
if (method.getMethod().getOwnerName().equals("java.lang.ref.WeakReference")) {
switch (method.getMethod().getName()) {
case "<init>":
if (method.getMethod().parameterCount() == 2) {
method.getVariable(0).connect(queuedReferenceNode);
refQueuePassedToRef = true;
checkRefQueue(agent);
}
method.getVariable(1).connect(valueNode);
break;
case "get":
valueNode.connect(method.getResult());
break;
}
} else if (method.getMethod().getOwnerName().equals(ReferenceQueue.class.getName())) {
if (method.getMethod().getName().equals("poll")) {
refQueuePoll = true;
checkRefQueue(agent);
}
}
}
private void checkRefQueue(DependencyAgent agent) {
if (refQueuePassedToRef && refQueuePoll && !supplyLinked) {
supplyLinked = true;
MethodDependency supply = agent.linkMethod(
new MethodReference(ReferenceQueue.class, "supply", Reference.class, void.class));
supply.propagate(0, ReferenceQueue.class)
.propagate(1, WeakReference.class);
queuedReferenceNode.connect(supply.getVariable(1));
supply.use();
}
}
}
@@ -0,0 +1,226 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): a class whose subclasses' tags fall in many
* ranges (an interface such as Function or Comparable, implemented all over the class hierarchy)
* finds the tag by a binary search of its ranges, where it walked every gap between them on each
* instanceof and cast.
*/
package org.teavm.backend.wasm.generate.classes;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import org.teavm.backend.wasm.WasmFunctionTypes;
import org.teavm.backend.wasm.generate.WasmGCNameProvider;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmFunctionType;
import org.teavm.backend.wasm.model.WasmLocal;
import org.teavm.backend.wasm.model.WasmModule;
import org.teavm.backend.wasm.model.WasmType;
import org.teavm.backend.wasm.model.instruction.WasmInt32Constant;
import org.teavm.backend.wasm.model.instruction.WasmIntBinaryOperation;
import org.teavm.backend.wasm.model.instruction.WasmIntType;
import org.teavm.model.ValueType;
import org.teavm.model.classes.TagRegistry;
public class WasmGCSupertypeFunctionGenerator implements WasmGCSupertypeFunctionProvider {
private Map<ValueType, WasmFunction> functions = new HashMap<>();
private WasmModule module;
private WasmGCClassGenerator classGenerator;
private WasmGCNameProvider nameProvider;
private TagRegistry tagRegistry;
private WasmFunctionTypes functionTypes;
private WasmFunctionType functionType;
private Queue<Runnable> queue;
private WasmFunction isArrayFunction;
WasmGCSupertypeFunctionGenerator(
WasmModule module,
WasmGCClassGenerator classGenerator,
WasmGCNameProvider nameProvider,
TagRegistry tagRegistry,
WasmFunctionTypes functionTypes,
Queue<Runnable> queue
) {
this.module = module;
this.classGenerator = classGenerator;
this.nameProvider = nameProvider;
this.tagRegistry = tagRegistry;
this.functionTypes = functionTypes;
this.queue = queue;
}
@Override
public WasmFunction getIsSupertypeFunction(ValueType type) {
if (type instanceof ValueType.Array) {
return getIsArraySupertypeFunction();
}
var result = functions.get(type);
if (result == null) {
result = generateIsSupertypeFunction(type);
functions.put(type, result);
}
return result;
}
private WasmFunction generateIsSupertypeFunction(ValueType type) {
var function = new WasmFunction(getFunctionType());
var classClass = classGenerator.standardClasses.classClass();
function.setName(nameProvider.topLevel(nameProvider.suggestForType(type) + "@isSupertypes"));
var subtypeVar = new WasmLocal(classClass.getType(), "subtype");
var supertypeVar = new WasmLocal(classClass.getType(), "supertype");
function.add(subtypeVar);
function.add(supertypeVar);
module.functions.add(function);
queue.add(() -> {
if (type instanceof ValueType.Object) {
var className = ((ValueType.Object) type).getClassName();
generateIsClass(subtypeVar, className, function);
} else {
var expected = classGenerator.getClassInfo(type).pointer;
function.getBody().builder()
.getLocal(subtypeVar)
.getGlobal(expected)
.refEqual();
}
});
return function;
}
private void generateIsClass(WasmLocal subtypeVar, String className, WasmFunction function) {
var ranges = tagRegistry.getRanges(className);
if (ranges.isEmpty()) {
function.getBody().add(new WasmInt32Constant(0));
return;
}
var classInfoStruct = classGenerator.reflectionTypes().classInfo().structure();
int tagOffset = classGenerator.reflectionTypes().classInfo().tagIndex();
var tagVar = new WasmLocal(WasmType.INT32, "tag");
function.add(tagVar);
ranges.sort(Comparator.comparingInt(range -> range.lower));
int lower = ranges.get(0).lower;
int upper = ranges.get(ranges.size() - 1).upper;
var body = function.getBody().builder();
if (ranges.size() > SEARCHED_RANGES) {
// Incari: a binary search of the ranges, which every path returns from.
body.getLocal(subtypeVar).structGet(classInfoStruct, tagOffset).setLocal(tagVar);
searchRanges(body, tagVar, ranges, 0, ranges.size());
body.unreachable();
return;
}
body.getLocal(subtypeVar).structGet(classInfoStruct, tagOffset).teeLocal(tagVar);
body.i32Const(lower).intBinary(WasmIntType.INT32, WasmIntBinaryOperation.LT_SIGNED);
body.conditional().getThenBlock().builder().i32Const(0).return_();
body.getLocal(tagVar).i32Const(upper).intBinary(WasmIntType.INT32, WasmIntBinaryOperation.GE_SIGNED);
body.conditional().getThenBlock().builder().i32Const(0).return_();
for (int i = 1; i < ranges.size(); ++i) {
int lowerHole = ranges.get(i - 1).upper;
int upperHole = ranges.get(i).lower;
body.getLocal(tagVar).i32Const(lowerHole)
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.GE_SIGNED);
var condHoleThen = body.conditional().getThenBlock().builder();
condHoleThen.getLocal(tagVar).i32Const(upperHole)
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.LT_SIGNED);
condHoleThen.conditional().getThenBlock().builder().i32Const(0).return_();
}
body.i32Const(1);
}
// Incari: above this many ranges a class's tag is found by a binary search rather than a walk.
private static final int SEARCHED_RANGES = 8;
/**
* Incari: returns 1 if the tag is in one of ranges[from..to), else 0. The ranges are sorted
* and don't overlap, so a tag below the middle range's lower bound can only be in the ranges
* before it, and one at or above it only in the middle range or those after it.
*/
private static void searchRanges(org.teavm.backend.wasm.model.instruction.WasmInstructionBuilder body,
WasmLocal tagVar, java.util.List<TagRegistry.Range> ranges, int from, int to) {
if (to - from <= 4) {
for (int i = from; i < to; ++i) {
var range = ranges.get(i);
body.getLocal(tagVar).i32Const(range.lower).intBinary(WasmIntType.INT32, WasmIntBinaryOperation.GE_SIGNED);
var inside = body.conditional().getThenBlock().builder();
inside.getLocal(tagVar).i32Const(range.upper).intBinary(WasmIntType.INT32, WasmIntBinaryOperation.LT_SIGNED);
inside.conditional().getThenBlock().builder().i32Const(1).return_();
}
body.i32Const(0).return_();
return;
}
int middle = (from + to) >>> 1;
body.getLocal(tagVar).i32Const(ranges.get(middle).lower)
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.LT_SIGNED);
var split = body.conditional();
searchRanges(split.getThenBlock().builder(), tagVar, ranges, from, middle);
searchRanges(split.getElseBlock().builder(), tagVar, ranges, middle, to);
}
WasmFunction getIsArraySupertypeFunction() {
if (isArrayFunction != null) {
return isArrayFunction;
}
var function = new WasmFunction(getFunctionType());
isArrayFunction = function;
module.functions.add(function);
var classInfoType = classGenerator.reflectionTypes().classInfo();
function.setName(nameProvider.topLevel("teavm@isArrayType"));
var subtypeVar = new WasmLocal(classInfoType.structure().getReference(), "subtype");
var supertypeVar = new WasmLocal(classInfoType.structure().getReference(), "supertype");
function.add(subtypeVar);
function.add(supertypeVar);
int itemOffset = classInfoType.itemTypeIndex();
var body = function.getBody().builder();
body.getLocal(supertypeVar).structGet(classInfoType.structure(), itemOffset).setLocal(supertypeVar);
body.getLocal(subtypeVar).structGet(classInfoType.structure(), itemOffset).setLocal(subtypeVar);
body.getLocal(subtypeVar).isNull();
var itemTest = body.conditional(WasmType.INT32);
itemTest.getThenBlock().builder().i32Const(0);
var funcType = functionTypes.of(WasmType.INT32, classInfoType.structure().getReference(),
classInfoType.structure().getReference());
var elseBody = itemTest.getElseBlock().builder();
elseBody.getLocal(subtypeVar).getLocal(supertypeVar)
.getLocal(supertypeVar).structGet(classInfoType.structure(), classInfoType.supertypeFunctionIndex())
.callReference(funcType);
return function;
}
@Override
public WasmFunctionType getFunctionType() {
if (functionType == null) {
var classInfoStruct = classGenerator.reflectionTypes().classInfo().structure().getReference();
functionType = functionTypes.of(WasmType.INT32, classInfoStruct, classInfoStruct);
}
return functionType;
}
}
@@ -0,0 +1,134 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the constructor leaves the reference
* empty for a null referent instead of passing null to JavaScript's WeakRef, which throws.
*/
package org.teavm.backend.wasm.intrinsics;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import org.teavm.backend.wasm.generate.classes.WasmGCClassInfoProvider;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmLocal;
import org.teavm.backend.wasm.model.WasmType;
import org.teavm.backend.wasm.model.instruction.WasmNullCondition;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
public class WeakReferenceIntrinsic implements WasmGCBodyIntrinsic {
private WasmGCCodeGenContext context;
private WasmFunction createWeakReferenceFunction;
public WeakReferenceIntrinsic(WasmGCCodeGenContext context) {
this.context = context;
}
@Override
public void apply(MethodReference method, WasmFunction function) {
switch (method.getName()) {
case "<init>":
generateConstructor(function);
break;
case "get":
generateDeref(function);
break;
case "clear":
generateClear(function);
break;
}
}
private void generateConstructor(WasmFunction function) {
var weakRefStruct = context.classInfoProvider().getClassInfo(WeakReference.class.getName()).getStructure();
var thisLocal = new WasmLocal(weakRefStruct.getReference(), "this");
var valueLocal = new WasmLocal(context.typeMapper().mapType(ValueType.parse(Object.class)), "value");
var queueLocal = new WasmLocal(context.typeMapper().mapType(ValueType.parse(ReferenceQueue.class)), "queue");
function.add(thisLocal);
function.add(valueLocal);
function.add(queueLocal);
var weakRefConstructor = getCreateWeakReferenceFunction();
var body = function.getBody().builder();
body.getLocal(valueLocal).isNull();
body.conditional().getThenBlock().builder().return_();
body.getLocal(thisLocal);
body.getLocal(valueLocal);
body.getLocal(thisLocal);
body.getLocal(queueLocal);
body.call(weakRefConstructor);
body.structSet(weakRefStruct, WasmGCClassInfoProvider.WEAK_REFERENCE_OFFSET);
}
private void generateDeref(WasmFunction function) {
var weakRefStruct = context.classInfoProvider().getClassInfo(WeakReference.class.getName()).getStructure();
var objectType = context.classInfoProvider().getClassInfo("java.lang.Object").getType();
var thisType = weakRefStruct.getReference();
var thisLocal = new WasmLocal(thisType, "this");
function.add(thisLocal);
var body = function.getBody().builder();
var block = body.block(WasmType.EXTERN);
block.getLocal(thisLocal);
block
.structGet(weakRefStruct, WasmGCClassInfoProvider.WEAK_REFERENCE_OFFSET)
.nullBranch(WasmNullCondition.NOT_NULL, block)
.nullConst(objectType)
.return_();
body.call(createDerefFunction());
}
private void generateClear(WasmFunction function) {
var weakRefStruct = context.classInfoProvider().getClassInfo(WeakReference.class.getName()).getStructure();
var thisType = weakRefStruct.getReference();
var thisLocal = new WasmLocal(thisType, "this");
function.add(thisLocal);
var body = function.getBody().builder();
body.getLocal(thisLocal);
body
.nullConst(WasmType.EXTERN)
.structSet(weakRefStruct, WasmGCClassInfoProvider.WEAK_REFERENCE_OFFSET);
}
private WasmFunction getCreateWeakReferenceFunction() {
if (createWeakReferenceFunction == null) {
var function = new WasmFunction(context.functionTypes().of(
WasmType.EXTERN,
context.typeMapper().mapType(ValueType.parse(Object.class)),
context.typeMapper().mapType(ValueType.parse(WeakReference.class)),
context.typeMapper().mapType(ValueType.parse(ReferenceQueue.class))
));
function.setName(context.names().topLevel("teavm@createWeakReference"));
function.setImportName("createWeakRef");
function.setImportModule("teavm");
context.module().functions.add(function);
createWeakReferenceFunction = function;
}
return createWeakReferenceFunction;
}
private WasmFunction createDerefFunction() {
var function = new WasmFunction(context.functionTypes().of(
context.typeMapper().mapType(ValueType.parse(Object.class)),
WasmType.EXTERN));
function.setName(context.names().topLevel("teavm@deref"));
function.setImportName("deref");
function.setImportModule("teavm");
context.module().functions.add(function);
return function;
}
}
@@ -0,0 +1,296 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): coroutines check the fiber with its
* instance methods isResuming() and isSuspending() again, as in TeaVM 0.15, not 0.16's static
* isPresentAndResuming(fiber) and isPresentAndSuspending(fiber). Those also accept a null fiber,
* which takes a test and a branch: twice the code in a function that every coroutine calls after
* each call that may suspend. In the Compatible build V8 then inlined less of the game's own small
* methods, and the lobby took 17% more CPU a frame at 4x throttle (ADR 0064). The game runs
* coroutines only on fibers, so the fiber is never null there.
*/
package org.teavm.backend.wasm.transformation;
import org.teavm.backend.wasm.BaseWasmFunctionRepository;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmFunctionType;
import org.teavm.backend.wasm.model.WasmLocal;
import org.teavm.backend.wasm.model.WasmType;
import org.teavm.backend.wasm.model.instruction.WasmCall;
import org.teavm.backend.wasm.model.instruction.WasmCast;
import org.teavm.backend.wasm.model.instruction.WasmExternConversion;
import org.teavm.backend.wasm.model.instruction.WasmExternConversionType;
import org.teavm.backend.wasm.model.instruction.WasmGetLocal;
import org.teavm.backend.wasm.model.instruction.WasmInstructionList;
import org.teavm.model.MethodReference;
import org.teavm.model.TextLocation;
import org.teavm.runtime.Fiber;
class CoroutineFunctions {
private BaseWasmFunctionRepository functions;
private WasmFunction pushIntCache;
private WasmFunction pushLongCache;
private WasmFunction pushFloatCache;
private WasmFunction pushDoubleCache;
private WasmFunction pushObjectCache;
private WasmFunction pushFunctionCache;
private WasmFunction pushExceptionCache;
private WasmFunction popIntCache;
private WasmFunction popLongCache;
private WasmFunction popFloatCache;
private WasmFunction popDoubleCache;
private WasmFunction popObjectCache;
private WasmFunction popFunctionCache;
private WasmFunction popExceptionCache;
private WasmFunction isResumingCache;
private WasmFunction isSuspendingCache;
private WasmFunction currentFiberCache;
CoroutineFunctions(BaseWasmFunctionRepository functions) {
this.functions = functions;
}
WasmFunction pushInt() {
if (pushIntCache == null) {
pushIntCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush", int.class,
Fiber.class, void.class));
}
return pushIntCache;
}
WasmFunction pushLong() {
if (pushLongCache == null) {
pushLongCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush", long.class,
Fiber.class, void.class));
}
return pushLongCache;
}
WasmFunction pushFloat() {
if (pushFloatCache == null) {
pushFloatCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush", float.class,
Fiber.class, void.class));
}
return pushFloatCache;
}
WasmFunction pushDouble() {
if (pushDoubleCache == null) {
pushDoubleCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush", double.class,
Fiber.class, void.class));
}
return pushDoubleCache;
}
WasmFunction pushPlatformObject() {
if (pushObjectCache == null) {
pushObjectCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush",
Fiber.PlatformObject.class, Fiber.class, void.class));
}
return pushObjectCache;
}
WasmFunction pushPlatformFunction() {
if (pushFunctionCache == null) {
pushFunctionCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush",
Fiber.PlatformFunction.class, Fiber.class, void.class));
}
return pushFunctionCache;
}
WasmFunction pushPlatformException() {
if (pushExceptionCache == null) {
pushExceptionCache = functions.forStaticMethod(new MethodReference(Fiber.class, "reversePush",
Fiber.PlatformException.class, Fiber.class, void.class));
}
return pushExceptionCache;
}
WasmFunction popInt() {
if (popIntCache == null) {
popIntCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popInt", int.class));
}
return popIntCache;
}
WasmFunction popLong() {
if (popLongCache == null) {
popLongCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popLong", long.class));
}
return popLongCache;
}
WasmFunction popFloat() {
if (popFloatCache == null) {
popFloatCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popFloat", float.class));
}
return popFloatCache;
}
WasmFunction popDouble() {
if (popDoubleCache == null) {
popDoubleCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popDouble", double.class));
}
return popDoubleCache;
}
WasmFunction popPlatformObject() {
if (popObjectCache == null) {
popObjectCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popPlatformObject",
Fiber.PlatformObject.class));
}
return popObjectCache;
}
WasmFunction popPlatformFunction() {
if (popFunctionCache == null) {
popFunctionCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popPlatformFunction",
Fiber.PlatformFunction.class));
}
return popFunctionCache;
}
WasmFunction popPlatformException() {
if (popExceptionCache == null) {
popExceptionCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "popPlatformException",
Fiber.PlatformException.class));
}
return popExceptionCache;
}
WasmFunction isResuming() {
if (isResumingCache == null) {
// Incari: the instance check, as in TeaVM 0.15 (see the header). Hot path.
isResumingCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "isResuming",
boolean.class));
}
return isResumingCache;
}
WasmFunction isSuspending() {
if (isSuspendingCache == null) {
// Incari: the instance check, as in TeaVM 0.15 (see the header). Hot path.
isSuspendingCache = functions.forInstanceMethod(new MethodReference(Fiber.class, "isSuspending",
boolean.class));
}
return isSuspendingCache;
}
WasmFunction currentFiber() {
if (currentFiberCache == null) {
currentFiberCache = functions.forStaticMethod(new MethodReference(Fiber.class, "current", Fiber.class));
}
return currentFiberCache;
}
void restoreValue(WasmType type, WasmInstructionList target, TextLocation location) {
if (type instanceof WasmType.Number) {
switch (((WasmType.Number) type).number) {
case INT32:
target.add(new WasmCall(popInt()), location);
break;
case INT64:
target.add(new WasmCall(popLong()), location);
break;
case FLOAT32:
target.add(new WasmCall(popFloat()), location);
break;
case FLOAT64:
target.add(new WasmCall(popDouble()), location);
break;
}
} else if (type instanceof WasmType.Reference) {
var refType = (WasmType.Reference) type;
if (type instanceof WasmType.SpecialReference) {
switch (((WasmType.SpecialReference) type).kind) {
case EXTERN:
target.add(new WasmCall(popPlatformObject()), location);
target.add(new WasmExternConversion(WasmExternConversionType.ANY_TO_EXTERN),
location);
return;
case FUNC:
target.add(new WasmCall(popPlatformFunction()), location);
break;
case EXN:
target.add(new WasmCall(popPlatformException()), location);
break;
default:
target.add(new WasmCall(popPlatformObject()), location);
break;
}
} else if (type instanceof WasmType.CompositeReference) {
var composite = ((WasmType.CompositeReference) type).composite;
if (composite instanceof WasmFunctionType) {
target.add(new WasmCall(popPlatformFunction()), location);
} else {
target.add(new WasmCall(popPlatformObject()), location);
}
}
target.add(new WasmCast(refType), location);
} else {
throw new IllegalArgumentException();
}
}
void saveValue(WasmType type, WasmInstructionList list, WasmLocal fiberLocal, TextLocation location) {
if (type instanceof WasmType.Number) {
list.add(new WasmGetLocal(fiberLocal), location);
switch (((WasmType.Number) type).number) {
case INT32:
list.add(new WasmCall(pushInt()), location);
break;
case INT64:
list.add(new WasmCall(pushLong()), location);
break;
case FLOAT32:
list.add(new WasmCall(pushFloat()), location);
break;
case FLOAT64:
list.add(new WasmCall(pushDouble()), location);
break;
}
} else {
if (type instanceof WasmType.SpecialReference) {
switch (((WasmType.SpecialReference) type).kind) {
case EXTERN:
list.add(new WasmExternConversion(WasmExternConversionType.EXTERN_TO_ANY),
location);
break;
case FUNC:
list.add(new WasmGetLocal(fiberLocal), location);
list.add(new WasmCall(pushPlatformFunction()), location);
return;
case EXN:
list.add(new WasmGetLocal(fiberLocal), location);
list.add(new WasmCall(pushPlatformException()), location);
return;
}
} else if (type instanceof WasmType.CompositeReference) {
var composite = ((WasmType.CompositeReference) type).composite;
if (composite instanceof WasmFunctionType) {
list.add(new WasmGetLocal(fiberLocal), location);
list.add(new WasmCall(pushPlatformFunction()), location);
return;
}
}
list.add(new WasmGetLocal(fiberLocal), location);
list.add(new WasmCall(pushPlatformObject()), location);
}
}
}
@@ -0,0 +1,640 @@
/*
* Copyright 2026 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the blocks this transformation creates
* declare their types with nullable references, as its save and restore blocks already did, since
* a value restored after a suspension is nullable even where the original was not. Non-nullable
* locals (other than parameters) become nullable, since the save and restore code reads them where
* WebAssembly doesn't count them as set.
*/
package org.teavm.backend.wasm.transformation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.teavm.backend.wasm.BaseWasmFunctionRepository;
import org.teavm.backend.wasm.WasmFunctionTypes;
import org.teavm.backend.wasm.generate.classes.WasmGCClassInfoProvider;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmLocal;
import org.teavm.backend.wasm.model.WasmType;
import org.teavm.backend.wasm.model.instruction.WasmBlock;
import org.teavm.backend.wasm.model.instruction.WasmBranch;
import org.teavm.backend.wasm.model.instruction.WasmBreak;
import org.teavm.backend.wasm.model.instruction.WasmCall;
import org.teavm.backend.wasm.model.instruction.WasmCallReference;
import org.teavm.backend.wasm.model.instruction.WasmCast;
import org.teavm.backend.wasm.model.instruction.WasmCastBranch;
import org.teavm.backend.wasm.model.instruction.WasmConditional;
import org.teavm.backend.wasm.model.instruction.WasmDefaultInstructionVisitor;
import org.teavm.backend.wasm.model.instruction.WasmDrop;
import org.teavm.backend.wasm.model.instruction.WasmFloat32Constant;
import org.teavm.backend.wasm.model.instruction.WasmFloat64Constant;
import org.teavm.backend.wasm.model.instruction.WasmGetLocal;
import org.teavm.backend.wasm.model.instruction.WasmInstruction;
import org.teavm.backend.wasm.model.instruction.WasmInstructionList;
import org.teavm.backend.wasm.model.instruction.WasmInstructionUtil;
import org.teavm.backend.wasm.model.instruction.WasmInt32Constant;
import org.teavm.backend.wasm.model.instruction.WasmInt64Constant;
import org.teavm.backend.wasm.model.instruction.WasmIntBinaryOperation;
import org.teavm.backend.wasm.model.instruction.WasmIntType;
import org.teavm.backend.wasm.model.instruction.WasmIntUnary;
import org.teavm.backend.wasm.model.instruction.WasmIntUnaryOperation;
import org.teavm.backend.wasm.model.instruction.WasmNullBranch;
import org.teavm.backend.wasm.model.instruction.WasmNullConstant;
import org.teavm.backend.wasm.model.instruction.WasmReturn;
import org.teavm.backend.wasm.model.instruction.WasmSetLocal;
import org.teavm.backend.wasm.model.instruction.WasmSwitch;
import org.teavm.backend.wasm.model.instruction.WasmTeeLocal;
import org.teavm.backend.wasm.model.instruction.WasmTry;
import org.teavm.backend.wasm.model.instruction.WasmTypeInference;
import org.teavm.backend.wasm.render.WasmSignature;
import org.teavm.model.TextLocation;
public class CoroutineTransformation {
private static final String FIBER = "org.teavm.runtime.Fiber";
private WasmFunctionTypes functionTypes;
private WasmGCClassInfoProvider classInfoProvider;
private CoroutineFunctions coroutineFunctions;
private WasmFunction currentFunction;
private WasmLocal savedFunctionLocal;
private WasmLocal fiberLocal;
private WasmLocal stateLocal;
private SuspensionPointCollector collector;
private int currentStateOffset;
private Set<WasmInstruction> usedBreakTargets = new HashSet<>();
public CoroutineTransformation(WasmFunctionTypes functionTypes, BaseWasmFunctionRepository functions,
WasmGCClassInfoProvider classInfoProvider) {
this.functionTypes = functionTypes;
this.classInfoProvider = classInfoProvider;
coroutineFunctions = new CoroutineFunctions(functions);
}
public void transform(WasmFunction function) {
currentFunction = function;
collector = new SuspensionPointCollector();
collector.visitMany(function.getBody());
var originalLocals = function.getLocalVariables().size();
// Incari: the epilogue saves every local after the blocks that set them, and the prologue
// restores them inside a conditional. WebAssembly only lets a non-nullable local be read
// where a set of it dominates within the same block, so such a local (the reflection
// caller's argsData) failed validation ("uninitialized local"). Make them nullable;
// parameters keep the types in the function's signature, and always count as set.
for (var i = function.getType().getParameterTypes().size(); i < originalLocals; ++i) {
var local = function.getLocalVariables().get(i);
if (local.getType() instanceof WasmType.Reference reference && !reference.isNullable()) {
local.setType(reference.asNullable());
}
}
fiberLocal = new WasmLocal(classInfoProvider.getClassInfo(FIBER).getType(), "coroutine$fiber");
stateLocal = new WasmLocal(WasmType.INT32, "coroutine$state");
function.add(fiberLocal);
function.add(stateLocal);
new BreakTargetCollector().visitMany(function.getBody());
var mainBlock = new WasmBlock(false);
mainBlock.getBody().transferFrom(function.getBody());
generatePrologue(originalLocals);
function.getBody().add(mainBlock);
splitList(mainBlock.getBody(), Collections.emptyList(), function.getType().getReturnTypes(),
mainBlock.getBody());
if (!mainBlock.getBody().getLast().isTerminating()) {
mainBlock.getBody().add(new WasmReturn());
}
generateEpilogue(originalLocals);
currentFunction = null;
savedFunctionLocal = null;
collector = null;
currentStateOffset = 0;
stateLocal = null;
fiberLocal = null;
usedBreakTargets.clear();
}
private void generatePrologue(int localsCount) {
var prologue = new WasmInstructionList();
var builder = prologue.builder();
builder
.call(coroutineFunctions.currentFiber())
.teeLocal(fiberLocal)
.call(coroutineFunctions.isResuming());
var restoreCond = builder.conditional(WasmType.INT32);
restoreCond.getThenBlock().builder()
.getLocal(fiberLocal)
.call(coroutineFunctions.popInt());
for (var i = localsCount - 1; i >= 0; i--) {
var local = currentFunction.getLocalVariables().get(i);
restoreCond.getThenBlock().add(new WasmGetLocal(fiberLocal));
coroutineFunctions.restoreValue(local.getType(), restoreCond.getThenBlock(), null);
restoreCond.getThenBlock().add(new WasmSetLocal(local));
}
restoreCond.getElseBlock().builder()
.i32Const(0);
builder.setLocal(stateLocal);
currentFunction.getBody().addFirst(prologue);
}
private void generateEpilogue(int localsCount) {
var list = new WasmInstructionList();
for (var i = 0; i < localsCount; i++) {
var local = currentFunction.getLocalVariables().get(i);
list.add(new WasmGetLocal(local));
coroutineFunctions.saveValue(local.getType(), list, fiberLocal, null);
}
list.add(new WasmGetLocal(stateLocal));
list.add(new WasmGetLocal(fiberLocal));
list.add(new WasmCall(coroutineFunctions.pushInt()));
var returnType = currentFunction.getType().getSingleReturnType();
if (returnType != null) {
if (returnType instanceof WasmType.Number) {
switch (((WasmType.Number) returnType).number) {
case INT32:
list.add(new WasmInt32Constant(0));
break;
case INT64:
list.add(new WasmInt64Constant(0));
break;
case FLOAT32:
list.add(new WasmFloat32Constant(0));
break;
case FLOAT64:
list.add(new WasmFloat64Constant(0));
break;
}
} else {
list.add(new WasmNullConstant((WasmType.Reference) returnType));
}
}
currentFunction.getBody().transferFrom(list);
}
private void splitList(WasmInstructionList list, List<? extends WasmType> inputTypes,
List<? extends WasmType> outputTypes, WasmInstructionList suspendLabel) {
var splitter = new ListSplitter(inputTypes, outputTypes, suspendLabel);
var first = list.getFirst();
splitter.addPrologue(list);
splitter.process(first);
}
private class ListSplitter {
private List<? extends WasmType> inputTypes;
private List<? extends WasmType> outputTypes;
private WasmInstructionList suspendLabel;
private WasmTypeInference typeInference;
private int minDepth;
private List<WasmType> stackSnapshot = new ArrayList<>();
private WasmSwitch switchInsn;
ListSplitter(List<? extends WasmType> inputTypes, List<? extends WasmType> outputTypes,
WasmInstructionList suspendLabel) {
this.inputTypes = inputTypes;
this.outputTypes = outputTypes;
this.suspendLabel = suspendLabel;
typeInference = new WasmTypeInference(true);
typeInference.typeStack.addAll(inputTypes);
minDepth = inputTypes.size();
}
void process(WasmInstruction insn) {
while (insn != null) {
var next = insn.getNext();
if (collector.isSuspending(insn)) {
if (insn instanceof WasmBlock block && !block.isLoop() && block.getType() == null) {
processOptimizedBlock(block);
insn = next;
continue;
} else if (insn instanceof WasmConditional conditional && isOptimizableConditional(conditional)) {
processOptimizedConditional(conditional);
insn = next;
continue;
}
var block = new WasmBlock(false);
var jumpToInsn = block;
if (!inputTypes.isEmpty()) {
var signature = new WasmSignature(Collections.emptyList(), mapToNullableTypes(inputTypes));
block.setType(functionTypes.get(signature).asBlock());
}
moveAllPreviousTo(insn, block.getBody());
var stateIndex = ++currentStateOffset;
block.getBody().add(new WasmInt32Constant(stateIndex), insn.getLocation());
block.getBody().add(new WasmSetLocal(stateLocal), insn.getLocation());
minDepth = Math.min(minDepth, typeInference.typeStack.size());
stackSnapshot.clear();
stackSnapshot.addAll(typeInference.typeStack);
WasmType functionType = null;
if (insn instanceof WasmCallReference) {
functionType = ((WasmCallReference) insn).getType().getReference();
}
updateTypes(insn);
if (minDepth != inputTypes.size() || inputTypes.size() != stackSnapshot.size()) {
block = createRestoreInstructions(block, insn.getLocation(), functionType != null);
}
insn.insertPrevious(block);
insn.insertNext(createSaveInstructions(functionType, insn.getLocation()));
switchInsn.getTargets().add(jumpToInsn.getBody());
handleSplitInstruction(insn, stateIndex);
for (var i = stateIndex; i < currentStateOffset; ++i) {
switchInsn.getTargets().add(jumpToInsn.getBody());
}
} else {
updateTypes(insn);
}
insn = next;
}
}
private void processOptimizedBlock(WasmBlock block) {
var start = block.getBody().getFirst();
moveAllPreviousTo(block, block.getBody());
process(start);
if (!typeInference.typeStack.isEmpty() || inputTypes.isEmpty()) {
block.setType(functionTypes.get(new WasmSignature(mapToNullableTypes(typeInference.typeStack),
mapToNullableTypes(inputTypes))).asBlock());
}
}
private boolean isOptimizableConditional(WasmConditional conditional) {
return conditional.getType() == null
|| (conditional.getType().getInputTypes().isEmpty() && !usedBreakTargets.contains(conditional));
}
private void processOptimizedConditional(WasmConditional conditional) {
var outputTypes = new ArrayList<>(typeInference.typeStack);
outputTypes.remove(outputTypes.size() - 1);
var typesAfterConditionCheck = List.copyOf(outputTypes);
if (conditional.getType() != null) {
outputTypes.addAll(conditional.getType().getOutputTypes());
}
var wrapper = new WasmBlock(false);
if (!outputTypes.isEmpty() || inputTypes.isEmpty()) {
wrapper.setType(functionTypes.get(new WasmSignature(mapToNullableTypes(outputTypes),
mapToNullableTypes(inputTypes)))
.asBlock());
}
typeInference.typeStack.remove(typeInference.typeStack.size() - 1);
minDepth = Math.min(minDepth, typeInference.typeStack.size());
if (conditional.getElseBlock().isEmpty()) {
moveAllPreviousTo(conditional, wrapper.getBody());
WasmInstructionUtil.negate(wrapper.getBody().getLast());
var branch = new WasmBranch(wrapper.getBody());
wrapper.getBody().add(branch);
wrapper.getBody().transferFrom(conditional.getThenBlock());
process(branch.getNext());
var replacement = new BreakTargetReplacement(target -> {
if (target == conditional.getThenBlock()) {
return wrapper.getBody();
} else {
return null;
}
});
replacement.visit(wrapper);
} else {
var thenWrapper = new WasmBlock(false);
if (!inputTypes.isEmpty() || !typesAfterConditionCheck.isEmpty()) {
thenWrapper.setType(functionTypes.get(new WasmSignature(
mapToNullableTypes(typesAfterConditionCheck), mapToNullableTypes(inputTypes))).asBlock());
}
moveAllPreviousTo(conditional, thenWrapper.getBody());
WasmInstructionUtil.negate(thenWrapper.getBody().getLast());
var branch = new WasmBranch(thenWrapper.getBody());
thenWrapper.getBody().add(branch);
thenWrapper.getBody().transferFrom(conditional.getThenBlock());
var backupTypes = List.copyOf(typeInference.typeStack);
var backupMinDepth = minDepth;
process(branch.getNext());
if (!thenWrapper.getBody().getLast().isTerminating()) {
thenWrapper.getBody().add(new WasmBreak(wrapper.getBody()));
}
wrapper.getBody().add(thenWrapper);
wrapper.getBody().transferFrom(conditional.getElseBlock());
typeInference.typeStack.clear();
typeInference.typeStack.addAll(backupTypes);
minDepth = backupMinDepth;
process(thenWrapper.getNext());
var replacement = new BreakTargetReplacement(target -> {
if (target == conditional.getThenBlock()) {
return thenWrapper.getBody();
} else if (target == conditional.getElseBlock()) {
return wrapper.getBody();
} else {
return null;
}
});
replacement.visit(wrapper);
}
typeInference.typeStack.clear();
typeInference.typeStack.addAll(outputTypes);
conditional.insertPrevious(wrapper);
conditional.delete();
}
private void updateTypes(WasmInstruction insn) {
insn.acceptVisitor(typeInference);
minDepth = Math.min(minDepth, typeInference.getDepthBeforeLastInstructionOut());
}
void addPrologue(WasmInstructionList target) {
var jumpToFirstLabel = new WasmBlock(false);
var jumpToUnreachable = new WasmBlock(false);
jumpToFirstLabel.getBody().builder()
.add(jumpToUnreachable)
.unreachable();
var jumpToUnreachableBuilder = jumpToUnreachable.getBody().builder();
jumpToUnreachableBuilder.getLocal(stateLocal);
if (currentStateOffset > 0) {
jumpToUnreachableBuilder
.i32Const(currentStateOffset)
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.SUB);
}
switchInsn = new WasmSwitch(jumpToUnreachable.getBody());
switchInsn.getTargets().add(jumpToFirstLabel.getBody());
jumpToUnreachableBuilder.add(switchInsn);
target.addFirst(jumpToFirstLabel);
}
private WasmBlock createRestoreInstructions(WasmBlock block, TextLocation location,
boolean isCallRef) {
var depthWithoutArgs = typeInference.getDepthBeforeLastInstructionOut();
var restoreBlock = new WasmBlock(false);
var signature = new WasmSignature(mapToNullableTypes(stackSnapshot), mapToNullableTypes(inputTypes));
restoreBlock.setType(functionTypes.get(signature).asBlock());
restoreBlock.setLocation(location);
restoreBlock.getBody().add(block);
block.getBody().add(new WasmBreak(restoreBlock.getBody()), location);
var typesToPush = stackSnapshot.subList(0, depthWithoutArgs);
for (var type : typesToPush) {
restoreBlock.getBody().add(new WasmGetLocal(fiberLocal), location);
coroutineFunctions.restoreValue(type, restoreBlock.getBody(), location);
}
var dummyArgs = stackSnapshot.size();
if (isCallRef) {
--dummyArgs;
}
for (var i = depthWithoutArgs; i < dummyArgs; ++i) {
var type = stackSnapshot.get(i);
pushDefault(restoreBlock.getBody(), type, location);
}
if (isCallRef) {
var type = stackSnapshot.get(dummyArgs);
restoreBlock.getBody().add(new WasmGetLocal(fiberLocal), location);
coroutineFunctions.restoreValue(type, restoreBlock.getBody(), location);
}
return restoreBlock;
}
private WasmInstructionList createSaveInstructions(WasmType callRefType, TextLocation location) {
var depthWithoutArgs = typeInference.getDepthBeforeLastInstructionOut();
var result = new WasmInstructionList();
emitIsSuspending(result, location);
var check = new WasmConditional();
result.add(check, location);
if (callRefType != null) {
check.getThenBlock().add(new WasmGetLocal(savedFunctionLocal()));
coroutineFunctions.saveValue(callRefType, check.getThenBlock(), fiberLocal, location);
}
var condTypes = mapToNullableTypes(typeInference.typeStack.subList(minDepth,
typeInference.typeStack.size()));
if (!condTypes.isEmpty()) {
check.setType(functionTypes.get(new WasmSignature(condTypes, condTypes)).asBlock());
}
for (var i = typeInference.typeStack.size() - 1; i >= depthWithoutArgs; --i) {
check.getThenBlock().add(new WasmDrop(), location);
}
for (var i = depthWithoutArgs - 1; i >= minDepth; --i) {
var type = stackSnapshot.get(i);
coroutineFunctions.saveValue(type, check.getThenBlock(), fiberLocal, location);
}
for (var i = 0; i < outputTypes.size(); ++i) {
pushDefault(check.getThenBlock(), outputTypes.get(i), location);
}
check.getThenBlock().add(new WasmBreak(suspendLabel), location);
return result;
}
}
private List<WasmType> mapToNullableTypes(List<? extends WasmType> types) {
var result = new ArrayList<WasmType>();
for (var type : types) {
if (type instanceof WasmType.Reference) {
type = ((WasmType.Reference) type).asNullable();
}
result.add(type);
}
return result;
}
private void moveAllPreviousTo(WasmInstruction instruction, WasmInstructionList list) {
instruction = instruction.getPrevious();
while (instruction != null) {
var previous = instruction.getPrevious();
instruction.delete();
list.addFirst(instruction);
instruction = previous;
}
}
private void handleSplitInstruction(WasmInstruction instruction, int stateIndex) {
if (instruction instanceof WasmCallReference callRef) {
instruction.insertPrevious(new WasmTeeLocal(savedFunctionLocal()));
instruction.insertPrevious(new WasmCast(callRef.getType().getReference()));
} else if (instruction instanceof WasmBlock block) {
if (block.isLoop()) {
splitLoop(block, stateIndex);
} else {
List<? extends WasmType> inputTypes = block.getType() != null
? block.getType().getInputTypes()
: Collections.emptyList();
List<? extends WasmType> outputTypes = block.getType() != null
? block.getType().getOutputTypes()
: Collections.emptyList();
splitList(block.getBody(), inputTypes, outputTypes, block.getBody());
}
} else if (instruction instanceof WasmConditional conditional) {
splitConditional(conditional);
} else if (instruction instanceof WasmTry tryInsn) {
List<? extends WasmType> outTypes = tryInsn.getType() != null
? List.of(tryInsn.getType())
: Collections.emptyList();
splitList(tryInsn.getBody(), Collections.emptyList(), outTypes, tryInsn.getBody());
}
}
private void splitLoop(WasmBlock block, int stateIndex) {
var breakLabel = new WasmBlock(false);
var newLoop = new WasmBlock(true);
breakLabel.getBody().add(newLoop);
block.insertPrevious(breakLabel);
block.delete();
block.setLoop(false);
newLoop.getBody().add(block);
newLoop.getBody().add(new WasmInt32Constant(stateIndex));
newLoop.getBody().add(new WasmSetLocal(stateLocal));
newLoop.getBody().add(new WasmBreak(newLoop.getBody()));
splitList(newLoop.getBody(), Collections.emptyList(), Collections.emptyList(), breakLabel.getBody());
}
private void splitConditional(WasmConditional conditional) {
var inputTypes = new ArrayList<WasmType>();
var outputTypes = new ArrayList<WasmType>();
if (conditional.getType() != null) {
inputTypes.addAll(conditional.getType().getInputTypes());
outputTypes.addAll(conditional.getType().getOutputTypes());
}
inputTypes.add(WasmType.INT32);
var wrapper = new WasmBlock(false);
wrapper.setType(functionTypes.get(new WasmSignature(mapToNullableTypes(outputTypes),
mapToNullableTypes(inputTypes))).asBlock());
conditional.insertPrevious(wrapper);
if (conditional.getElseBlock().isEmpty()) {
wrapper.getBody().add(new WasmIntUnary(WasmIntType.INT32, WasmIntUnaryOperation.EQZ));
wrapper.getBody().add(new WasmBranch(conditional.getThenBlock()));
wrapper.getBody().transferFrom(conditional.getThenBlock());
splitList(wrapper.getBody(), inputTypes, outputTypes, wrapper.getBody());
var replacement = new BreakTargetReplacement(target -> {
if (target == conditional.getThenBlock()) {
return wrapper.getBody();
} else {
return null;
}
});
replacement.visit(wrapper);
} else {
var thenWrapper = new WasmBlock(false);
thenWrapper.setType(functionTypes.get(new WasmSignature(Collections.emptyList(),
mapToNullableTypes(inputTypes))).asBlock());
thenWrapper.getBody().add(new WasmIntUnary(WasmIntType.INT32, WasmIntUnaryOperation.EQZ));
thenWrapper.getBody().add(new WasmBranch(conditional.getThenBlock()));
thenWrapper.getBody().transferFrom(conditional.getThenBlock());
var splitter = new ListSplitter(inputTypes, outputTypes, wrapper.getBody());
var first = thenWrapper.getBody().getFirst();
splitter.addPrologue(thenWrapper.getBody());
splitter.process(first);
if (!thenWrapper.getBody().getLast().isTerminating()) {
thenWrapper.getBody().add(new WasmBreak(wrapper.getBody()));
}
wrapper.getBody().add(thenWrapper);
wrapper.getBody().transferFrom(conditional.getElseBlock());
splitter.typeInference.typeStack.clear();
if (conditional.getType() != null) {
splitter.typeInference.typeStack.addAll(conditional.getType().getInputTypes());
}
splitter.process(wrapper.getBody().getFirst().getNext());
var replacement = new BreakTargetReplacement(target -> {
if (target == conditional.getThenBlock()) {
return thenWrapper.getBody();
} else if (target == conditional.getElseBlock()) {
return wrapper.getBody();
} else {
return null;
}
});
replacement.visit(wrapper);
}
conditional.delete();
}
private WasmLocal savedFunctionLocal() {
if (savedFunctionLocal == null) {
savedFunctionLocal = new WasmLocal(WasmType.FUNC, "coroutine$savedFunction");
currentFunction.add(savedFunctionLocal);
}
return savedFunctionLocal;
}
private void pushDefault(WasmInstructionList list, WasmType type, TextLocation location) {
if (type instanceof WasmType.Number) {
switch (((WasmType.Number) type).number) {
case INT32:
list.add(new WasmInt32Constant(0), location);
break;
case INT64:
list.add(new WasmInt64Constant(0L), location);
break;
case FLOAT32:
list.add(new WasmFloat32Constant(0), location);
break;
case FLOAT64:
list.add(new WasmFloat64Constant(0), location);
break;
}
} else {
var ref = (WasmType.Reference) type;
list.add(new WasmNullConstant(ref), location);
}
}
private void emitIsSuspending(WasmInstructionList list, TextLocation location) {
list.add(new WasmGetLocal(fiberLocal), location);
list.add(new WasmCall(coroutineFunctions.isSuspending()), location);
}
private class BreakTargetCollector extends WasmDefaultInstructionVisitor {
@Override
public void visit(WasmBreak instruction) {
usedBreakTargets.add(instruction.getTarget().getBreakTarget());
super.visit(instruction);
}
@Override
public void visit(WasmBranch instruction) {
usedBreakTargets.add(instruction.getTarget().getBreakTarget());
super.visit(instruction);
}
@Override
public void visit(WasmCastBranch instruction) {
usedBreakTargets.add(instruction.getTarget().getBreakTarget());
super.visit(instruction);
}
@Override
public void visit(WasmNullBranch instruction) {
usedBreakTargets.add(instruction.getTarget().getBreakTarget());
super.visit(instruction);
}
@Override
public void visit(WasmSwitch instruction) {
usedBreakTargets.add(instruction.getDefaultTarget().getBreakTarget());
for (var target : instruction.getTargets()) {
usedBreakTargets.add(target.getBreakTarget());
}
super.visit(instruction);
}
}
}
@@ -0,0 +1,146 @@
/*
* Copyright 2018 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.
*
* Modified for Incari (tools/teavm-patches/README.md): String arguments and constant text are
* appended with append(String), not append(Object), so concatenating strings never makes a
* virtual toString call.
*/
package org.teavm.classlib.impl;
import org.teavm.dependency.BootstrapMethodSubstitutor;
import org.teavm.dependency.DynamicCallSite;
import org.teavm.model.MethodReference;
import org.teavm.model.ReferenceCache;
import org.teavm.model.RuntimeConstant;
import org.teavm.model.ValueType;
import org.teavm.model.emit.ProgramEmitter;
import org.teavm.model.emit.ValueEmitter;
import org.teavm.model.instructions.IntegerSubtype;
public class StringConcatFactorySubstitutor implements BootstrapMethodSubstitutor {
private ReferenceCache referenceCache = new ReferenceCache();
private static final String STRING_BUILDER = "java.lang.StringBuilder";
private static final char VALUE_ARGUMENT = '\1';
private static final char CONST_ARGUMENT = '\2';
@Override
public ValueEmitter substitute(DynamicCallSite callSite, ProgramEmitter pe) {
ValueEmitter sb = pe.construct(STRING_BUILDER);
if (callSite.getBootstrapMethod().getName().equals("makeConcatWithConstants")) {
appendArgumentWithRecipe(sb, callSite);
} else {
appendSimpleArguments(sb, callSite);
}
return sb.invokeSpecial("toString", ValueType.object("java.lang.String"));
}
private ValueEmitter appendSimpleArguments(ValueEmitter sb, DynamicCallSite callSite) {
int parameterCount = callSite.getCalledMethod().parameterCount();
for (int i = 0; i < parameterCount; ++i) {
sb = appendArgument(sb, callSite.getCalledMethod().parameterType(i), callSite.getArguments().get(i));
}
return sb;
}
private ValueEmitter appendArgumentWithRecipe(ValueEmitter sb, DynamicCallSite callSite) {
String recipe = callSite.getBootstrapArguments().get(0).getString();
int charCount = recipe.length();
int constantIndex = 0;
int valueIndex = 0;
int paramIndex = 0;
StringBuilder acc = new StringBuilder();
for (int i = 0; i < charCount; ++i) {
char c = recipe.charAt(i);
switch (c) {
case VALUE_ARGUMENT: {
sb = flushAcc(sb, acc);
ValueType type = callSite.getCalledMethod().parameterType(paramIndex++);
sb = appendArgument(sb, type, callSite.getArguments().get(valueIndex++));
break;
}
case CONST_ARGUMENT: {
sb = flushAcc(sb, acc);
ValueType type = callSite.getCalledMethod().parameterType(paramIndex++);
RuntimeConstant poolConstant = callSite.getBootstrapArguments().get(1 + constantIndex++);
sb = appendArgument(sb, type, constant(sb.getProgramEmitter(), poolConstant));
break;
}
default:
acc.append(c);
break;
}
}
sb = flushAcc(sb, acc);
return sb;
}
private ValueEmitter flushAcc(ValueEmitter sb, StringBuilder acc) {
if (acc.length() == 0) {
return sb;
} else if (acc.length() == 1) {
sb = appendArgument(sb, ValueType.CHARACTER, sb.getProgramEmitter().constant(acc.charAt(0))
.cast(ValueType.CHARACTER));
} else {
sb = appendArgument(sb, ValueType.object("java.lang.String"),
sb.getProgramEmitter().constant(acc.toString()));
}
acc.setLength(0);
return sb;
}
private ValueEmitter appendArgument(ValueEmitter sb, ValueType type, ValueEmitter argument) {
if (type instanceof ValueType.Primitive) {
switch (((ValueType.Primitive) type).getKind()) {
case BYTE:
argument = argument.castToInteger(IntegerSubtype.BYTE);
type = ValueType.INTEGER;
break;
case SHORT:
argument = argument.castToInteger(IntegerSubtype.SHORT);
type = ValueType.INTEGER;
break;
default:
break;
}
} else if (!type.isObject("java.lang.String")) {
type = ValueType.object("java.lang.Object");
}
MethodReference method = referenceCache.getCached(new MethodReference(STRING_BUILDER, "append", type,
ValueType.object(STRING_BUILDER)));
return sb.invokeSpecial(method, argument);
}
private ValueEmitter constant(ProgramEmitter pe, RuntimeConstant value) {
switch (value.getKind()) {
case RuntimeConstant.STRING:
return pe.constant(value.getString());
case RuntimeConstant.TYPE:
return pe.constant(value.getValueType());
case RuntimeConstant.INT:
return pe.constant(value.getInt());
case RuntimeConstant.LONG:
return pe.constant(value.getLong());
case RuntimeConstant.FLOAT:
return pe.constant(value.getFloat());
case RuntimeConstant.DOUBLE:
return pe.constant(value.getDouble());
default:
throw new IllegalArgumentException("Unsupported constant type: " + value.getKind());
}
}
}
@@ -0,0 +1,598 @@
/*
* Copyright 2013 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.
*
* Modified for Incari (tools/teavm-patches/README.md): an interrupted wait() now takes the
* monitor back before it throws InterruptedException, as Object.wait specifies, and no longer
* counts as a waiter a later notify() could wake. It threw without the monitor, so the caller's
* synchronized block ended in IllegalMonitorStateException.
*/
package org.teavm.classlib.java.lang;
import java.util.ArrayDeque;
import java.util.Queue;
import org.teavm.backend.wasm.runtime.WasmGCSupport;
import org.teavm.classlib.PlatformDetector;
import org.teavm.dependency.PluggableDependency;
import org.teavm.interop.Address;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.interop.DelegateTo;
import org.teavm.interop.NoSideEffects;
import org.teavm.interop.Rename;
import org.teavm.interop.Structure;
import org.teavm.interop.Superclass;
import org.teavm.interop.Unmanaged;
import org.teavm.jso.browser.TimerHandler;
import org.teavm.platform.Platform;
import org.teavm.platform.PlatformObject;
import org.teavm.platform.PlatformRunnable;
import org.teavm.runtime.Allocator;
import org.teavm.runtime.EventQueue;
import org.teavm.runtime.RuntimeArray;
import org.teavm.runtime.RuntimeClass;
import org.teavm.runtime.RuntimeObject;
import org.teavm.runtime.reflect.ClassInfo;
@Superclass("")
public class TObject {
Monitor monitor;
static class Monitor {
static final int MASK = 0x80000000;
Queue<PlatformRunnable> enteringThreads;
Queue<NotifyListener> notifyListeners;
TThread owner;
int count;
int id;
Monitor() {
this.owner = TThread.currentThread();
}
}
interface NotifyListener extends PlatformRunnable, EventQueue.Event {
boolean expired();
}
static void monitorEnterSync(TObject o) {
if (Thread.currentThread() == null) {
return;
}
if (o.monitor == null) {
createMonitor(o);
}
if (o.monitor.owner == null) {
o.monitor.owner = TThread.currentThread();
} else if (o.monitor.owner != TThread.currentThread()) {
throw new IllegalStateException("Can't enter monitor from another thread synchronously");
}
o.monitor.count++;
}
static void monitorExitSync(TObject o) {
if (Thread.currentThread() == null) {
return;
}
if (o.isEmptyMonitor() || o.monitor.owner != TThread.currentThread()) {
throw new TIllegalMonitorStateException();
}
if (--o.monitor.count == 0) {
o.monitor.owner = null;
}
o.isEmptyMonitor();
}
static void monitorEnter(TObject o) {
monitorEnter(o, 1);
}
static void monitorEnter(TObject o, int count) {
if (o.monitor == null) {
createMonitor(o);
}
if (o.monitor.owner == null) {
o.monitor.owner = TThread.currentThread();
}
if (o.monitor.owner != TThread.currentThread()) {
monitorEnterWait(o, count);
} else {
o.monitor.count += count;
}
}
private static void createMonitor(TObject o) {
if (PlatformDetector.isWebAssemblyGC()) {
int hashCode = o.wasmGCIdentity();
o.monitor = new Monitor();
o.monitor.id = hashCode;
} else if (PlatformDetector.isLowLevel()) {
int hashCode = hashCodeLowLevel(o);
o.monitor = new Monitor();
o.monitor.id = hashCode;
} else {
o.monitor = new Monitor();
}
}
@Async
static native void monitorEnterWait(TObject o, int count);
static void monitorEnterWait(TObject o, int count, AsyncCallback<Void> callback) {
TThread thread = TThread.currentThread();
if (o.monitor == null) {
createMonitor(o);
TThread.setCurrentThread(thread);
o.monitor.count += count;
callback.complete(null);
return;
} else if (o.monitor.owner == null) {
o.monitor.owner = thread;
TThread.setCurrentThread(thread);
o.monitor.count += count;
callback.complete(null);
return;
}
Monitor monitor = o.monitor;
if (monitor.enteringThreads == null) {
monitor.enteringThreads = new ArrayDeque<>();
}
monitor.enteringThreads.add(() -> {
TThread.setCurrentThread(thread);
o.monitor.owner = thread;
o.monitor.count += count;
callback.complete(null);
});
}
static void monitorExit(TObject o) {
monitorExit(o, 1);
}
static void monitorExit(TObject o, int count) {
if (o.isEmptyMonitor() || o.monitor.owner != TThread.currentThread()) {
throw new TIllegalMonitorStateException();
}
Monitor monitor = o.monitor;
monitor.count -= count;
if (monitor.count > 0) {
return;
}
monitor.owner = null;
if (monitor.enteringThreads != null && !monitor.enteringThreads.isEmpty()) {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.offer(() -> waitForOtherThreads(o));
} else {
Platform.postpone(() -> waitForOtherThreads(o));
}
} else {
o.isEmptyMonitor();
}
}
private static void waitForOtherThreads(TObject o) {
if (o.isEmptyMonitor() || o.monitor.owner != null) {
return;
}
Monitor monitor = o.monitor;
if (monitor.enteringThreads != null && !monitor.enteringThreads.isEmpty()) {
var enteringThreads = monitor.enteringThreads;
PlatformRunnable r = enteringThreads.remove();
monitor.enteringThreads = null;
r.run();
}
}
final boolean isEmptyMonitor() {
Monitor monitor = this.monitor;
if (monitor == null) {
return true;
}
if (monitor.owner == null
&& (monitor.enteringThreads == null || monitor.enteringThreads.isEmpty())
&& (monitor.notifyListeners == null || monitor.notifyListeners.isEmpty())) {
deleteMonitor();
return true;
} else {
return false;
}
}
private void deleteMonitor() {
if (PlatformDetector.isLowLevel()) {
int id = monitor.id;
setHashCodeLowLevel(this, id);
} else if (PlatformDetector.isWebAssemblyGC()) {
setWasmGCIdentity(monitor.id);
} else {
monitor = null;
}
}
static boolean holdsLock(TObject o) {
return o.monitor != null && o.monitor.owner == TThread.currentThread();
}
@Rename("fakeInit")
public TObject() {
}
@Rename("<init>")
private void init() {
}
@Rename("getClass")
public final TClass<?> getClass0() {
return (TClass<?>) (Object) getObjectClassInfo(this).classObject();
}
public static native ClassInfo getObjectClassInfo(Object obj);
@Override
public int hashCode() {
return identity();
}
@Override
public boolean equals(Object obj) {
return equals0((TObject) obj);
}
@Rename("equals")
public boolean equals0(TObject other) {
return this == other;
}
@Override
public String toString() {
return getClass().getName() + "@" + TInteger.toHexString(identity());
}
private String obfuscatedToString() {
return "<java_object>@" + Integer.toHexString(identity());
}
final int identity() {
if (PlatformDetector.isWebAssemblyGC()) {
var identity = wasmGCIdentity();
if (identity < 0) {
var monitor = this.monitor;
if (monitor != null) {
if (monitor.id < 0) {
monitor.id = WasmGCSupport.nextObjectId() & 0x7fffffff;
}
return monitor.id;
} else {
identity = WasmGCSupport.nextObjectId() & 0x7fffffff;
setWasmGCIdentity(identity);
}
}
return identity;
} else if (PlatformDetector.isLowLevel()) {
Monitor monitor = this.monitor;
if (monitor == null) {
int hashCode = hashCodeLowLevel(this);
if (hashCode == 0) {
hashCode = identityLowLevel();
setHashCodeLowLevel(this, hashCode);
}
return hashCode;
} else {
int hashCode = monitor.id;
if (hashCode == 0) {
hashCode = identityLowLevel();
monitor.id = hashCode;
}
return hashCode;
}
}
PlatformObject platformThis = Platform.getPlatformObject(this);
if (platformThis.getId() == 0) {
platformThis.setId(Platform.nextObjectId());
}
return Platform.getPlatformObject(this).getId();
}
private native int wasmGCIdentity();
private native void setWasmGCIdentity(int identity);
@DelegateTo("hashCodeLowLevelImpl")
@NoSideEffects
@Unmanaged
private static native int hashCodeLowLevel(TObject obj);
@Unmanaged
private static int hashCodeLowLevelImpl(RuntimeObject obj) {
return obj.hashCode;
}
@DelegateTo("setHashCodeLowLevelImpl")
@NoSideEffects
@Unmanaged
private static native void setHashCodeLowLevel(TObject obj, int value);
@Unmanaged
private static void setHashCodeLowLevelImpl(RuntimeObject obj, int value) {
obj.hashCode = value;
}
@Unmanaged
private static int identityLowLevel() {
int result = RuntimeObject.nextId++;
if (result == 0) {
result = RuntimeObject.nextId++;
if (result == Monitor.MASK) {
result = 1;
}
}
return result;
}
@DelegateTo("identityOrMonitorLowLevel")
@NoSideEffects
private native int identityOrMonitor();
private static int identityOrMonitorLowLevel(RuntimeObject object) {
return object.hashCode;
}
@DelegateTo("setIdentityLowLevel")
@NoSideEffects
native void setIdentity(int id);
private static void setIdentityLowLevel(RuntimeObject object, int id) {
object.hashCode = id;
}
@Override
@DelegateTo("cloneLowLevel")
@PluggableDependency(ObjectDependencyPlugin.class)
protected Object clone() throws TCloneNotSupportedException {
if (PlatformDetector.isWebAssemblyGC()) {
return cloneObject();
}
var cls = ((TClass<?>) (Object) getClass()).getClassInfo();
if (!(this instanceof TCloneable) && cls.itemType() == null) {
throw new TCloneNotSupportedException();
}
Object result = Platform.clone(this);
Platform.getPlatformObject(result).setId(Platform.nextObjectId());
return result;
}
private native TObject cloneObject();
@SuppressWarnings("unused")
private static RuntimeObject cloneLowLevel(RuntimeObject self) {
RuntimeClass cls = RuntimeClass.getClass(self);
int skip = Structure.sizeOf(RuntimeObject.class);
int size;
RuntimeObject copy;
if (cls.itemType == null) {
copy = Allocator.allocate(cls).toStructure();
size = cls.size;
} else {
RuntimeArray array = (RuntimeArray) self;
copy = Allocator.allocateArray(cls, array.size).toStructure();
int itemSize = RuntimeClass.isPrimitive(cls) ? cls.itemType.size : Address.sizeOf();
Address headerSize = Address.align(Address.fromInt(Structure.sizeOf(RuntimeArray.class)), itemSize);
size = itemSize * array.size + headerSize.toInt();
}
if (size > skip) {
Address.moveMemoryBlock(self.toAddress().add(skip), copy.toAddress().add(skip), size - skip);
}
return copy;
}
@Rename("notify")
public final void notify0() {
if (!holdsLock(this)) {
throw new TIllegalMonitorStateException();
}
var listeners = monitor.notifyListeners;
if (listeners == null) {
return;
}
while (!listeners.isEmpty()) {
NotifyListener listener = listeners.remove();
if (!listener.expired()) {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.offer(listener);
} else {
Platform.postpone(listener);
}
break;
}
}
if (listeners.isEmpty()) {
monitor.notifyListeners = null;
}
}
@Rename("notifyAll")
public final void notifyAll0() {
if (!holdsLock(this)) {
throw new TIllegalMonitorStateException();
}
var listeners = monitor.notifyListeners;
if (listeners == null) {
return;
}
while (!listeners.isEmpty()) {
NotifyListener listener = listeners.remove();
if (!listener.expired()) {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.offer(listener);
} else {
Platform.postpone(listener);
}
}
}
monitor.notifyListeners = null;
}
@Rename("wait")
public final void wait0(long timeout) throws TInterruptedException {
try {
wait(timeout, 0);
} catch (InterruptedException ex) {
throw new TInterruptedException();
}
}
@Rename("wait")
private void wait0(long timeout, int nanos) throws TInterruptedException {
if (!holdsLock(this)) {
throw new TIllegalMonitorStateException();
}
waitImpl(timeout, nanos);
}
@Async
private native void waitImpl(long timeout, int nanos) throws TInterruptedException;
final void waitImpl(long timeout, int nanos, AsyncCallback<Void> callback) {
Monitor monitor = this.monitor;
var listener = new NotifyListenerImpl(this, callback, monitor.count);
if (monitor.notifyListeners == null) {
monitor.notifyListeners = new ArrayDeque<>();
}
monitor.notifyListeners.add(listener);
TThread.currentThread().interruptHandler = listener;
if (timeout > 0 || nanos > 0) {
int timeoutToSchedule = timeout >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) timeout;
listener.timerId = PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()
? EventQueue.offer(listener, timeoutToSchedule + System.currentTimeMillis())
: Platform.schedule(listener, timeoutToSchedule);
}
monitorExit(this, monitor.count);
}
static class NotifyListenerImpl implements NotifyListener, TimerHandler, PlatformRunnable,
TThreadInterruptHandler {
final TObject obj;
final AsyncCallback<Void> callback;
final TThread currentThread = TThread.currentThread();
int timerId = -1;
boolean expired;
boolean performed;
int lockCount;
NotifyListenerImpl(TObject obj, AsyncCallback<Void> callback, int lockCount) {
this.obj = obj;
this.callback = callback;
this.lockCount = lockCount;
}
@Override
public boolean expired() {
boolean result = expired;
expired = true;
return result;
}
@Override
public void onTimer() {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.offer(() -> {
if (!expired()) {
run();
}
});
} else {
Platform.postpone(() -> {
if (!expired()) {
run();
}
});
}
}
@Override
public void run() {
if (performed) {
return;
}
performed = true;
if (timerId >= 0) {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.kill(timerId);
} else {
Platform.killSchedule(timerId);
}
timerId = -1;
}
TThread.setCurrentThread(currentThread);
monitorEnterWait(obj, lockCount, callback);
}
@Override
public void interrupted() {
if (performed) {
return;
}
performed = true;
// Incari: no longer waiting, so notify() passes over it to a thread that is.
expired = true;
if (timerId >= 0) {
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.kill(timerId);
} else {
Platform.killSchedule(timerId);
}
timerId = -1;
}
if (PlatformDetector.isLowLevel() || PlatformDetector.isWebAssemblyGC()) {
EventQueue.offer(this::failHoldingMonitor);
} else {
Platform.postpone(this::failHoldingMonitor);
}
}
// Incari: wait() throws InterruptedException only once it holds the monitor again, as
// run() does before it returns normally.
private void failHoldingMonitor() {
TThread.setCurrentThread(currentThread);
monitorEnterWait(obj, lockCount, new AsyncCallback<Void>() {
@Override
public void complete(Void result) {
callback.error(new TInterruptedException());
}
@Override
public void error(Throwable e) {
callback.error(e);
}
});
}
}
@Rename("wait")
public final void wait0() throws TInterruptedException {
try {
wait(0L);
} catch (InterruptedException ex) {
throw new TInterruptedException();
}
}
@Override
protected void finalize() throws TThrowable {
}
}
@@ -0,0 +1,439 @@
/*
* Copyright 2015 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the absolute bulk put(int, ByteBuffer, int,
* int) returned without copying when the source had nothing remaining after its position, which
* an absolute put doesn't read; it now returns early only for an empty range. And allocateDirect
* on WebAssembly GC handed out linear memory as its allocator left it, where the JDK's direct
* buffers start zeroed: a new region file's header (RegionFile reads none from an empty file and
* keeps the buffer's contents) pointed its chunks at random sectors. It now clears the memory.
*/
package org.teavm.classlib.java.nio;
import java.nio.BufferUnderflowException;
import java.util.Objects;
import org.teavm.backend.c.runtime.Memory;
import org.teavm.classlib.PlatformDetector;
import org.teavm.classlib.java.lang.TComparable;
import org.teavm.classlib.java.lang.TOutOfMemoryError;
import org.teavm.interop.Address;
import org.teavm.jso.core.JSObjects;
import org.teavm.jso.typedarrays.Int8Array;
import org.teavm.runtime.GC;
import org.teavm.runtime.heap.Heap;
public abstract class TByteBuffer extends TBuffer implements TComparable<TByteBuffer> {
TByteOrder order = TByteOrder.BIG_ENDIAN;
TByteBuffer() {
}
public static TByteBuffer allocateDirect(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity is negative: " + capacity);
}
if (PlatformDetector.isJavaScript()) {
var result = new TByteBufferJsImpl(null, 0, new Int8Array(capacity), true, false);
result.limit = capacity;
return result;
}
if (PlatformDetector.isC()) {
var memory = Memory.malloc(capacity);
var result = new TByteBufferNative(null, null, 0, null, memory, capacity, false);
GC.registerDirectBuffer(Address.ofObject(result).toStructure());
result.limit = capacity;
return result;
}
if (PlatformDetector.isWebAssemblyGC()) {
var addr = Heap.alloc(capacity);
if (addr == null) {
throw new TOutOfMemoryError();
}
// Incari: direct buffers start zeroed, as the JDK's do.
int i = 0;
for (; i + 8 <= capacity; i += 8) {
addr.add(i).putLong(0);
}
for (; i < capacity; i++) {
addr.add(i).putByte((byte) 0);
}
var result = new TByteBufferWasmGC(null, null, 0, null, addr, capacity, false);
result.regKey = JSObjects.create();
result.regToken = JSObjects.create();
result.limit = capacity;
TJSBufferHelper.WasmGC.register(result.regKey, addr, result.regToken);
return result;
}
return new TByteBufferImpl(capacity, true);
}
public static TByteBuffer allocate(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity is negative: " + capacity);
}
if (PlatformDetector.isJavaScript()) {
var array = new byte[capacity];
var result = new TByteBufferJsImpl(array, 0, Int8Array.fromJavaArray(array), false, false);
result.limit = capacity;
return result;
}
if (PlatformDetector.isC()) {
var array = new byte[capacity];
var result = new TByteBufferNative(null, array, 0, array, Address.ofData(array), array.length, false);
result.limit = capacity;
return result;
}
return new TByteBufferImpl(capacity, false);
}
public static TByteBuffer wrap(byte[] array, int offset, int length) {
Objects.checkFromIndexSize(offset, length, array.length);
if (PlatformDetector.isJavaScript()) {
var data = Int8Array.fromJavaArray(array);
var result = new TByteBufferJsImpl(array, 0, data, false, false);
result.position = offset;
result.limit = offset + length;
return result;
}
if (PlatformDetector.isC()) {
var result = new TByteBufferNative(null, array, 0, array, Address.ofData(array), array.length, false);
result.position = offset;
result.limit = offset + length;
return result;
}
return new TByteBufferImpl(0, array.length, array, offset, offset + length, false, false);
}
public static TByteBuffer wrap(byte[] array) {
return wrap(array, 0, array.length);
}
public abstract TByteBuffer slice();
public abstract TByteBuffer duplicate();
public abstract TByteBuffer asReadOnlyBuffer();
public abstract byte get();
public abstract TByteBuffer put(byte b);
public abstract byte get(int index);
public abstract TByteBuffer put(int index, byte b);
public TByteBuffer get(byte[] dst, int offset, int length) {
if (length < 0 || offset < 0 || offset + length > dst.length) {
throw new IndexOutOfBoundsException();
}
if (length > remaining()) {
throw new BufferUnderflowException();
}
getImpl(position, dst, offset, length);
position += length;
return this;
}
public TByteBuffer get(int index, byte[] dst) {
return get(index, dst, 0, dst.length);
}
public TByteBuffer get(int index, byte[] dst, int offset, int length) {
if (length < 0 || offset < 0 || offset + length > dst.length || index < 0 || index + length > capacity()) {
throw new IndexOutOfBoundsException();
}
getImpl(index, dst, offset, length);
return this;
}
abstract void getImpl(int index, byte[] dst, int offset, int length);
public TByteBuffer get(byte[] dst) {
return get(dst, 0, dst.length);
}
public TByteBuffer put(TByteBuffer src) {
if (src == this) {
throw new IllegalArgumentException();
}
var bytesToTransfer = src.remaining();
if (bytesToTransfer > remaining()) {
throw new TBufferOverflowException();
}
if (isReadOnly()) {
throw new TReadOnlyBufferException();
}
putImpl(position(), src, src.position(), bytesToTransfer);
position += bytesToTransfer;
src.position += bytesToTransfer;
return this;
}
public TByteBuffer put(int index, TByteBuffer src, int offset, int length) {
// Incari: an absolute put copies the range it's given, whatever the source's position.
if (length == 0) {
return this;
}
if (isReadOnly()) {
throw new TReadOnlyBufferException();
}
if (length < 0 || offset < 0 || offset + length > src.limit() || index < 0 || index + length > capacity()) {
throw new IndexOutOfBoundsException();
}
putImpl(index, src, offset, length);
return this;
}
abstract void putImpl(int index, TByteBuffer src, int offset, int length);
public TByteBuffer put(byte[] src, int offset, int length) {
if (length == 0) {
return this;
}
if (isReadOnly()) {
throw new TReadOnlyBufferException();
}
if (length < 0 || offset < 0 || offset + length > src.length) {
throw new IndexOutOfBoundsException();
}
if (length > remaining()) {
throw new TBufferOverflowException();
}
putImpl(src, offset, position, length);
position += length;
return this;
}
public final TByteBuffer put(byte[] src) {
return put(src, 0, src.length);
}
public TByteBuffer put(int index, byte[] src) {
return put(index, src, 0, src.length);
}
public TByteBuffer put(int index, byte[] src, int offset, int length) {
if (length == 0) {
return this;
}
if (isReadOnly()) {
throw new TReadOnlyBufferException();
}
if (length < 0 || offset < 0 || offset + length > src.length || index < 0 || index + length > capacity()) {
throw new IndexOutOfBoundsException();
}
putImpl(src, offset, index, length);
return this;
}
abstract void putImpl(byte[] src, int srcOffset, int destOffset, int length);
@Override
public final boolean hasArray() {
return hasArrayImpl();
}
@Override
public final byte[] array() {
return arrayImpl();
}
@Override
public final int arrayOffset() {
return arrayOffsetImpl();
}
abstract boolean hasArrayImpl();
abstract byte[] arrayImpl();
abstract int arrayOffsetImpl();
public abstract TByteBuffer compact();
@Override
public abstract boolean isDirect();
@Override
public String toString() {
return "[ByteBuffer position=" + position + ", limit=" + limit + ", capacity=" + capacity() + ", mark "
+ (mark >= 0 ? " at " + mark : " is not set") + "]";
}
@Override
public int hashCode() {
int hashCode = 0;
int pos = position();
for (int i = position(); i < limit; ++i) {
hashCode = 31 * hashCode + get(pos);
}
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof TByteBuffer)) {
return false;
}
TByteBuffer other = (TByteBuffer) obj;
int sz = remaining();
if (sz != other.remaining()) {
return false;
}
int a = position();
int b = other.position();
for (int i = 0; i < sz; ++i) {
if (get(a++) != other.get(b++)) {
return false;
}
}
return true;
}
@Override
public int compareTo(TByteBuffer other) {
if (this == other) {
return 0;
}
int sz = Math.min(remaining(), other.remaining());
int a = position();
int b = other.position();
for (int i = 0; i < sz; ++i) {
int r = Byte.compare(get(a++), other.get(b++));
if (r != 0) {
return r;
}
}
return Integer.compare(remaining(), other.remaining());
}
public final TByteOrder order() {
return order;
}
public final TByteBuffer order(TByteOrder bo) {
order = bo;
onOrderChanged();
return this;
}
void onOrderChanged() {
}
public abstract char getChar();
public abstract TByteBuffer putChar(char value);
public abstract char getChar(int index);
public abstract TByteBuffer putChar(int index, char value);
public abstract TCharBuffer asCharBuffer();
public abstract short getShort();
public abstract TByteBuffer putShort(short value);
public abstract short getShort(int index);
public abstract TByteBuffer putShort(int index, short value);
public abstract TShortBuffer asShortBuffer();
public abstract int getInt();
public abstract TByteBuffer putInt(int value);
public abstract int getInt(int index);
public abstract TByteBuffer putInt(int index, int value);
public abstract TIntBuffer asIntBuffer();
public abstract long getLong();
public abstract TByteBuffer putLong(long value);
public abstract long getLong(int index);
public abstract TByteBuffer putLong(int index, long value);
public abstract TLongBuffer asLongBuffer();
public abstract float getFloat();
public abstract TByteBuffer putFloat(float value);
public abstract float getFloat(int index);
public abstract TByteBuffer putFloat(int index, float value);
public abstract TFloatBuffer asFloatBuffer();
public abstract double getDouble();
public abstract TByteBuffer putDouble(double value);
public abstract double getDouble(int index);
public abstract TByteBuffer putDouble(int index, double value);
public abstract TDoubleBuffer asDoubleBuffer();
@Override
public final TByteBuffer mark() {
super.mark();
return this;
}
@Override
public final TByteBuffer reset() {
super.reset();
return this;
}
@Override
public final TByteBuffer clear() {
super.clear();
return this;
}
@Override
public final TByteBuffer flip() {
super.flip();
return this;
}
@Override
public final TByteBuffer rewind() {
super.rewind();
return this;
}
@Override
public TByteBuffer limit(int newLimit) {
super.limit(newLimit);
return this;
}
@Override
public TByteBuffer position(int newPosition) {
super.position(newPosition);
return this;
}
}
@@ -0,0 +1,575 @@
/*
* Copyright 2015 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the absolute getLong(int) no longer moves
* the buffer's position.
*/
package org.teavm.classlib.java.nio;
class TByteBufferImpl extends TByteBuffer {
private int capacity;
private int start;
byte[] array;
private boolean direct;
private boolean readOnly;
TByteBufferImpl(int capacity, boolean direct) {
this(0, capacity, new byte[capacity], 0, capacity, direct, false);
}
TByteBufferImpl(int start, int capacity, byte[] array, int position, int limit, boolean direct, boolean readOnly) {
this.start = start;
this.capacity = capacity;
this.array = array;
this.position = position;
this.limit = limit;
this.direct = direct;
this.readOnly = readOnly;
}
@Override
boolean hasArrayImpl() {
return true;
}
@Override
byte[] arrayImpl() {
return array;
}
@Override
int arrayOffsetImpl() {
return start;
}
@Override
int capacityImpl() {
return capacity;
}
@Override
public TByteBuffer slice() {
return new TByteBufferImpl(position + start, limit - position, array, 0, limit - position,
direct, readOnly);
}
@Override
public TByteBuffer duplicate() {
return new TByteBufferImpl(start, capacity, array, position, limit, direct, readOnly);
}
@Override
public TByteBuffer asReadOnlyBuffer() {
return new TByteBufferImpl(start, capacity, array, position, limit, direct, true);
}
@Override
public byte get() {
if (position >= limit) {
throw new TBufferUnderflowException();
}
return array[start + position++];
}
@Override
public TByteBuffer put(byte b) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position >= limit) {
throw new TBufferOverflowException();
}
array[start + position++] = b;
return this;
}
@Override
public byte get(int index) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + limit + ")");
}
return array[start + index];
}
@Override
public TByteBuffer put(int index, byte b) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + limit + ")");
}
array[start + index] = b;
return this;
}
@Override
void getImpl(int index, byte[] dst, int offset, int length) {
System.arraycopy(array, start + index, dst, offset, length);
}
@Override
void putImpl(int index, TByteBuffer src, int offset, int length) {
if (src.hasArray()) {
System.arraycopy(src.array(), src.arrayOffset() + offset, array, start + index, length);
} else {
for (var i = 0; i < length; i++) {
put(index + i, src.get(offset + i));
}
}
}
@Override
void putImpl(byte[] src, int srcOffset, int destOffset, int length) {
System.arraycopy(src, srcOffset, array, start + destOffset, length);
}
@Override
public TByteBuffer compact() {
if (readOnly) {
throw new TReadOnlyBufferException();
}
int sz = remaining();
if (position > 0) {
int dst = start;
int src = start + position;
for (int i = 0; i < sz; ++i) {
array[dst++] = array[src++];
}
}
position = sz;
limit = capacity;
mark = -1;
return this;
}
@Override
public boolean isDirect() {
return direct;
}
@Override
public boolean isReadOnly() {
return readOnly;
}
@Override
public char getChar() {
if (position + 1 >= limit) {
throw new TBufferUnderflowException();
}
int a = array[start + position] & 0xFF;
int b = array[start + position + 1] & 0xFF;
position += 2;
if (order == TByteOrder.BIG_ENDIAN) {
return (char) ((a << 8) | b);
} else {
return (char) ((b << 8) | a);
}
}
@Override
public TByteBuffer putChar(char value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 1 >= limit) {
throw new TBufferOverflowException();
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) value;
} else {
array[start + position++] = (byte) value;
array[start + position++] = (byte) (value >> 8);
}
return this;
}
@Override
public char getChar(int index) {
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
}
int a = array[start + index] & 0xFF;
int b = array[start + index + 1] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) {
return (char) ((a << 8) | b);
} else {
return (char) ((b << 8) | a);
}
}
@Override
public TByteBuffer putChar(int index, char value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte) (value >> 8);
array[start + index + 1] = (byte) value;
} else {
array[start + index] = (byte) value;
array[start + index + 1] = (byte) (value >> 8);
}
return this;
}
@Override
public TCharBuffer asCharBuffer() {
int sz = remaining() / 2;
if (order == TByteOrder.BIG_ENDIAN) {
return new TCharBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TCharBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
@Override
public short getShort() {
if (position + 1 >= limit) {
throw new TBufferUnderflowException();
}
int a = array[start + position] & 0xFF;
int b = array[start + position + 1] & 0xFF;
position += 2;
if (order == TByteOrder.BIG_ENDIAN) {
return (short) ((a << 8) | b);
} else {
return (short) ((b << 8) | a);
}
}
@Override
public TByteBuffer putShort(short value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 1 >= limit) {
throw new TBufferOverflowException();
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) value;
} else {
array[start + position++] = (byte) value;
array[start + position++] = (byte) (value >> 8);
}
return this;
}
@Override
public short getShort(int index) {
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
}
int a = array[start + index] & 0xFF;
int b = array[start + index + 1] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) {
return (short) ((a << 8) | b);
} else {
return (short) ((b << 8) | a);
}
}
@Override
public TByteBuffer putShort(int index, short value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 1) + ")");
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte) (value >> 8);
array[start + index + 1] = (byte) value;
} else {
array[start + index] = (byte) value;
array[start + index + 1] = (byte) (value >> 8);
}
return this;
}
@Override
public TShortBuffer asShortBuffer() {
int sz = remaining() / 2;
if (order == TByteOrder.BIG_ENDIAN) {
return new TShortBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TShortBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
@Override
public int getInt() {
if (position + 3 >= limit) {
throw new TBufferUnderflowException();
}
int a = array[start + position] & 0xFF;
int b = array[start + position + 1] & 0xFF;
int c = array[start + position + 2] & 0xFF;
int d = array[start + position + 3] & 0xFF;
position += 4;
if (order == TByteOrder.BIG_ENDIAN) {
return (a << 24) | (b << 16) | (c << 8) | d;
} else {
return (d << 24) | (c << 16) | (b << 8) | a;
}
}
@Override
public TByteBuffer putInt(int value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 3 >= limit) {
throw new TBufferOverflowException();
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) value;
} else {
array[start + position++] = (byte) value;
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte) (value >> 24);
}
return this;
}
@Override
public int getInt(int index) {
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
}
int a = array[start + index] & 0xFF;
int b = array[start + index + 1] & 0xFF;
int c = array[start + index + 2] & 0xFF;
int d = array[start + index + 3] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) {
return (a << 24) | (b << 16) | (c << 8) | d;
} else {
return (d << 24) | (c << 16) | (b << 8) | a;
}
}
@Override
public TByteBuffer putInt(int index, int value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + index] = (byte) (value >> 24);
array[start + index + 1] = (byte) (value >> 16);
array[start + index + 2] = (byte) (value >> 8);
array[start + index + 3] = (byte) value;
} else {
array[start + index] = (byte) value;
array[start + index + 1] = (byte) (value >> 8);
array[start + index + 2] = (byte) (value >> 16);
array[start + index + 3] = (byte) (value >> 24);
}
return this;
}
@Override
public TIntBuffer asIntBuffer() {
int sz = remaining() / 4;
if (order == TByteOrder.BIG_ENDIAN) {
return new TIntBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TIntBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
@Override
public float getFloat() {
return Float.intBitsToFloat(getInt());
}
@Override
public TByteBuffer putFloat(float value) {
return putInt(Float.floatToRawIntBits(value));
}
@Override
public TByteBuffer putFloat(int index, float value) {
return putInt(index, Float.floatToRawIntBits(value));
}
@Override
public float getFloat(int index) {
return Float.intBitsToFloat(getInt(index));
}
@Override
public double getDouble() {
return Double.longBitsToDouble(getLong());
}
@Override
public TByteBuffer putDouble(double value) {
return putLong(Double.doubleToRawLongBits(value));
}
@Override
public double getDouble(int index) {
return Double.longBitsToDouble(getLong(index));
}
@Override
public TByteBuffer putDouble(int index, double value) {
return putLong(index, Double.doubleToRawLongBits(value));
}
@Override
public long getLong() {
if (position + 7 >= limit) {
throw new TBufferUnderflowException();
}
long a = array[start + position] & 0xFF;
long b = array[start + position + 1] & 0xFF;
long c = array[start + position + 2] & 0xFF;
long d = array[start + position + 3] & 0xFF;
long e = array[start + position + 4] & 0xFF;
long f = array[start + position + 5] & 0xFF;
long g = array[start + position + 6] & 0xFF;
long h = array[start + position + 7] & 0xFF;
position += 8;
if (order == TByteOrder.BIG_ENDIAN) {
return (a << 56) | (b << 48) | (c << 40) | (d << 32) | (e << 24) | (f << 16) | (g << 8) | h;
} else {
return (h << 56) | (g << 48) | (f << 40) | (e << 32) | (d << 24) | (c << 16) | (b << 8) | a;
}
}
@Override
public TByteBuffer putLong(long value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 7 >= limit) {
throw new TBufferOverflowException();
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + position++] = (byte) (value >> 56);
array[start + position++] = (byte) (value >> 48);
array[start + position++] = (byte) (value >> 40);
array[start + position++] = (byte) (value >> 32);
array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) value;
} else {
array[start + position++] = (byte) value;
array[start + position++] = (byte) (value >> 8);
array[start + position++] = (byte) (value >> 16);
array[start + position++] = (byte) (value >> 24);
array[start + position++] = (byte) (value >> 32);
array[start + position++] = (byte) (value >> 40);
array[start + position++] = (byte) (value >> 48);
array[start + position++] = (byte) (value >> 56);
}
return this;
}
@Override
public long getLong(int index) {
if (index < 0 || index + 7 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 7) + ")");
}
long a = array[start + index] & 0xFF;
long b = array[start + index + 1] & 0xFF;
long c = array[start + index + 2] & 0xFF;
long d = array[start + index + 3] & 0xFF;
long e = array[start + index + 4] & 0xFF;
long f = array[start + index + 5] & 0xFF;
long g = array[start + index + 6] & 0xFF;
long h = array[start + index + 7] & 0xFF;
if (order == TByteOrder.BIG_ENDIAN) {
return (a << 56) | (b << 48) | (c << 40) | (d << 32) | (e << 24) | (f << 16) | (g << 8) | h;
} else {
return (h << 56) | (g << 48) | (f << 40) | (e << 32) | (d << 24) | (c << 16) | (b << 8) | a;
}
}
@Override
public TByteBuffer putLong(int index, long value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
}
if (order == TByteOrder.BIG_ENDIAN) {
array[start + index + 0] = (byte) (value >> 56);
array[start + index + 1] = (byte) (value >> 48);
array[start + index + 2] = (byte) (value >> 40);
array[start + index + 3] = (byte) (value >> 32);
array[start + index + 4] = (byte) (value >> 24);
array[start + index + 5] = (byte) (value >> 16);
array[start + index + 6] = (byte) (value >> 8);
array[start + index + 7] = (byte) value;
} else {
array[start + index + 0] = (byte) value;
array[start + index + 1] = (byte) (value >> 8);
array[start + index + 2] = (byte) (value >> 16);
array[start + index + 3] = (byte) (value >> 24);
array[start + index + 4] = (byte) (value >> 32);
array[start + index + 5] = (byte) (value >> 40);
array[start + index + 6] = (byte) (value >> 48);
array[start + index + 7] = (byte) (value >> 56);
}
return this;
}
@Override
public TLongBuffer asLongBuffer() {
int sz = remaining() / 8;
if (order == TByteOrder.BIG_ENDIAN) {
return new TLongBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TLongBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
@Override
public TFloatBuffer asFloatBuffer() {
int sz = remaining() / 4;
if (order == TByteOrder.LITTLE_ENDIAN) {
return new TFloatBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TFloatBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
@Override
public TDoubleBuffer asDoubleBuffer() {
int sz = remaining() / 8;
if (order == TByteOrder.LITTLE_ENDIAN) {
return new TDoubleBufferOverByteBufferBigEndian(start + position, sz, this, 0, sz, isReadOnly());
} else {
return new TDoubleBufferOverByteBufferLittleEndian(start + position, sz, this, 0, sz, isReadOnly());
}
}
}
@@ -0,0 +1,586 @@
/*
* Copyright 2025 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.
*
* Modified for Incari (tools/teavm-patches/README.md): the absolute getLong(int) no longer moves
* the buffer's position.
*/
package org.teavm.classlib.java.nio;
import org.teavm.backend.c.runtime.Memory;
import org.teavm.classlib.PlatformDetector;
import org.teavm.classlib.java.nio.file.TAddressBasedBuffer;
import org.teavm.interop.Address;
import org.teavm.jso.typedarrays.ArrayBufferView;
import org.teavm.jso.typedarrays.Int8Array;
import org.teavm.runtime.heap.Heap;
class TByteBufferNative extends TByteBuffer implements TArrayBufferViewProvider, TNativeBuffer, TAddressBasedBuffer {
Object gcRef;
byte[] array;
int arrayOffset;
@TNativeBufferObjectMarker
Object base;
Address address;
int capacity;
boolean readOnly;
boolean swap;
TByteBufferNative(Object gcRef, byte[] array, int arrayOffset, Object base, Address address, int capacity,
boolean readOnly) {
this.gcRef = gcRef != null ? gcRef : this;
this.array = array;
this.arrayOffset = arrayOffset;
this.base = base;
this.address = address;
this.capacity = capacity;
this.readOnly = readOnly;
updateSwap();
}
@Override
public Address getDataAddress() {
return address;
}
@Override
public void release() {
if (address != Address.fromInt(0)) {
if (PlatformDetector.isWebAssemblyGC()) {
Heap.release(address);
} else {
Memory.free(address);
}
address = Address.fromInt(0);
}
}
@Override
void onOrderChanged() {
updateSwap();
}
private void updateSwap() {
swap = order != TByteOrder.nativeOrder();
}
@Override
byte[] arrayImpl() {
if (array == null) {
throw new UnsupportedOperationException();
}
return array;
}
@Override
int arrayOffsetImpl() {
if (array == null) {
throw new UnsupportedOperationException();
}
return arrayOffset;
}
@Override
boolean hasArrayImpl() {
return array != null;
}
@Override
int capacityImpl() {
return capacity;
}
@Override
void getImpl(int index, byte[] dst, int offset, int length) {
copy(address.add(index), dst, offset, length);
}
@Override
void putImpl(int index, TByteBuffer src, int offset, int length) {
if (src instanceof TByteBufferNative) {
var srcImpl = (TByteBufferNative) src;
copy(srcImpl.address.add(offset), address.add(index), length);
} else if (src.hasArray()) {
copy(src.array(), offset + src.arrayOffset(), address.add(index), length);
} else {
var addr = address.add(index);
while (length-- > 0) {
addr.putByte(src.get(offset++));
addr = addr.add(1);
}
}
}
@Override
void putImpl(byte[] src, int srcOffset, int destOffset, int length) {
copy(src, srcOffset, address.add(destOffset), length);
}
@Override
public TByteBuffer slice() {
var newData = address.add(position);
var result = new TByteBufferNative(gcRef, array, arrayOffset + position, base, newData, remaining(), readOnly);
result.position = 0;
result.limit = result.capacity();
result.order = TByteOrder.BIG_ENDIAN;
return result;
}
@Override
public TByteBuffer duplicate() {
var result = new TByteBufferNative(gcRef, array, arrayOffset + position, base, address, capacity, readOnly);
result.position = position;
result.limit = limit;
result.mark = mark;
result.order = TByteOrder.BIG_ENDIAN;
return result;
}
@Override
public TByteBuffer asReadOnlyBuffer() {
var result = new TByteBufferNative(gcRef, array, arrayOffset + position, base, address, capacity, true);
result.position = position;
result.limit = limit;
result.mark = mark;
result.order = TByteOrder.BIG_ENDIAN;
return result;
}
@Override
public byte get() {
if (position >= limit) {
throw new TBufferUnderflowException();
}
return address.add(position++).getByte();
}
@Override
public TByteBuffer put(byte b) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position >= limit) {
throw new TBufferOverflowException();
}
address.add(position++).putByte(b);
return this;
}
@Override
public byte get(int index) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
return address.add(index).getByte();
}
@Override
public TByteBuffer put(int index, byte b) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
address.add(index).putByte(b);
return this;
}
@Override
public TByteBuffer compact() {
if (readOnly) {
throw new TReadOnlyBufferException();
}
int sz = remaining();
if (position > 0) {
copy(address.add(position), address, sz);
}
position = sz;
limit = capacity();
mark = -1;
return this;
}
@Override
public boolean isDirect() {
return base == null;
}
@Override
public boolean isReadOnly() {
return readOnly;
}
@Override
public char getChar() {
if (position + 1 >= limit) {
throw new TBufferUnderflowException();
}
var result = address.add(position).getChar();
position += 2;
return swap ? Character.reverseBytes(result) : result;
}
@Override
public TByteBuffer putChar(char value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 1 >= limit) {
throw new TBufferOverflowException();
}
address.add(position).putChar(swap ? Character.reverseBytes(value) : value);
position += 2;
return this;
}
@Override
public char getChar(int index) {
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException();
}
var result = address.add(index).getChar();
return swap ? Character.reverseBytes(result) : result;
}
@Override
public TByteBuffer putChar(int index, char value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException();
}
address.add(index).putChar(swap ? Character.reverseBytes(value) : value);
return this;
}
@Override
public TCharBuffer asCharBuffer() {
int sz = remaining() / 2;
return new TCharBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
@Override
public short getShort() {
if (position + 1 >= limit) {
throw new TBufferUnderflowException();
}
var result = address.add(position).getShort();
position += 2;
return swap ? Short.reverseBytes(result) : result;
}
@Override
public TByteBuffer putShort(short value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 1 >= limit) {
throw new TBufferOverflowException();
}
address.add(position).putShort(swap ? Short.reverseBytes(value) : value);
position += 2;
return this;
}
@Override
public short getShort(int index) {
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException();
}
var result = address.add(index).getShort();
return swap ? Short.reverseBytes(result) : result;
}
@Override
public TByteBuffer putShort(int index, short value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 1 >= limit) {
throw new IndexOutOfBoundsException();
}
address.add(index).putShort(swap ? Short.reverseBytes(value) : value);
return this;
}
@Override
public TShortBuffer asShortBuffer() {
int sz = remaining() / 2;
return new TShortBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
@Override
public int getInt() {
if (position + 3 >= limit) {
throw new TBufferUnderflowException();
}
var result = address.add(position).getInt();
position += 4;
return swap ? Integer.reverseBytes(result) : result;
}
@Override
public TByteBuffer putInt(int value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 3 >= limit) {
throw new TBufferOverflowException();
}
address.add(position).putInt(swap ? Integer.reverseBytes(value) : value);
position += 4;
return this;
}
@Override
public int getInt(int index) {
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException();
}
var result = address.add(index).getInt();
return swap ? Integer.reverseBytes(result) : result;
}
@Override
public TByteBuffer putInt(int index, int value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException();
}
address.add(index).putInt(swap ? Integer.reverseBytes(value) : value);
return this;
}
@Override
public TIntBuffer asIntBuffer() {
int sz = remaining() / 4;
return new TIntBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
@Override
public float getFloat() {
if (position + 3 >= limit) {
throw new TBufferUnderflowException();
}
var address = this.address.add(position);
var result = swap
? Float.intBitsToFloat(Integer.reverseBytes(address.getInt()))
: address.getFloat();
position += 4;
return result;
}
@Override
public TByteBuffer putFloat(float value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 3 >= limit) {
throw new TBufferOverflowException();
}
var address = this.address.add(position);
if (swap) {
address.putInt(Integer.reverseBytes(Float.floatToRawIntBits(value)));
} else {
address.putFloat(value);
}
position += 4;
return this;
}
@Override
public TByteBuffer putFloat(int index, float value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index + 3 >= limit) {
throw new TBufferOverflowException();
}
var address = this.address.add(index);
if (swap) {
address.putInt(Integer.reverseBytes(Float.floatToRawIntBits(value)));
} else {
address.putFloat(value);
}
return this;
}
@Override
public float getFloat(int index) {
if (index + 3 >= limit) {
throw new TBufferUnderflowException();
}
var address = this.address.add(index);
return swap
? Float.intBitsToFloat(Integer.reverseBytes(address.getInt()))
: address.getFloat();
}
@Override
public double getDouble() {
if (position + 7 >= limit) {
throw new TBufferUnderflowException();
}
var address = this.address.add(position);
var result = swap
? Double.longBitsToDouble(Long.reverseBytes(address.getLong()))
: address.getDouble();
position += 8;
return result;
}
@Override
public TByteBuffer putDouble(double value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 7 >= limit) {
throw new TBufferOverflowException();
}
var address = this.address.add(position);
if (swap) {
address.putLong(Long.reverseBytes(Double.doubleToRawLongBits(value)));
} else {
address.putDouble(value);
}
position += 8;
return this;
}
@Override
public double getDouble(int index) {
if (index + 7 >= limit) {
throw new TBufferUnderflowException();
}
var address = this.address.add(index);
return swap
? Double.longBitsToDouble(Long.reverseBytes(address.getLong()))
: address.getDouble();
}
@Override
public TByteBuffer putDouble(int index, double value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index + 7 >= limit) {
throw new TBufferOverflowException();
}
var address = this.address.add(index);
if (swap) {
address.putLong(Long.reverseBytes(Double.doubleToRawLongBits(value)));
} else {
address.putDouble(value);
}
return this;
}
@Override
public long getLong() {
if (position + 7 >= limit) {
throw new TBufferUnderflowException();
}
var result = address.add(position).getLong();
position += 8;
return swap ? Long.reverseBytes(result) : result;
}
@Override
public TByteBuffer putLong(long value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (position + 7 >= limit) {
throw new TBufferOverflowException();
}
address.add(position).putLong(swap ? Long.reverseBytes(value) : value);
position += 8;
return this;
}
@Override
public long getLong(int index) {
if (index < 0 || index + 7 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 7) + ")");
}
var result = address.add(index).getLong();
return swap ? Long.reverseBytes(result) : result;
}
@Override
public TByteBuffer putLong(int index, long value) {
if (readOnly) {
throw new TReadOnlyBufferException();
}
if (index < 0 || index + 3 >= limit) {
throw new IndexOutOfBoundsException("Index " + index + " is outside of range [0;" + (limit - 3) + ")");
}
address.add(index).putLong(swap ? Long.reverseBytes(value) : value);
return this;
}
@Override
public TLongBuffer asLongBuffer() {
int sz = remaining() / 8;
return new TLongBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
@Override
public TFloatBuffer asFloatBuffer() {
int sz = remaining() / 4;
return new TFloatBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
@Override
public TDoubleBuffer asDoubleBuffer() {
int sz = remaining() / 8;
return new TDoubleBufferNative(gcRef, null, 0, sz, readOnly, base, address.add(position), sz, swap);
}
void copy(byte[] from, int fromOffset, Address to, int count) {
if (PlatformDetector.isWebAssemblyGC()) {
throw new UnsupportedOperationException();
}
copy(Address.ofData(from).add(fromOffset), to, count);
}
void copy(Address from, byte[] to, int toOffset, int count) {
if (PlatformDetector.isWebAssemblyGC()) {
throw new UnsupportedOperationException();
}
copy(from, Address.ofData(to).add(toOffset), count);
}
static void copy(Address from, Address to, int count) {
Address.moveMemoryBlock(from, to, count);
}
static TByteOrder oppositeOrder(TByteOrder order) {
return order == TByteOrder.BIG_ENDIAN ? TByteOrder.LITTLE_ENDIAN : TByteOrder.BIG_ENDIAN;
}
@Override
public ArrayBufferView getArrayBufferView() {
return new Int8Array(TJSBufferHelper.WasmGC.getLinearMemory(), address.toInt(), capacity);
}
@Override
public int elementSize() {
return 1;
}
}
@@ -0,0 +1,103 @@
/*
* Copyright 2025 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.
*
* Modified for Incari (tools/teavm-patches/README.md): of(URI) asks the scheme's provider for the
* path, as the JDK does, instead of first asking for the file system, which the default provider
* grants only for the root URI.
*/
package org.teavm.classlib.java.nio.file;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystemNotFoundException;
import org.teavm.classlib.java.net.TURI;
import org.teavm.classlib.java.nio.file.spi.TFileSystemProvider;
public interface TPath extends Comparable<TPath>, Iterable<TPath> {
static TPath of(String first, String... more) {
return TFileSystems.getDefault().getPath(first, more);
}
static TPath of(TURI uri) {
for (var provider : TFileSystemProvider.installedProviders()) {
if (provider.getScheme().equalsIgnoreCase(uri.getScheme())) {
return provider.getPath(uri);
}
}
throw new FileSystemNotFoundException();
}
TFileSystem getFileSystem();
boolean isAbsolute();
TPath getRoot();
TPath getFileName();
TPath getParent();
int getNameCount();
TPath getName(int index);
TPath subpath(int beginIndex, int endIndex);
boolean startsWith(TPath other);
default boolean startsWith(String other) {
return startsWith(getFileSystem().getPath(other));
}
boolean endsWith(TPath other);
default boolean endsWith(String other) {
return endsWith(getFileSystem().getPath(other));
}
TPath normalize();
TPath resolve(TPath other);
default TPath resolve(String other) {
return resolve(getFileSystem().getPath(other));
}
default TPath resolveSibling(TPath other) {
return getParent() == null ? other : getParent().resolve(other);
}
default TPath resolveSibling(String other) {
return resolveSibling(getFileSystem().getPath(other));
}
TPath relativize(TPath other);
TURI toUri();
TPath toAbsolutePath();
TPath toRealPath(TLinkOption... options) throws IOException;
@Override
int compareTo(TPath o);
default File toFile() {
if (getFileSystem() != TFileSystems.getDefault()) {
throw new UnsupportedOperationException();
}
return new File(toString());
}
}
@@ -0,0 +1,389 @@
/*
* Copyright 2025 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.
*
* Modified for Incari (tools/teavm-patches/README.md): resolve() made a relative path absolute
* when this path was empty, and doubled the separator after the root.
*/
package org.teavm.classlib.java.nio.file.impl;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.teavm.classlib.java.net.TURI;
import org.teavm.classlib.java.nio.file.TLinkOption;
import org.teavm.classlib.java.nio.file.TPath;
public class TDefaultPath implements TPath {
private TDefaultFileSystem fs;
public final String pathString;
private int[] segments;
public TDefaultPath(TDefaultFileSystem fs, String pathString) {
this.fs = fs;
this.pathString = pathString;
}
@Override
public TDefaultFileSystem getFileSystem() {
return fs;
}
@Override
public boolean isAbsolute() {
return pathString.startsWith("/");
}
@Override
public TDefaultPath getRoot() {
if (!isAbsolute()) {
return null;
}
return new TDefaultPath(fs, "/");
}
@Override
public TDefaultPath getFileName() {
var sep = fs.getSeparatorChar();
var index = pathString.lastIndexOf(sep);
if (index == 0 && pathString.length() == 1) {
return null;
}
return index >= 0 ? new TDefaultPath(fs, pathString.substring(index + 1)) : this;
}
@Override
public TDefaultPath getParent() {
var sep = fs.getSeparatorChar();
var index = pathString.lastIndexOf(sep);
if (index == 0) {
return pathString.length() == 1 ? null : new TDefaultPath(fs, pathString.substring(0, 1));
}
return index > 0 ? new TDefaultPath(fs, pathString.substring(0, index)) : null;
}
@Override
public int getNameCount() {
initSegments();
return segments.length - 1;
}
@Override
public TPath getName(int index) {
return subpath(index, index + 1);
}
@Override
public TPath subpath(int beginIndex, int endIndex) {
if (beginIndex >= endIndex || beginIndex < 0) {
throw new IllegalArgumentException();
}
initSegments();
if (endIndex > segments.length - 1) {
throw new IllegalArgumentException();
}
if (beginIndex == 0 && endIndex == segments.length) {
return this;
}
return new TDefaultPath(fs, pathString.substring(segments[beginIndex] + 1, segments[endIndex]));
}
@Override
public boolean startsWith(TPath other) {
if (!(other instanceof TDefaultPath)) {
return false;
}
var otherPath = (TDefaultPath) other;
if (otherPath.pathString.isEmpty()) {
return pathString.isEmpty();
}
if (fs.vfs.isWindows()) {
if (pathString.length() < otherPath.pathString.length()
|| !pathString.regionMatches(true, 0, otherPath.pathString, 0, otherPath.pathString.length())) {
return false;
}
} else {
if (!pathString.startsWith(otherPath.pathString)) {
return false;
}
}
if (pathString.length() == otherPath.pathString.length()) {
return true;
}
var sep = fs.getSeparatorChar();
return otherPath.pathString.charAt(otherPath.pathString.length() - 1) == sep
|| pathString.charAt(otherPath.pathString.length()) == sep;
}
@Override
public boolean endsWith(TPath other) {
if (!(other instanceof TDefaultPath)) {
return false;
}
var otherPath = (TDefaultPath) other;
if (fs.vfs.isWindows()) {
if (pathString.length() < otherPath.pathString.length()
|| !pathString.regionMatches(true, pathString.length() - otherPath.pathString.length(),
otherPath.pathString, 0, otherPath.pathString.length())) {
return false;
}
} else {
if (!pathString.endsWith(otherPath.pathString)) {
return false;
}
}
return pathString.length() == otherPath.pathString.length()
|| pathString.charAt(pathString.length() - otherPath.pathString.length() - 1) == fs.getSeparatorChar();
}
@Override
public TDefaultPath normalize() {
var result = new char[pathString.length()];
var resultIndex = 0;
initSegments();
var resultSegments = new int[this.segments.length];
var resultSegmentIndex = 0;
var abs = isAbsolute();
if (abs) {
pathString.getChars(0, segments[0], result, 0);
resultIndex = segments[0];
}
var initialLength = resultIndex;
for (var i = 0; i < segments.length - 1; ++i) {
var start = segments[i] + 1;
var end = segments[i + 1];
if (start + 2 == end && pathString.charAt(start) == '.' && pathString.charAt(start + 1) == '.') {
if (resultSegmentIndex > 0) {
resultIndex = resultSegments[--resultSegmentIndex];
} else if (!abs) {
start = Math.max(0, start - 1);
pathString.getChars(start, end, result, resultIndex);
resultIndex += end - start;
}
} else if (start + 1 != end || pathString.charAt(start) != '.') {
resultSegments[resultSegmentIndex++] = resultIndex;
pathString.getChars(start - 1, end, result, resultIndex);
resultIndex += end - start + 1;
}
}
if (resultIndex == pathString.length()) {
return this;
}
if (abs && initialLength == resultIndex) {
result[resultIndex++] = fs.getSeparatorChar();
}
return new TDefaultPath(fs, new String(result, 0, resultIndex));
}
@Override
public TPath resolve(TPath other) {
if (other.isAbsolute()) {
return other;
}
if (other.getNameCount() == 1 && other.getFileName().toString().isEmpty()) {
return this;
}
if (pathString.isEmpty()) {
return other;
}
var separator = pathString.charAt(pathString.length() - 1) == fs.getSeparatorChar()
? "" : String.valueOf(fs.getSeparatorChar());
if (other instanceof TDefaultPath) {
return new TDefaultPath(fs, pathString + separator + ((TDefaultPath) other).pathString);
}
var sb = new StringBuilder(pathString);
if (separator.isEmpty()) {
sb.setLength(sb.length() - 1);
}
var count = other.getNameCount();
for (var i = 0; i < count; ++i) {
sb.append(fs.getSeparatorChar());
sb.append(other.getName(i).toString());
}
return new TDefaultPath(fs, sb.toString());
}
@Override
public TDefaultPath relativize(TPath other) {
if (isAbsolute() != other.isAbsolute()) {
throw new IllegalArgumentException();
}
if (other.equals(this)) {
return new TDefaultPath(fs, "");
}
var otherPath = (TDefaultPath) other;
initSegments();
otherPath.initSegments();
var count = Math.min(otherPath.segments.length, segments.length) - 1;
var index = 0;
for (; index < count; ++index) {
if (segments[index] != otherPath.segments[index]
|| segments[index + 1] != otherPath.segments[index + 1]) {
break;
}
if (!pathString.regionMatches(fs.vfs.isWindows(), segments[index] + 1, otherPath.pathString,
segments[index] + 1, segments[index + 1] - segments[index] - 1)) {
break;
}
}
var sb = new StringBuilder();
var sep = fs.getSeparatorChar();
for (var i = index + 1; i < segments.length; ++i) {
sb.append("..").append(sep);
}
sb.append(otherPath.pathString, otherPath.segments[index] + 1, otherPath.pathString.length());
return new TDefaultPath(fs, sb.toString());
}
@Override
public TDefaultPath toAbsolutePath() {
if (isAbsolute()) {
return this;
}
return new TDefaultPath(fs, toAbsolutePathString());
}
private String toAbsolutePathString() {
var userdir = fs.vfs.getUserDir();
if (fs.vfs.isWindows()) {
userdir = userdir.replace('\\', '/');
}
if (pathString.isEmpty()) {
return userdir;
}
var separatorChar = fs.getSeparatorChar();
var result = new StringBuilder(userdir);
if (result.charAt(result.length() - 1) != separatorChar) {
result.append(separatorChar);
}
result.append(pathString);
return result.toString();
}
@Override
public TURI toUri() {
return new TURI("file", null, toAbsolutePathString(), null, null);
}
@Override
public TPath toRealPath(TLinkOption... options) throws IOException {
var pathString = toAbsolutePath().normalize().pathString;
return new TDefaultPath(fs, fs.vfs.canonicalize(pathString));
}
@Override
public int compareTo(TPath o) {
var other = (TDefaultPath) o;
if (this.fs != other.fs) {
throw new ClassCastException();
}
return fs.vfs.isWindows()
? pathString.compareToIgnoreCase(other.pathString)
: pathString.compareTo(other.pathString);
}
@Override
public Iterator<TPath> iterator() {
initSegments();
return new Iterator<>() {
int index;
int count = segments.length - 1;
@Override
public boolean hasNext() {
return index < count;
}
@Override
public TPath next() {
if (index >= count) {
throw new NoSuchElementException();
}
var result = new TDefaultPath(fs, pathString.substring(segments[index] + 1, segments[index + 1]));
++index;
return result;
}
};
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof TDefaultPath)) {
return false;
}
var other = (TDefaultPath) obj;
if (fs != other.fs) {
return false;
}
return fs.vfs.isWindows()
? pathString.equalsIgnoreCase(other.pathString)
: pathString.equals(other.pathString);
}
@Override
public int hashCode() {
return fs.vfs.isWindows() ? pathString.toLowerCase().hashCode() : pathString.hashCode();
}
@Override
public String toString() {
return pathString;
}
private void initSegments() {
if (segments == null) {
var sep = fs.getSeparatorChar();
var count = 1;
var startIndex = 0;
if (!pathString.isEmpty() && pathString.charAt(0) == sep) {
++startIndex;
if (startIndex == pathString.length()) {
segments = new int[] { 0 };
return;
}
}
var index = startIndex;
while (true) {
var next = pathString.indexOf(sep, index);
if (next < 0) {
break;
}
++count;
index = next + 1;
}
var result = new int[count + 1];
var resultIndex = 0;
segments = result;
index = startIndex;
result[resultIndex++] = startIndex - 1;
while (true) {
var next = pathString.indexOf(sep, index);
if (next < 0) {
break;
}
result[resultIndex++] = next;
index = next + 1;
}
result[resultIndex] = pathString.length();
}
}
}
@@ -0,0 +1,396 @@
/*
* Copyright 2014 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.
*
* Modified for Incari (tools/teavm-patches/README.md): after the forward iterator's remove()
* shifts the later elements left, the next element is at the removed slot; the iterator stepped
* past it instead, skipping one element and reading past the end (null) at the last.
* And removeAt() shifts with System.arraycopy rather than a loop: the particle engine removes
* each dead particle through the iterator, and the loop was 2% of the lobby on the floor stand-in.
*/
package org.teavm.classlib.java.util;
import java.util.Arrays;
import org.teavm.classlib.java.io.TSerializable;
import org.teavm.classlib.java.lang.TCloneable;
public class TArrayDeque<E> extends TAbstractCollection<E> implements TDeque<E>, TCloneable, TSerializable {
private int version;
private Object[] array;
private int head;
private int tail;
public TArrayDeque() {
this(8);
}
public TArrayDeque(int numElements) {
array = new Object[numElements + 1];
}
public TArrayDeque(TCollection<? extends E> c) {
if (c.isEmpty()) {
array = new Object[8];
} else {
array = new Object[c.size() + 1];
int index = 0;
for (var it = c.iterator(); it.hasNext();) {
array[index++] = it.next();
}
tail = array.length - 1;
}
}
@Override
public void addFirst(E e) {
TObjects.requireNonNull(e);
ensureCapacity(size() + 1);
head = modDec(head, array.length);
array[head] = e;
++version;
}
@Override
public void addLast(E e) {
TObjects.requireNonNull(e);
ensureCapacity(size() + 1);
array[tail] = e;
tail = modInc(tail, array.length);
++version;
}
@Override
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
@Override
public boolean offerLast(E e) {
addLast(e);
return true;
}
@Override
public E removeFirst() {
E value = pollFirst();
if (value == null) {
throw new TNoSuchElementException();
}
return value;
}
@Override
public E removeLast() {
E value = pollLast();
if (value == null) {
throw new TNoSuchElementException();
}
return value;
}
@Override
public E pollFirst() {
if (head == tail) {
return null;
}
@SuppressWarnings("unchecked")
E result = (E) array[head];
array[head] = null;
head = modInc(head, array.length);
++version;
return result;
}
@Override
public E pollLast() {
if (head == tail) {
return null;
}
tail = modDec(tail, array.length);
@SuppressWarnings("unchecked")
E result = (E) array[tail];
array[tail] = null;
++version;
return result;
}
@Override
public E getFirst() {
E result = peekFirst();
if (result == null) {
throw new TNoSuchElementException();
}
return result;
}
@Override
public E getLast() {
E result = peekLast();
if (result == null) {
throw new TNoSuchElementException();
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public E peekFirst() {
return !isEmpty() ? (E) array[head] : null;
}
@Override
@SuppressWarnings("unchecked")
public E peekLast() {
return !isEmpty() ? (E) array[modDec(tail, array.length)] : null;
}
@Override
public boolean removeFirstOccurrence(Object o) {
if (o == null) {
return false;
}
for (var it = iterator(); it.hasNext();) {
if (it.next().equals(o)) {
it.remove();
return true;
}
}
return false;
}
@Override
public boolean removeLastOccurrence(Object o) {
if (o == null) {
return false;
}
for (var it = descendingIterator(); it.hasNext();) {
if (it.next().equals(o)) {
it.remove();
return true;
}
}
return false;
}
@Override
public boolean add(E e) {
addLast(e);
return true;
}
@Override
public boolean offer(E e) {
return offerLast(e);
}
@Override
public E remove() {
return removeFirst();
}
@Override
public E poll() {
return pollFirst();
}
@Override
public E element() {
return getFirst();
}
@Override
public E peek() {
return peekFirst();
}
@Override
public void push(E e) {
addFirst(e);
}
@Override
public E pop() {
return removeFirst();
}
@Override
public int size() {
return tail >= head ? tail - head : array.length - head + tail;
}
@Override
public boolean isEmpty() {
return head == tail;
}
private boolean removeAt(int index) {
// Incari: the shifts are one System.arraycopy each (overlapping ranges copy as if through
// a temporary array), not a loop of element stores.
if (head < tail) {
if (tail - index < index - head) {
System.arraycopy(array, index + 1, array, index, tail - index - 1);
array[--tail] = null;
return true;
} else {
System.arraycopy(array, head, array, head + 1, index - head);
array[head++] = null;
return false;
}
} else {
if (index >= head) {
System.arraycopy(array, head, array, head + 1, index - head);
array[head] = null;
head = modInc(head, array.length);
return false;
} else {
System.arraycopy(array, index + 1, array, index, tail - index - 1);
tail = modDec(tail, array.length);
array[tail] = null;
return true;
}
}
}
private static int modInc(int i, int mod) {
return ++i == mod ? 0 : i;
}
private static int modDec(int i, int mod) {
return --i == -1 ? mod - 1 : i;
}
@Override
public TIterator<E> iterator() {
return new TIterator<>() {
private int refVersion = version;
private int index = head;
private int lastIndex = -1;
private int left = size();
@Override
public boolean hasNext() {
return left > 0;
}
@Override
public E next() {
if (--left < 0) {
throw new TNoSuchElementException();
}
if (version > refVersion) {
throw new TConcurrentModificationException();
}
lastIndex = index;
@SuppressWarnings("unchecked")
E result = (E) array[index];
index = modInc(index, array.length);
return result;
}
@Override
public void remove() {
if (lastIndex < 0) {
throw new IllegalStateException();
}
boolean toLeft = removeAt(lastIndex);
if (toLeft) {
// Incari: the next element moved into the removed slot; was modInc.
index = modDec(index, array.length);
}
lastIndex = -1;
}
};
}
@Override
public TIterator<E> descendingIterator() {
return new TIterator<>() {
private int refVersion = version;
private int index = tail;
private int lastIndex = -1;
private int left = size();
@Override
public boolean hasNext() {
return left > 0;
}
@Override
public E next() {
if (--left < 0) {
throw new TNoSuchElementException();
}
if (version > refVersion) {
throw new TConcurrentModificationException();
}
index = modDec(index, array.length);
lastIndex = index;
@SuppressWarnings("unchecked")
E result = (E) array[index];
return result;
}
@Override
public void remove() {
if (lastIndex < 0) {
throw new IllegalStateException();
}
boolean toLeft = removeAt(lastIndex);
if (!toLeft) {
index = modInc(index, array.length);
}
lastIndex = -1;
}
};
}
private void ensureCapacity(int capacity) {
if (capacity < array.length) {
return;
}
int newArraySize = Math.max(array.length * 2, capacity * 3 / 2 + 1);
if (newArraySize < 1) {
newArraySize = Integer.MAX_VALUE;
}
Object[] newArray = new Object[newArraySize];
int j = 0;
if (head <= tail) {
for (int i = head; i < tail; ++i) {
newArray[j++] = array[i];
}
} else {
for (int i = head; i < array.length; ++i) {
newArray[j++] = array[i];
}
for (int i = 0; i < tail; ++i) {
newArray[j++] = array[i];
}
}
head = 0;
tail = j;
array = newArray;
}
@Override
public void clear() {
Arrays.fill(array, null);
head = tail;
}
@Override
protected TArrayDeque<E> clone() {
return new TArrayDeque<>(this);
}
}
@@ -0,0 +1,713 @@
/*
* Copyright 2014 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.
*
* Modified for Incari (tools/teavm-patches/README.md): unmodifiableCollection() left isEmpty(),
* contains() and containsAll() to AbstractCollection's walk of the iterator, so a hash set wrapped
* in it looked elements up in linear time. They now ask the collection it wraps. (TeaVM 0.16.0
* made the same change to unmodifiableSet() and unmodifiableMap().)
*/
package org.teavm.classlib.java.util;
import java.util.RandomAccess;
import org.teavm.classlib.java.lang.*;
import org.teavm.classlib.java.util.TMap.Entry;
import org.teavm.classlib.java.util.random.TRandomGenerator;
public final class TCollections extends TObject {
@SuppressWarnings("rawtypes")
public static final TSet EMPTY_SET = new TTemplateCollections.AbstractImmutableSet<>() {
@Override public int size() {
return 0;
}
@Override public TIterator<Object> iterator() {
return emptyIterator();
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(Object o) {
return false;
}
@Override public boolean containsAll(TCollection<?> c) {
return c.isEmpty();
}
};
@SuppressWarnings("rawtypes")
public static final TMap EMPTY_MAP = new TTemplateCollections.AbstractImmutableMap<>() {
@Override public TSet<Entry<Object, Object>> entrySet() {
return emptySet();
}
@Override
public int size() {
return 0;
}
@Override public Object get(Object key) {
return null;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean containsKey(Object key) {
return false;
}
@Override public boolean containsValue(Object value) {
return false;
}
};
@SuppressWarnings("rawtypes")
public static final TList EMPTY_LIST = new TTemplateCollections.AbstractImmutableList<>() {
@Override public Object get(int index) {
throw new TIndexOutOfBoundsException();
}
@Override public int size() {
return 0;
}
@Override
public TIterator<Object> iterator() {
return emptyIterator();
}
@Override
public TListIterator<Object> listIterator(int index) {
if (index != 0) {
throw new IndexOutOfBoundsException();
}
return emptyListIterator();
}
@Override public boolean isEmpty() {
return true;
}
};
private static final TIterator<?> EMPTY_ITERATOR = new TIterator<>() {
@Override public boolean hasNext() {
return false;
}
@Override public Object next() {
throw new TNoSuchElementException();
}
@Override public void remove() {
throw new TIllegalStateException();
}
};
private static final TListIterator<?> EMPTY_LIST_ITERATOR = new TListIterator<>() {
@Override public boolean hasNext() {
return false;
}
@Override public Object next() {
throw new TNoSuchElementException();
}
@Override public void remove() {
throw new TIllegalStateException();
}
@Override public boolean hasPrevious() {
return false;
}
@Override public Object previous() {
throw new TNoSuchElementException();
}
@Override public int nextIndex() {
return 0;
}
@Override public int previousIndex() {
return -1;
}
@Override public void set(Object e) {
throw new TUnsupportedOperationException();
}
@Override public void add(Object e) {
throw new TUnsupportedOperationException();
}
};
@SuppressWarnings("unchecked")
public static <T> TIterator<T> emptyIterator() {
return (TIterator<T>) EMPTY_ITERATOR;
}
@SuppressWarnings("unchecked")
public static <T> TListIterator<T> emptyListIterator() {
return (TListIterator<T>) EMPTY_LIST_ITERATOR;
}
@SuppressWarnings("unchecked")
public static <T> TList<T> emptyList() {
return (TList<T>) EMPTY_LIST;
}
public static <T> TEnumeration<T> emptyEnumeration() {
return new TEnumeration<>() {
@Override public boolean hasMoreElements() {
return false;
}
@Override public T nextElement() {
throw new TNoSuchElementException();
}
};
}
@SuppressWarnings("unchecked")
public static <T> TSet<T> emptySet() {
return (TSet<T>) EMPTY_SET;
}
@SuppressWarnings("unchecked")
public static <K, V> TMap<K, V> emptyMap() {
return (TMap<K, V>) EMPTY_MAP;
}
public static <T> TList<T> singletonList(T o) {
return new TTemplateCollections.SingleElementList<>(o);
}
public static <T> TSet<T> singleton(T o) {
return new TTemplateCollections.SingleElementSet<>(o);
}
public static <K, V> TMap<K, V> singletonMap(final K key, final V value) {
final TSet<Entry<K, V>> entries = singleton(new TAbstractMap.SimpleImmutableEntry<>(key, value));
return new TAbstractMap<>() {
@Override public TSet<Entry<K, V>> entrySet() {
return entries;
}
};
}
public static <T> TList<T> nCopies(final int n, final T o) {
if (n < 0) {
throw new IllegalArgumentException();
}
return new TAbstractList<>() {
@Override public T get(int index) {
if (index < 0 || index >= n) {
throw new TIndexOutOfBoundsException();
}
return o;
}
@Override public int size() {
return n;
}
};
}
public static void swap(TList<?> list, int i, int j) {
@SuppressWarnings("unchecked")
TList<Object> objList = (TList<Object>) list;
Object tmp = objList.get(i);
objList.set(i, objList.get(j));
objList.set(j, tmp);
}
public static <T> void sort(TList<T> list, TComparator<? super T> c) {
if (c == null) {
c = TComparator.NaturalOrder.instance();
}
@SuppressWarnings("unchecked")
T[] array = (T[]) new Object[list.size()];
list.toArray(array);
TArrays.sort(array, c);
for (int i = 0; i < array.length; ++i) {
list.set(i, array[i]);
}
}
public static <T extends TComparable<? super T>> void sort(TList<T> list) {
sort(list, TComparator.NaturalOrder.instance());
}
@SuppressWarnings("unchecked")
public static void reverse(TList<?> list) {
if (list instanceof RandomAccess) {
reverse(list, 0, list.size());
} else {
TList<Object> randomAccess = new TArrayList<>(list);
reverse(randomAccess, 0, randomAccess.size());
list.clear();
((TList<Object>) list).addAll(randomAccess);
}
}
public static <T> int binarySearch(TList<? extends TComparable<? super T>> list, T key) {
return binarySearch(list, key, TComparator.NaturalOrder.instance());
}
public static <T> int binarySearch(TList<? extends T> list, T key, TComparator<? super T> c) {
if (!(list instanceof TRandomAccess)) {
list = new TArrayList<>(list);
}
if (c == null) {
c = TComparator.NaturalOrder.instance();
}
int l = 0;
int u = list.size() - 1;
if (u < 0) {
return -1;
}
while (true) {
int i = (l + u) / 2;
T e = list.get(i);
int cmp = c.compare(e, key);
if (cmp == 0) {
return i;
} else if (cmp > 0) {
u = i - 1;
if (u < l) {
return -i - 1;
}
} else {
l = i + 1;
if (l > u) {
return -i - 2;
}
}
}
}
public static void shuffle(TList<?> list) {
shuffle(list, new TRandom());
}
public static void shuffle(TList<?> list, TRandom rnd) {
shuffle(list, (TRandomGenerator) rnd);
}
@SuppressWarnings("unchecked")
public static void shuffle(TList<?> list, TRandomGenerator rnd) {
if (list instanceof TRandomAccess) {
shuffleRandomAccess(list, rnd);
} else {
TList<Object> randomAccess = new TArrayList<>(list);
shuffleRandomAccess(randomAccess, rnd);
list.clear();
((TList<Object>) list).addAll(randomAccess);
}
}
private static void shuffleRandomAccess(TList<?> list, TRandomGenerator rnd) {
for (int i = list.size() - 1; i > 0; --i) {
int j = rnd.nextInt(i + 1);
swap(list, i, j);
}
}
public static <T> void fill(TList<? super T> list, T obj) {
if (list instanceof RandomAccess) {
for (int i = 0; i < list.size(); ++i) {
list.set(i, obj);
}
} else {
for (TListIterator<? super T> iter = list.listIterator(); iter.hasNext();) {
iter.next();
iter.set(obj);
}
}
}
public static <T> void copy(TList<? super T> dest, TList<? extends T> src) {
if (src.size() > dest.size()) {
throw new IndexOutOfBoundsException();
}
if (src instanceof RandomAccess && dest instanceof RandomAccess) {
for (int i = 0; i < src.size(); ++i) {
dest.set(i, src.get(i));
}
} else {
TListIterator<? extends T> srcIter = src.listIterator();
TListIterator<? super T> destIter = dest.listIterator();
while (srcIter.hasNext()) {
destIter.next();
destIter.set(srcIter.next());
}
}
}
public static <T extends Object & TComparable<? super T>> T min(TCollection<? extends T> coll) {
return min(coll, TComparator.NaturalOrder.instance());
}
public static <T> T min(TCollection<? extends T> coll, TComparator<? super T> comp) {
if (comp == null) {
comp = TComparator.NaturalOrder.instance();
}
TIterator<? extends T> iter = coll.iterator();
T min = iter.next();
while (iter.hasNext()) {
T elem = iter.next();
if (comp.compare(elem, min) < 0) {
min = elem;
}
}
return min;
}
public static <T extends Object & TComparable<? super T>> T max(TCollection<? extends T> coll) {
return max(coll, TComparator.NaturalOrder.instance());
}
public static <T> T max(TCollection<? extends T> coll, TComparator<? super T> comp) {
if (comp == null) {
comp = TComparator.NaturalOrder.instance();
}
TIterator<? extends T> iter = coll.iterator();
T max = iter.next();
while (iter.hasNext()) {
T elem = iter.next();
if (comp.compare(elem, max) > 0) {
max = elem;
}
}
return max;
}
@SuppressWarnings("unchecked")
public static void rotate(TList<?> list, int distance) {
if (list instanceof TRandomAccess) {
rotateRandomAccess(list, distance);
} else {
TList<Object> randomAccess = new TArrayList<>(list);
rotateRandomAccess(randomAccess, distance);
list.clear();
((TList<Object>) list).addAll(randomAccess);
}
}
private static void rotateRandomAccess(TList<?> list, int distance) {
distance %= list.size();
if (distance < 0) {
distance += list.size();
}
if (distance == 0) {
return;
}
reverse(list, 0, list.size());
reverse(list, 0, distance);
reverse(list, distance, list.size());
}
private static void reverse(TList<?> list, int from, int to) {
@SuppressWarnings("unchecked")
TList<Object> safeList = (TList<Object>) list;
int half = (from + to) / 2;
int j = to - 1;
for (int i = from; i < half; ++i, --j) {
Object tmp = safeList.get(i);
safeList.set(i, safeList.get(j));
safeList.set(j, tmp);
}
}
public static <T> boolean replaceAll(TList<T> list, T oldVal, T newVal) {
TListIterator<T> iter = list.listIterator();
boolean hasValue = false;
while (iter.hasNext()) {
if (TObjects.equals(iter.next(), oldVal)) {
iter.set(newVal);
hasValue = true;
}
}
return hasValue;
}
public static int indexOfSubList(TList<?> source, TList<?> target) {
int sz = source.size() - target.size();
if (sz < 0) {
return -1;
}
if (source instanceof RandomAccess) {
source = new TArrayList<>(source);
}
outer: for (int i = 0; i <= sz; ++i) {
int j = i;
for (TIterator<?> iter = target.iterator(); iter.hasNext();) {
if (!iter.next().equals(source.get(j++))) {
continue outer;
}
}
return i;
}
return -1;
}
public static int lastIndexOfSubList(TList<?> source, TList<?> target) {
int start = source.size() - target.size();
if (start < 0) {
return -1;
}
if (source instanceof RandomAccess) {
source = new TArrayList<>(source);
}
outer: for (int i = start; i >= 0; --i) {
int j = i;
for (TIterator<?> iter = target.iterator(); iter.hasNext();) {
if (!iter.next().equals(source.get(j++))) {
continue outer;
}
}
return i;
}
return -1;
}
public static <T> TList<T> unmodifiableList(final TList<? extends T> list) {
TObjects.requireNonNull(list);
return new TAbstractList<>() {
@Override public T get(int index) {
return list.get(index);
}
@Override public int size() {
return list.size();
}
@Override public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
};
}
public static <T> TCollection<T> unmodifiableCollection(final TCollection<? extends T> c) {
TObjects.requireNonNull(c);
return new TAbstractCollection<>() {
@Override public TIterator<T> iterator() {
return unmodifiableIterator(c.iterator());
}
@Override public int size() {
return c.size();
}
@Override public boolean isEmpty() {
return c.isEmpty();
}
@Override public boolean contains(Object o) {
return c.contains(o);
}
@Override public boolean containsAll(TCollection<?> other) {
return c.containsAll(other);
}
@Override public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
};
}
private static <T> TIterator<T> unmodifiableIterator(final TIterator<? extends T> c) {
return new TIterator<>() {
@Override public boolean hasNext() {
return c.hasNext();
}
@Override public T next() {
return c.next();
}
@Override public void remove() {
throw new TUnsupportedOperationException();
}
};
}
public static <T> TSet<T> unmodifiableSet(final TSet<? extends T> s) {
TObjects.requireNonNull(s);
return new TAbstractSet<>() {
@Override public TIterator<T> iterator() {
return unmodifiableIterator(s.iterator());
}
@Override public int size() {
return s.size();
}
@Override public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override public boolean contains(Object o) {
return s.contains(o);
}
@Override public boolean containsAll(TCollection<?> c) {
return s.containsAll(c);
}
@Override public boolean isEmpty() {
return s.isEmpty();
}
};
}
public static <K, V> TMap<K, V> unmodifiableMap(final TMap<? extends K, ? extends V> m) {
TObjects.requireNonNull(m);
return new TAbstractMap<>() {
private TSet<Entry<K, V>> entrySetCache;
@Override public TSet<Entry<K, V>> entrySet() {
if (entrySetCache == null) {
entrySetCache = unmodifiableMapEntrySet(m.entrySet());
}
return entrySetCache;
}
@Override public V remove(Object o) {
throw new UnsupportedOperationException();
}
@Override public boolean containsKey(Object key) {
return m.containsKey(key);
}
@Override public boolean containsValue(Object value) {
return m.containsValue(value);
}
@Override public int size() {
return m.size();
}
@Override public V get(Object key) {
return m.get(key);
}
@Override public boolean isEmpty() {
return m.isEmpty();
}
};
}
private static <K, V> TSet<Entry<K, V>> unmodifiableMapEntrySet(
final TSet<? extends Entry<? extends K, ? extends V>> c) {
return new TAbstractSet<>() {
@Override public int size() {
return c.size();
}
@Override public TIterator<Entry<K, V>> iterator() {
return unmodifiableMapEntryIterator(c.iterator());
}
@Override public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
};
}
private static <K, V> TIterator<Entry<K, V>> unmodifiableMapEntryIterator(
final TIterator<? extends Entry<? extends K, ? extends V>> c) {
return new TIterator<>() {
@Override public boolean hasNext() {
return c.hasNext();
}
@Override public Entry<K, V> next() {
return new TAbstractMap.SimpleImmutableEntry<>(c.next());
}
@Override public void remove() {
throw new TUnsupportedOperationException();
}
};
}
public static <T> TCollection<T> synchronizedCollection(TCollection<T> c) {
return c;
}
public static <T> TSet<T> synchronizedSet(TSet<T> s) {
return s;
}
public static <T> TList<T> synchronizedList(TList<T> list) {
return list;
}
public static <K, V> TMap<K, V> synchronizedMap(TMap<K, V> m) {
return m;
}
@SuppressWarnings("unchecked")
public static <T> TComparator<T> reverseOrder() {
return (TComparator<T>) reverseOrder;
}
@SuppressWarnings("unchecked")
private static TComparator<Object> reverseOrder = (o1, o2) -> ((TComparable<Object>) o2).compareTo(o1);
public static <T> TComparator<T> reverseOrder(final TComparator<T> cmp) {
if (cmp == null) {
return reverseOrder();
}
return (o1, o2) -> -cmp.compare(o1, o2);
}
public static <T> TEnumeration<T> enumeration(TCollection<T> c) {
final TIterator<T> iter = c.iterator();
return new TEnumeration<>() {
@Override public boolean hasMoreElements() {
return iter.hasNext();
}
@Override public T nextElement() {
return iter.next();
}
};
}
public static <T> TArrayList<T> list(TEnumeration<T> e) {
TArrayList<T> list = new TArrayList<>();
while (e.hasMoreElements()) {
list.add(e.nextElement());
}
return list;
}
public static <E> TCollection<E> checkedCollection(TCollection<E> c, Class<E> type) {
return new TCheckedCollection<>(c, type);
}
public static <E> TSet<E> checkedSet(TSet<E> s, Class<E> type) {
return new TCheckedSet<>(s, type);
}
public static <E> TList<E> checkedList(TList<E> list, Class<E> type) {
return new TCheckedList<>(list, type);
}
public static <K, V> TMap<K, V> checkedMap(TMap<K, V> m, Class<K> keyType, Class<V> valueType) {
return new TCheckedMap<>(m, keyType, valueType);
}
public static int frequency(TCollection<?> c, Object o) {
int freq = 0;
for (TIterator<?> iter = c.iterator(); iter.hasNext();) {
if (TObjects.equals(iter.next(), o)) {
++freq;
}
}
return freq;
}
public static boolean disjoint(TCollection<?> c1, TCollection<?> c2) {
if (c1.size() > c2.size()) {
TCollection<?> tmp = c1;
c1 = c2;
c2 = tmp;
}
for (TIterator<?> iter = c1.iterator(); iter.hasNext();) {
if (c2.contains(iter.next())) {
return false;
}
}
return true;
}
@SafeVarargs
public static <T> boolean addAll(TCollection<? super T> c, T... elements) {
return c.addAll(TArrays.asList(elements));
}
public static <E> TSet<E> newSetFromMap(TMap<E, TBoolean> map) {
if (!map.isEmpty()) {
throw new IllegalArgumentException();
}
return new TSetFromMap<>(map);
}
public static <E> TSequencedSet<E> newSequencedSetFromMap(TSequencedMap<E, TBoolean> map) {
if (!map.isEmpty()) {
throw new IllegalArgumentException();
}
return new TSetFromMap.SequencedSetFromMap<E>(map);
}
}
@@ -0,0 +1,697 @@
/*
* Copyright 2017 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.
*
* Modified for Incari (tools/teavm-patches/README.md): %% and %n no longer take an argument (a
* %d after %% read the argument after its own, and past the end of the arguments threw
* ArrayIndexOutOfBoundsException); %% honours its width and '-' flag, %n writes the line
* separator; and %d of Long.MIN_VALUE or Integer.MIN_VALUE no longer prints two minus signs.
*/
package org.teavm.classlib.java.util;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.DuplicateFormatFlagsException;
import java.util.FormatFlagsConversionMismatchException;
import java.util.IllegalFormatConversionException;
import java.util.Locale;
import java.util.UnknownFormatConversionException;
import org.teavm.classlib.impl.IntegerUtil;
import org.teavm.classlib.java.text.TDecimalFormat;
public final class TFormatter implements Closeable, Flushable {
private Locale locale;
private Appendable out;
private IOException ioException;
public TFormatter() {
this(Locale.getDefault());
}
public TFormatter(Appendable a) {
this(a, Locale.getDefault());
}
public TFormatter(Locale l) {
this(new StringBuilder(), l);
}
public TFormatter(Appendable a, Locale l) {
out = a;
locale = l;
}
public TFormatter(PrintStream ps) {
this(new OutputStreamWriter(ps));
}
public TFormatter(OutputStream os) {
this(new OutputStreamWriter(os));
}
public TFormatter(OutputStream os, String csn) throws UnsupportedEncodingException {
this(new OutputStreamWriter(os, csn));
}
public TFormatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException {
this(new OutputStreamWriter(os, csn), l);
}
public Locale locale() {
requireOpen();
return locale;
}
public Appendable out() {
requireOpen();
return out;
}
private void requireOpen() {
if (out == null) {
throw new TFormatterClosedException();
}
}
@Override
public String toString() {
requireOpen();
return out.toString();
}
@Override
public void flush() {
requireOpen();
if (out instanceof Flushable) {
try {
((Flushable) out).flush();
} catch (IOException e) {
ioException = e;
}
}
}
@Override
public void close() {
requireOpen();
try {
if (out instanceof Closeable) {
((Closeable) out).close();
}
} catch (IOException e) {
ioException = e;
} finally {
out = null;
}
}
public IOException ioException() {
return ioException;
}
public TFormatter format(String format, Object... args) {
return format(locale, format, args);
}
public TFormatter format(Locale l, String format, Object... args) {
requireOpen();
try {
if (args == null) {
args = new Object[1];
}
new FormatWriter(this, out, l, format, args).write();
} catch (IOException e) {
ioException = e;
}
return this;
}
static class FormatWriter {
private static final String FORMAT_FLAGS = "--#+ 0,(<";
private static final int MASK_FOR_GENERAL_FORMAT =
TFormattableFlags.LEFT_JUSTIFY | TFormattableFlags.ALTERNATE
| TFormattableFlags.UPPERCASE | TFormattableFlags.PREVIOUS_ARGUMENT;
private static final int MASK_FOR_CHAR_FORMAT =
TFormattableFlags.LEFT_JUSTIFY | TFormattableFlags.UPPERCASE | TFormattableFlags.PREVIOUS_ARGUMENT;
private static final int MASK_FOR_INT_DECIMAL_FORMAT = MASK_FOR_GENERAL_FORMAT ^ TFormattableFlags.ALTERNATE
| TFormattableFlags.LEADING_SPACE | TFormattableFlags.ZERO_PADDED
| TFormattableFlags.PARENTHESIZED_NEGATIVE | TFormattableFlags.SIGNED
| TFormattableFlags.GROUPING_SEPARATOR;
private static final int MASK_FOR_INT_RADIX_FORMAT = MASK_FOR_GENERAL_FORMAT
| TFormattableFlags.ZERO_PADDED | TFormattableFlags.PARENTHESIZED_NEGATIVE;
private TFormatter formatter;
Appendable out;
Locale locale;
String format;
Object[] args;
int index;
int formatSpecifierStart;
int defaultArgumentIndex;
int argumentIndex;
int previousArgumentIndex;
int width;
int precision;
int flags;
FormatWriter(TFormatter formatter, Appendable out, Locale locale, String format, Object[] args) {
this.formatter = formatter;
this.out = out;
this.locale = locale;
this.format = format;
this.args = args;
}
void write() throws IOException {
while (true) {
int next = format.indexOf('%', index);
if (next < 0) {
out.append(format.substring(index));
break;
}
out.append(format.substring(index, next));
index = next + 1;
formatSpecifierStart = index;
char specifier = parseFormatSpecifier();
if (specifier == '%') {
// Takes no argument, as the JDK's: '%%' mustn't move the argument index.
verifyFlags(specifier, TFormattableFlags.LEFT_JUSTIFY);
if ((flags & TFormattableFlags.LEFT_JUSTIFY) != 0 && width < 0) {
throw new TMissingFormatWidthException(format.substring(formatSpecifierStart, index));
}
if (precision >= 0) {
throw new TIllegalFormatPrecisionException(precision);
}
formatGivenString(false, "%");
continue;
}
if (specifier == 'n') {
// TeaVM has no IllegalFormatWidthException; a width is reported as a flag.
if (flags != 0 || width >= 0) {
throw new TIllegalFormatFlagsException(format.substring(formatSpecifierStart, index));
}
if (precision >= 0) {
throw new TIllegalFormatPrecisionException(precision);
}
out.append(System.lineSeparator());
continue;
}
configureFormat();
formatValue(specifier);
}
}
private void formatValue(char specifier) throws IOException {
switch (specifier) {
case 'b':
formatBoolean(specifier, false);
break;
case 'B':
formatBoolean(specifier, true);
break;
case 'h':
formatHex(specifier, false);
break;
case 'H':
formatHex(specifier, true);
break;
case 's':
formatString(specifier, false);
break;
case 'S':
formatString(specifier, true);
break;
case 'c':
formatChar(specifier, false);
break;
case 'C':
formatChar(specifier, true);
break;
case 'd':
formatDecimalInt(specifier, false);
break;
case 'D':
formatDecimalInt(specifier, true);
break;
case 'o':
formatRadixInt(specifier, 3, false);
break;
case 'O':
formatRadixInt(specifier, 3, true);
break;
case 'x':
formatRadixInt(specifier, 4, false);
break;
case 'X':
formatRadixInt(specifier, 4, true);
break;
case 'f':
formatFloat(specifier, false);
break;
case '%':
out.append("%");
break;
default:
throw new UnknownFormatConversionException(String.valueOf(specifier));
}
}
private void formatFloat(char specifier, boolean upperCase) throws IOException {
verifyFlags(specifier, MASK_FOR_INT_DECIMAL_FORMAT);
verifyFloatFlags();
if (precision == -1) {
precision = 6;
}
Object arg = args[argumentIndex];
boolean negative;
if (arg instanceof Double) {
negative = (Double) arg < 0;
} else if (arg instanceof Float) {
negative = (Float) arg < 0;
} else if (arg instanceof BigDecimal) {
negative = ((BigDecimal) arg).signum() < 0;
} else {
throw new IllegalFormatConversionException(specifier, arg == null ? null : arg.getClass());
}
TDecimalFormat format = new TDecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
if (width != -1) {
int decimalSize = predictDecimalSize(negative, format);
format.setMaximumIntegerDigits(decimalSize);
if ((flags & TFormattableFlags.ZERO_PADDED) != 0) {
format.setMinimumIntegerDigits(decimalSize);
}
}
format.setMaximumFractionDigits(precision);
format.setMinimumFractionDigits(precision);
format.setGroupingUsed((flags & TFormattableFlags.GROUPING_SEPARATOR) != 0);
if ((flags & TFormattableFlags.PARENTHESIZED_NEGATIVE) != 0) {
format.setNegativePrefix("(");
format.setNegativeSuffix(")");
}
if ((flags & TFormattableFlags.SIGNED) != 0) {
format.setPositivePrefix("+"); // DecimalFormatSymbols has no plus sign
} else if ((flags & TFormattableFlags.LEADING_SPACE) != 0) {
format.setPositivePrefix(" ");
}
String str = format.format(arg);
precision = -1; // prevent formatGivenString from trimming
formatGivenString(upperCase, str);
}
private int predictDecimalSize(boolean negative, TDecimalFormat format) {
int decimalSize = width;
if (precision > 0) {
decimalSize -= precision + 1; // width also includes decimal places. Subtract them!
}
// signs take up space as well. Also subtract them!
if (negative) {
if ((flags & TFormattableFlags.PARENTHESIZED_NEGATIVE) != 0) {
decimalSize -= 2;
} else {
decimalSize--;
}
} else if ((flags & (TFormattableFlags.SIGNED | TFormattableFlags.LEADING_SPACE)) != 0) {
decimalSize--;
}
// the grouping separator also takes up space. You know the drill.
if ((flags & TFormattableFlags.GROUPING_SEPARATOR) != 0) {
decimalSize -= decimalSize / (format.getGroupingSize() + 1);
}
return decimalSize;
}
private void verifyFloatFlags() {
if ((flags & TFormattableFlags.SIGNED) != 0 && (flags & TFormattableFlags.LEADING_SPACE) != 0) {
throw new TIllegalFormatFlagsException("+ ");
}
if ((flags & TFormattableFlags.ZERO_PADDED) != 0 && (flags & TFormattableFlags.LEFT_JUSTIFY) != 0) {
throw new TIllegalFormatFlagsException("0-");
}
if ((flags & TFormattableFlags.LEFT_JUSTIFY) != 0 && width < 0) {
throw new TMissingFormatWidthException(format.substring(formatSpecifierStart, index));
}
}
private void formatBoolean(char specifier, boolean upperCase) throws IOException {
verifyFlagsForGeneralFormat(specifier);
Object arg = args[argumentIndex];
String s = Boolean.toString(arg instanceof Boolean ? (Boolean) arg : arg != null);
formatGivenString(upperCase, s);
}
private void formatHex(char specifier, boolean upperCase) throws IOException {
verifyFlagsForGeneralFormat(specifier);
Object arg = args[argumentIndex];
String s = arg != null ? Integer.toHexString(arg.hashCode()) : "null";
formatGivenString(upperCase, s);
}
private void formatString(char specifier, boolean upperCase) throws IOException {
verifyFlagsForGeneralFormat(specifier);
Object arg = args[argumentIndex];
if (arg instanceof TFormattable) {
int flagsToPass = flags & 7;
if (upperCase) {
flagsToPass |= TFormattableFlags.UPPERCASE;
}
((TFormattable) arg).formatTo(formatter, flagsToPass, width, precision);
} else {
formatGivenString(upperCase, String.valueOf(arg));
}
}
private void formatChar(char specifier, boolean upperCase) throws IOException {
verifyFlags(specifier, MASK_FOR_CHAR_FORMAT);
Object arg = args[argumentIndex];
if (precision >= 0) {
throw new TIllegalFormatPrecisionException(precision);
}
int c;
if (arg instanceof Character) {
c = (Character) arg;
} else if (arg instanceof Byte) {
c = (char) (byte) arg;
} else if (arg instanceof Short) {
c = (char) (short) arg;
} else if (arg instanceof Integer) {
c = (int) arg;
if (!Character.isValidCodePoint(c)) {
throw new TIllegalFormatCodePointException(c);
}
} else if (arg == null) {
formatGivenString(upperCase, "null");
return;
} else {
throw new IllegalFormatConversionException(specifier, arg.getClass());
}
formatGivenString(upperCase, new String(Character.toChars(c)));
}
private void formatDecimalInt(char specifier, boolean upperCase) throws IOException {
verifyFlags(specifier, MASK_FOR_INT_DECIMAL_FORMAT);
verifyIntFlags();
String str;
Object arg = args[argumentIndex];
boolean negative;
if (arg instanceof Long) {
long value = (Long) arg;
// Not Math.abs: it leaves MIN_VALUE negative, and the sign would print twice.
str = Long.toString(value);
negative = value < 0;
} else if (arg instanceof Integer || arg instanceof Byte || arg instanceof Short) {
int value = ((Number) arg).intValue();
str = Integer.toString(value);
negative = value < 0;
} else {
throw new IllegalFormatConversionException(specifier, arg != null ? arg.getClass() : null);
}
if (negative) {
str = str.substring(1);
}
int additionalSymbols = 0;
StringBuilder sb = new StringBuilder();
if (negative) {
if ((flags & TFormattableFlags.PARENTHESIZED_NEGATIVE) != 0) {
sb.append('(');
additionalSymbols += 2;
} else {
sb.append('-');
additionalSymbols++;
}
} else {
if ((flags & TFormattableFlags.SIGNED) != 0) {
sb.append('+');
additionalSymbols++;
} else if ((flags & TFormattableFlags.LEADING_SPACE) != 0) {
sb.append(' ');
additionalSymbols++;
}
}
StringBuilder valueSb = new StringBuilder();
if ((flags & TFormattableFlags.GROUPING_SEPARATOR) != 0) {
char separator = new DecimalFormatSymbols(locale).getGroupingSeparator();
int size = ((DecimalFormat) NumberFormat.getNumberInstance(locale)).getGroupingSize();
int offset = str.length() % size;
if (offset == 0) {
offset = size;
}
int prev = 0;
for (int i = offset; i < str.length(); i += size) {
valueSb.append(str.substring(prev, i));
valueSb.append(separator);
prev = i;
}
valueSb.append(str.substring(prev));
} else {
valueSb.append(str);
}
if ((flags & TFormattableFlags.ZERO_PADDED) != 0) {
int actual = valueSb.length() + additionalSymbols;
for (int i = actual; i < width; ++i) {
sb.append(Character.forDigit(0, 10));
}
}
sb.append(valueSb);
if (negative && (flags & TFormattableFlags.PARENTHESIZED_NEGATIVE) != 0) {
sb.append(')');
}
formatGivenString(upperCase, sb.toString());
}
private void formatRadixInt(char specifier, int radixLog2, boolean upperCase) throws IOException {
verifyFlags(specifier, MASK_FOR_INT_RADIX_FORMAT);
verifyIntFlags();
String str;
Object arg = args[argumentIndex];
if (arg instanceof Long) {
str = IntegerUtil.toUnsignedLogRadixString((Long) arg, radixLog2);
} else if (arg instanceof Integer) {
str = IntegerUtil.toUnsignedLogRadixString((Integer) arg, radixLog2);
} else if (arg instanceof Short) {
str = IntegerUtil.toUnsignedLogRadixString((Short) arg & 0xFFFF, radixLog2);
} else if (arg instanceof Byte) {
str = IntegerUtil.toUnsignedLogRadixString((Byte) arg & 0xFF, radixLog2);
} else {
throw new IllegalFormatConversionException(specifier, arg != null ? arg.getClass() : null);
}
StringBuilder sb = new StringBuilder();
if ((flags & TFormattableFlags.ALTERNATE) != 0) {
String prefix = radixLog2 == 4 ? "0x" : "0";
str = prefix + str;
}
if ((flags & TFormattableFlags.ZERO_PADDED) != 0) {
for (int i = str.length(); i < width; ++i) {
sb.append(Character.forDigit(0, 10));
}
}
sb.append(str);
formatGivenString(upperCase, sb.toString());
}
private void verifyIntFlags() {
if ((flags & TFormattableFlags.SIGNED) != 0 && (flags & TFormattableFlags.LEADING_SPACE) != 0) {
throw new TIllegalFormatFlagsException("+ ");
}
if ((flags & TFormattableFlags.ZERO_PADDED) != 0 && (flags & TFormattableFlags.LEFT_JUSTIFY) != 0) {
throw new TIllegalFormatFlagsException("0-");
}
if (precision >= 0) {
throw new TIllegalFormatPrecisionException(precision);
}
if ((flags & TFormattableFlags.LEFT_JUSTIFY) != 0 && width < 0) {
throw new TMissingFormatWidthException(format.substring(formatSpecifierStart, index));
}
}
private void formatGivenString(boolean upperCase, String str) throws IOException {
if (precision > 0 && precision < str.length()) {
str = str.substring(0, precision);
}
if (upperCase) {
str = str.toUpperCase();
}
if ((flags & TFormattableFlags.LEFT_JUSTIFY) != 0) {
out.append(str);
mayBeAppendSpaces(str);
} else {
mayBeAppendSpaces(str);
out.append(str);
}
}
private void verifyFlagsForGeneralFormat(char conversion) {
verifyFlags(conversion, MASK_FOR_GENERAL_FORMAT);
}
private void verifyFlags(char conversion, int mask) {
if ((flags | mask) != mask) {
throw new FormatFlagsConversionMismatchException(flagsToString(flags & ~mask), conversion);
}
}
private String flagsToString(int flags) {
int flagIndex = Integer.numberOfTrailingZeros(flags);
return String.valueOf(FORMAT_FLAGS.charAt(flagIndex));
}
private void mayBeAppendSpaces(String str) throws IOException {
if (width > str.length()) {
int diff = width - str.length();
StringBuilder sb = new StringBuilder(diff);
for (int i = 0; i < diff; ++i) {
sb.append(' ');
}
out.append(sb);
}
}
private void configureFormat() {
if ((flags & TFormattableFlags.PREVIOUS_ARGUMENT) != 0) {
argumentIndex = Math.max(0, previousArgumentIndex);
}
if (argumentIndex == -1) {
argumentIndex = defaultArgumentIndex++;
}
previousArgumentIndex = argumentIndex;
}
private char parseFormatSpecifier() {
flags = 0;
argumentIndex = -1;
width = -1;
precision = -1;
char c = format.charAt(index);
if (c != '0' && isDigit(c)) {
int n = readInt();
if (index < format.length() && format.charAt(index) == '$') {
index++;
argumentIndex = n - 1;
} else {
width = n;
}
}
parseFlags();
if (width < 0 && index < format.length() && isDigit(format.charAt(index))) {
width = readInt();
}
if (index < format.length() && format.charAt(index) == '.') {
index++;
if (index >= format.length() || !isDigit(format.charAt(index))) {
throw new UnknownFormatConversionException(String.valueOf(format.charAt(index - 1)));
}
precision = readInt();
}
if (index >= format.length()) {
throw new UnknownFormatConversionException(String.valueOf(format.charAt(format.length() - 1)));
}
return format.charAt(index++);
}
private void parseFlags() {
while (index < format.length()) {
char c = format.charAt(index);
int flag;
switch (c) {
case '-':
flag = TFormattableFlags.LEFT_JUSTIFY;
break;
case '#':
flag = TFormattableFlags.ALTERNATE;
break;
case '+':
flag = TFormattableFlags.SIGNED;
break;
case ' ':
flag = TFormattableFlags.LEADING_SPACE;
break;
case '0':
flag = TFormattableFlags.ZERO_PADDED;
break;
case ',':
flag = TFormattableFlags.GROUPING_SEPARATOR;
break;
case '(':
flag = TFormattableFlags.PARENTHESIZED_NEGATIVE;
break;
case '<':
flag = TFormattableFlags.PREVIOUS_ARGUMENT;
break;
default:
return;
}
if ((flags & flag) != 0) {
throw new DuplicateFormatFlagsException(String.valueOf(c));
}
flags |= flag;
index++;
}
}
private int readInt() {
int result = 0;
while (index < format.length() && isDigit(format.charAt(index))) {
result = result * 10 + (format.charAt(index++) - '0');
}
return result;
}
private static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
}
}
@@ -0,0 +1,790 @@
/*
* Copyright 2020 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.
*
* Modified for Incari (tools/teavm-patches/README.md): an empty map made from entries (Map.of()
* through NEtriesMap, Map.copyOf of an empty map) took each key's hash modulo zero in get(), which
* WebAssembly traps on ("remainder by zero"); get() and its entry set's contains() now answer
* first, as containsKey() already did.
*
* Modified for Incari: the sets and maps of more than two elements (Set.of, Set.copyOf, Map.of,
* Map.copyOf) weren't hashed for lookups. Their tables had a slot per element and no free slot to
* end a search, and Set.copyOf's packed its elements together, so contains(), containsKey() and
* get() compared every element whenever the one asked for was missing. The game's tag checks
* (Holder.is(TagKey), against a Set.copyOf of the holder's tags) are mostly misses. Elements now
* stay packed in insertion order for iteration, and a table of their indices, at least twice as
* large, is probed from the hash until a free slot (HashSlots).
*/
package org.teavm.classlib.java.util;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.RandomAccess;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
public final class TTemplateCollections {
private TTemplateCollections() {
}
public static class ImmutableArrayList<T> extends AbstractImmutableList<T> implements RandomAccess {
private final T[] list;
@SafeVarargs
public ImmutableArrayList(T... list) {
this.list = list;
}
@SuppressWarnings("unchecked")
ImmutableArrayList(TCollection<? extends T> collection) {
T[] list = (T[]) new Object[collection.size()];
TIterator<? extends T> iter = collection.iterator();
int index = 0;
while (iter.hasNext()) {
T element = iter.next();
if (element == null) {
throw new NullPointerException();
}
list[index++] = element;
}
this.list = list;
}
@Override
public T get(int index) {
return list[index];
}
@Override
public int size() {
return list.length;
}
}
static class SingleElementList<T> extends AbstractImmutableList<T> implements RandomAccess {
private T value;
SingleElementList(T value) {
this.value = value;
}
@Override
public int size() {
return 1;
}
@Override
public T get(int index) {
if (index == 0) {
return value;
}
throw new IndexOutOfBoundsException();
}
@Override
public void sort(TComparator<? super T> c) {
}
}
static class TwoElementsList<T> extends AbstractImmutableList<T> implements RandomAccess {
private T first;
private T second;
TwoElementsList(T first, T second) {
this.first = first;
this.second = second;
}
@Override
public int size() {
return 2;
}
@Override
public T get(int index) {
if (index == 0) {
return first;
} else if (index == 1) {
return second;
}
throw new IndexOutOfBoundsException();
}
}
static class SingleElementSet<T> extends AbstractImmutableSet<T> {
private T element;
SingleElementSet(T element) {
this.element = element;
}
@Override
public TIterator<T> iterator() {
return new TIterator<>() {
private boolean more = true;
@Override
public boolean hasNext() {
return more;
}
@Override
public T next() {
if (!more) {
throw new NoSuchElementException();
}
more = false;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return 1;
}
@Override
public boolean contains(Object o) {
return Objects.equals(o, element);
}
}
static class TwoElementsSet<T> extends AbstractImmutableSet<T> {
private T first;
private T second;
TwoElementsSet(T first, T second) {
this.first = first;
this.second = second;
}
@Override
public boolean contains(Object o) {
return Objects.equals(o, first) || Objects.equals(o, second);
}
@Override
public TIterator<T> iterator() {
return new TIterator<>() {
private int index;
@Override
public boolean hasNext() {
return index < 2;
}
@Override
public T next() {
switch (index++) {
case 0:
return first;
case 1:
return second;
default:
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return 2;
}
}
static class NElementSet<T> extends AbstractImmutableSet<T> {
private T[] data;
private int[] slots;
/**
* Throws an exception on duplicate elements.
*/
@SafeVarargs
NElementSet(T... data) {
T[] elements = data.clone();
int[] table = HashSlots.create(elements.length);
for (int i = 0; i < elements.length; i++) {
T element = Objects.requireNonNull(elements[i]);
if (HashSlots.find(table, elements, element) >= 0) {
throw new IllegalArgumentException();
}
HashSlots.add(table, element, i);
}
this.data = elements;
this.slots = table;
}
/**
* Duplicate elements will be ignored (does NOT throw an exception).
*/
@SuppressWarnings("unchecked")
NElementSet(TCollection<T> collection) {
T[] source = (T[]) collection.toArray();
T[] elements = (T[]) new Object[source.length];
int[] table = HashSlots.create(source.length);
int count = 0;
for (T element : source) {
Objects.requireNonNull(element);
if (HashSlots.find(table, elements, element) >= 0) {
continue;
}
elements[count] = element;
HashSlots.add(table, element, count);
count++;
}
this.data = count == elements.length ? elements : Arrays.copyOf(elements, count);
this.slots = table;
}
@Override
public TIterator<T> iterator() {
return new TIterator<>() {
private int index;
@Override
public boolean hasNext() {
return index < data.length;
}
@Override
public T next() {
if (index >= data.length) {
throw new NoSuchElementException();
}
return data[index++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public int size() {
return data.length;
}
@Override
public boolean contains(Object o) {
if (data.length == 0 || o == null) {
return false;
}
return HashSlots.find(slots, data, o) >= 0;
}
}
static class SingleEntryMap<K, V> extends AbstractImmutableMap<K, V> {
private Entry<K, V> entry;
private AbstractImmutableSet<Entry<K, V>> entrySet;
private AbstractImmutableSet<K> keySet;
private AbstractImmutableList<V> values;
SingleEntryMap(K key, V value) {
this.entry = new ImmutableEntry<>(Objects.requireNonNull(key), Objects.requireNonNull(value));
}
@Override
public TSet<Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new SingleElementSet<>(entry);
}
return entrySet;
}
@Override
public V get(Object key) {
return entry.getKey().equals(key) ? entry.getValue() : null;
}
@Override
public int size() {
return 1;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsValue(Object value) {
return entry.getValue().equals(value);
}
@Override
public boolean containsKey(Object key) {
return entry.getKey().equals(key);
}
@Override
public TSet<K> keySet() {
if (keySet == null) {
keySet = new SingleElementSet<>(entry.getKey());
}
return keySet;
}
@Override
public TCollection<V> values() {
if (values == null) {
values = new SingleElementList<>(entry.getValue());
}
return values;
}
}
static class TwoEntriesMap<K, V> extends AbstractImmutableMap<K, V> {
private Entry<K, V> first;
private Entry<K, V> second;
private AbstractImmutableSet<Entry<K, V>> entrySet;
private AbstractImmutableSet<K> keySet;
private AbstractImmutableList<V> values;
TwoEntriesMap(K k1, V v1, K k2, V v2) {
this.first = new ImmutableEntry<>(Objects.requireNonNull(k1), Objects.requireNonNull(v1));
this.second = new ImmutableEntry<>(Objects.requireNonNull(k2), Objects.requireNonNull(v2));
if (Objects.equals(k1, k2)) {
throw new IllegalArgumentException();
}
}
@Override
public TSet<Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new TwoElementsSet<>(first, second);
}
return entrySet;
}
@Override
public V get(Object key) {
return first.getKey().equals(key)
? first.getValue()
: second.getKey().equals(key) ? second.getValue() : null;
}
@Override
public int size() {
return 2;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsValue(Object value) {
return first.getValue().equals(value) || second.getValue().equals(value);
}
@Override
public boolean containsKey(Object key) {
return first.getKey().equals(key) || second.getKey().equals(key);
}
@Override
public TSet<K> keySet() {
if (keySet == null) {
keySet = new TwoElementsSet<>(first.getKey(), second.getKey());
}
return keySet;
}
@Override
public TCollection<V> values() {
if (values == null) {
values = new TwoElementsList<>(first.getValue(), second.getValue());
}
return values;
}
}
static class NEtriesMap<K, V> extends AbstractImmutableMap<K, V> {
private Entry<K, V>[] data;
private Object[] keys;
private int[] slots;
private AbstractImmutableSet<Entry<K, V>> entrySet;
@SafeVarargs
NEtriesMap(Entry<K, V>... data) {
this.data = toEntryArray(data);
}
@SuppressWarnings("unchecked")
NEtriesMap(TMap<? extends K, ? extends V> map) {
this.data = toEntryArray(map.entrySet().toArray(new TMap.Entry[0]));
}
/** Copies the entries in order and hashes their keys; throws on a duplicate key. */
@SuppressWarnings("unchecked")
private Entry<K, V>[] toEntryArray(Entry<K, V>[] entries) {
Entry<K, V>[] table = new Entry[entries.length];
Object[] entryKeys = new Object[entries.length];
int[] entrySlots = HashSlots.create(entries.length);
for (int i = 0; i < entries.length; i++) {
Entry<K, V> entry = entries[i];
Objects.requireNonNull(entry.getKey());
Objects.requireNonNull(entry.getValue());
if (HashSlots.find(entrySlots, entryKeys, entry.getKey()) >= 0) {
throw new IllegalArgumentException();
}
table[i] = new ImmutableEntry<>(entry.getKey(), entry.getValue());
entryKeys[i] = entry.getKey();
HashSlots.add(entrySlots, entry.getKey(), i);
}
keys = entryKeys;
slots = entrySlots;
return table;
}
@Override
public int size() {
return data.length;
}
@Override
public boolean isEmpty() {
return data.length == 0;
}
@Override
public boolean containsValue(Object value) {
if (value == null) {
return false;
}
for (Entry<K, V> entry : data) {
if (entry.getValue().equals(value)) {
return true;
}
}
return false;
}
@Override
public boolean containsKey(Object key) {
if (key == null || data.length == 0) {
return false;
}
return HashSlots.find(slots, keys, key) >= 0;
}
@Override
public V get(Object key) {
if (key == null || data.length == 0) {
return null;
}
int index = HashSlots.find(slots, keys, key);
return index >= 0 ? data[index].getValue() : null;
}
@Override
public TSet<Entry<K, V>> entrySet() {
if (entrySet == null) {
entrySet = new AbstractImmutableSet<>() {
@Override
public int size() {
return data.length;
}
@Override
public TIterator<Entry<K, V>> iterator() {
return new TIterator<>() {
int index;
@Override
public boolean hasNext() {
return index < data.length;
}
@Override
public Entry<K, V> next() {
if (index == data.length) {
throw new NoSuchElementException();
}
return data[index++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry<?, ?> e)) {
return false;
}
Object key = e.getKey();
if (key == null || data.length == 0) {
return false;
}
int index = HashSlots.find(slots, keys, key);
if (index >= 0) {
return data[index].getValue().equals(e.getValue());
}
return false;
}
};
}
return entrySet;
}
}
/**
* An open-addressing table of element indices (plus one; zero is a free slot), at least twice
* as large as the elements, so every probe ends at a free slot.
*/
static final class HashSlots {
private HashSlots() {
}
static int[] create(int elements) {
int size = 2;
while (size < elements * 2) {
size <<= 1;
}
return new int[size];
}
private static int start(Object element, int[] table) {
int hash = element.hashCode();
return (hash ^ (hash >>> 16)) & (table.length - 1);
}
/** The index of the element equal to {@code element}, or -1. */
static int find(int[] table, Object[] elements, Object element) {
int mask = table.length - 1;
for (int slot = start(element, table);; slot = (slot + 1) & mask) {
int entry = table[slot];
if (entry == 0) {
return -1;
}
Object candidate = elements[entry - 1];
if (candidate == element || candidate.equals(element)) {
return entry - 1;
}
}
}
/** Adds the element at {@code index}, which {@link #find} didn't find. */
static void add(int[] table, Object element, int index) {
int mask = table.length - 1;
int slot = start(element, table);
while (table[slot] != 0) {
slot = (slot + 1) & mask;
}
table[slot] = index + 1;
}
}
static abstract class AbstractImmutableList<T> extends TAbstractList<T> implements RandomAccess {
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public T remove(int index) {
throw new UnsupportedOperationException();
}
@Override
protected void removeRange(int start, int end) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(TCollection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(TCollection<?> c) {
throw new UnsupportedOperationException();
}
}
static abstract class AbstractImmutableSet<T> extends TAbstractSet<T> {
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(TCollection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(TCollection<?> c) {
throw new UnsupportedOperationException();
}
}
static abstract class AbstractImmutableMap<K, V> extends TAbstractMap<K, V> {
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(TMap<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean replace(K key, V value, V newValue) {
throw new UnsupportedOperationException();
}
@Override
public V replace(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V putIfAbsent(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
throw new UnsupportedOperationException();
}
}
static class ImmutableEntry<K, V> implements TMap.Entry<K, V>, Cloneable {
K key;
V value;
ImmutableEntry(K theKey, V theValue) {
key = theKey;
value = theValue;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof TMap.Entry<?, ?> entry) {
return TObjects.equals(key, entry.getKey()) && TObjects.equals(value, entry.getValue());
}
return false;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public int hashCode() {
return TObjects.hashCode(key) ^ TObjects.hashCode(value);
}
@Override
public V setValue(V object) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return key + "=" + value;
}
}
}
@@ -0,0 +1,361 @@
/*
* Copyright 2017 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.
*
* Modified for Incari (tools/teavm-patches/README.md): toArray() filled an array of the stream's
* estimated size and overflowed it when the estimate was short; the array now grows.
*/
package org.teavm.classlib.java.util.stream.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import org.teavm.classlib.java.util.stream.TCollector;
import org.teavm.classlib.java.util.stream.TDoubleStream;
import org.teavm.classlib.java.util.stream.TIntStream;
import org.teavm.classlib.java.util.stream.TLongStream;
import org.teavm.classlib.java.util.stream.TStream;
public abstract class TSimpleStreamImpl<T> implements TStream<T> {
@Override
public TStream<T> filter(Predicate<? super T> predicate) {
return new TFilteringStreamImpl<>(this, predicate);
}
@Override
public <R> TStream<R> map(Function<? super T, ? extends R> mapper) {
return new TMappingStreamImpl<>(this, mapper);
}
@Override
public TIntStream mapToInt(ToIntFunction<? super T> mapper) {
return new TMappingToIntStreamImpl<>(this, mapper);
}
@Override
public TLongStream mapToLong(ToLongFunction<? super T> mapper) {
return new TMappingToLongStreamImpl<>(this, mapper);
}
@Override
public TDoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
return new TMappingToDoubleStreamImpl<>(this, mapper);
}
@Override
public <R> TStream<R> flatMap(Function<? super T, ? extends TStream<? extends R>> mapper) {
return new TFlatMappingStreamImpl<>(this, mapper);
}
@Override
public TIntStream flatMapToInt(Function<? super T, ? extends TIntStream> mapper) {
return new TFlatMappingToIntStreamImpl<>(this, mapper);
}
@Override
public TLongStream flatMapToLong(Function<? super T, ? extends TLongStream> mapper) {
return new TFlatMappingToLongStreamImpl<>(this, mapper);
}
@Override
public TDoubleStream flatMapToDouble(Function<? super T, ? extends TDoubleStream> mapper) {
return new TFlatMappingToDoubleStreamImpl<>(this, mapper);
}
@Override
public TStream<T> distinct() {
return new TDistinctStreamImpl<>(this);
}
@Override
@SuppressWarnings("unchecked")
public TStream<T> sorted() {
return new TSortedStreamImpl<>(this, (a, b) -> ((Comparable<Object>) a).compareTo(b));
}
@Override
public TStream<T> sorted(Comparator<? super T> comparator) {
return new TSortedStreamImpl<>(this, comparator);
}
@Override
public TStream<T> peek(Consumer<? super T> action) {
return new TPeekingStreamImpl<>(this, action);
}
@Override
public TStream<T> limit(long maxSize) {
return new TLimitingStreamImpl<>(this, (int) maxSize);
}
@Override
public TStream<T> takeWhile(Predicate<? super T> predicate) {
return new TTakeWhileStream<>(this, predicate);
}
@Override
public TStream<T> dropWhile(Predicate<? super T> predicate) {
return new TDropWhileStream<>(this, predicate);
}
@Override
public TStream<T> skip(long n) {
return new TSkippingStreamImpl<>(this, (int) n);
}
@Override
public void forEach(Consumer<? super T> action) {
forEachOrdered(action);
}
@Override
public void forEachOrdered(Consumer<? super T> action) {
while (true) {
boolean hasMore = next(e -> {
action.accept(e);
return true;
});
if (!hasMore) {
return;
}
}
}
@Override
public Object[] toArray() {
return toArray(Object[]::new);
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(IntFunction<A[]> generator) {
int estimatedSize = estimateSize();
if (estimatedSize < 0) {
List<T> list = new ArrayList<>();
while (next(list::add)) {
// go on
}
A[] array = generator.apply(list.size());
for (int i = 0; i < array.length; ++i) {
array[i] = (A) list.get(i);
}
return array;
} else {
A[] array = generator.apply(estimatedSize);
ArrayFillingConsumer<A, T> consumer = new ArrayFillingConsumer<>(array);
while (next(consumer)) {
// go on
}
array = consumer.array; // Incari: the consumer may have grown it.
if (consumer.index < array.length) {
array = Arrays.copyOf(array, consumer.index);
}
return array;
}
}
@Override
public T reduce(T identity, BinaryOperator<T> accumulator) {
TReducingConsumer<T> consumer = new TReducingConsumer<>(accumulator, identity, true);
while (next(consumer)) {
// go on
}
return consumer.result;
}
@Override
public Optional<T> reduce(BinaryOperator<T> accumulator) {
TReducingConsumer<T> consumer = new TReducingConsumer<>(accumulator, null, false);
while (next(consumer)) {
// go on
}
return Optional.ofNullable(consumer.result);
}
@Override
public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) {
TReducingConsumer2<T, U> consumer = new TReducingConsumer2<>(accumulator, identity);
while (next(consumer)) {
// go on
}
return consumer.result;
}
@Override
public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) {
R collection = supplier.get();
while (true) {
boolean hasMore = next(e -> {
accumulator.accept(collection, e);
return true;
});
if (!hasMore) {
break;
}
}
return collection;
}
@Override
public <R, A> R collect(TCollector<? super T, A, R> collector) {
A collection = collector.supplier().get();
BiConsumer<A, ? super T> accumulator = collector.accumulator();
while (true) {
boolean hasMore = next(e -> {
accumulator.accept(collection, e);
return true;
});
if (!hasMore) {
break;
}
}
return collector.finisher().apply(collection);
}
@Override
public Optional<T> min(Comparator<? super T> comparator) {
return reduce((a, b) -> comparator.compare(a, b) <= 0 ? a : b);
}
@Override
public Optional<T> max(Comparator<? super T> comparator) {
return reduce((a, b) -> comparator.compare(a, b) >= 0 ? a : b);
}
@Override
public long count() {
TCountingConsumer<T> consumer = new TCountingConsumer<>();
while (next(consumer)) {
// go on
}
return consumer.count;
}
@Override
public boolean anyMatch(Predicate<? super T> predicate) {
TAnyMatchConsumer<T> consumer = new TAnyMatchConsumer<>(predicate);
while (!consumer.matched && next(consumer)) {
// go on
}
return consumer.matched;
}
@Override
public boolean allMatch(Predicate<? super T> predicate) {
TAllMatchConsumer<T> consumer = new TAllMatchConsumer<>(predicate);
while (consumer.matched && next(consumer)) {
// go on
}
return consumer.matched;
}
@Override
public boolean noneMatch(Predicate<? super T> predicate) {
return !anyMatch(predicate);
}
@Override
public Optional<T> findFirst() {
TFindFirstConsumer<T> consumer = new TFindFirstConsumer<>();
while (consumer.result == null && next(consumer)) {
// go on
}
return Optional.ofNullable(consumer.result);
}
@Override
public Optional<T> findAny() {
return findFirst();
}
@Override
public Iterator<T> iterator() {
return new TSimpleStreamIterator<>(this);
}
@Override
public Spliterator<T> spliterator() {
return new TSimpleStreamSpliterator<>(this);
}
@Override
public boolean isParallel() {
return false;
}
@Override
public TStream<T> sequential() {
return this;
}
@Override
public TStream<T> parallel() {
return this;
}
@Override
public TStream<T> unordered() {
return this;
}
@Override
public TStream<T> onClose(Runnable closeHandler) {
return new TCloseHandlingStream<>(this, closeHandler);
}
@Override
public void close() {
}
protected int estimateSize() {
return -1;
}
public abstract boolean next(Predicate<? super T> consumer);
static class ArrayFillingConsumer<A, T> implements Predicate<T> {
A[] array;
int index;
ArrayFillingConsumer(A[] array) {
this.array = array;
}
@Override
@SuppressWarnings("unchecked")
public boolean test(T t) {
if (index == array.length) {
// Incari: an estimate is only an estimate; grow rather than overflow.
array = Arrays.copyOf(array, Math.max(8, array.length * 2));
}
array[index++] = (A) t;
return true;
}
}
}
@@ -0,0 +1,58 @@
/*
* Copyright 2017 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.
*
* Modified for Incari (tools/teavm-patches/README.md): estimateSize() asked the source stream,
* which the constructor has already drained; a spliterator that counts what's left (fastutil's)
* then said 0, and toArray() behind a limit() overflowed a zero-length array.
*/
package org.teavm.classlib.java.util.stream.impl;
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.Predicate;
public class TSortedStreamImpl<T> extends TSimpleStreamImpl<T> {
private TSimpleStreamImpl<T> sourceStream;
private T[] array;
private int index;
@SuppressWarnings("unchecked")
public TSortedStreamImpl(TSimpleStreamImpl<T> sourceStream, Comparator<? super T> comparator) {
this.sourceStream = sourceStream;
array = (T[]) sourceStream.toArray(Object[]::new);
Arrays.sort(array, comparator);
}
@Override
public boolean next(Predicate<? super T> consumer) {
while (index < array.length) {
if (!consumer.test(array[index++])) {
break;
}
}
return index < array.length;
}
@Override
protected int estimateSize() {
// Incari: the elements are all in the array; was sourceStream.estimateSize().
return array.length - index;
}
@Override
public void close() {
sourceStream.close();
}
}
@@ -0,0 +1,351 @@
/*
* Copyright 2017 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.
*
* Modified for Incari (tools/teavm-patches/README.md): a deflated entry's stream ends with one
* extra zero byte after its compressed data, as the JDK's ZipFile gives its raw inflater. Without
* it the inflater could still ask for input at the end of the data, and InflaterInputStream threw
* EOFException for an entry that was whole.
*/
package org.teavm.classlib.java.util.zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.teavm.classlib.java.io.TCloseable;
import org.teavm.classlib.java.util.zip.TZipEntry.LittleEndianReader;
public class TZipFile implements TZipConstants, TCloseable {
public static final int OPEN_READ = 1;
public static final int OPEN_DELETE = 4;
private final String fileName;
private File fileToDeleteOnClose;
private RandomAccessFile mRaf;
private final LittleEndianReader ler = new LittleEndianReader();
private final LinkedHashMap<String, TZipEntry> mEntries = new LinkedHashMap<>();
public TZipFile(File file) throws TZipException, IOException {
this(file, OPEN_READ);
}
public TZipFile(File file, int mode) throws IOException {
fileName = file.getPath();
if (mode != OPEN_READ && mode != (OPEN_READ | OPEN_DELETE)) {
throw new IllegalArgumentException();
}
if ((mode & OPEN_DELETE) != 0) {
fileToDeleteOnClose = file; // file.deleteOnExit();
} else {
fileToDeleteOnClose = null;
}
mRaf = new RandomAccessFile(fileName, "r");
readCentralDir();
}
public TZipFile(String name) throws IOException {
this(new File(name), OPEN_READ);
}
@Override
public void close() throws IOException {
RandomAccessFile raf = mRaf;
if (raf != null) {
mRaf = null;
raf.close();
if (fileToDeleteOnClose != null) {
new File(fileName).delete();
// fileToDeleteOnClose.delete();
fileToDeleteOnClose = null;
}
}
}
private void checkNotClosed() {
if (mRaf == null) {
throw new IllegalStateException();
}
}
public Enumeration<? extends TZipEntry> entries() {
checkNotClosed();
final Iterator<TZipEntry> iterator = mEntries.values().iterator();
return new Enumeration<TZipEntry>() {
@Override
public boolean hasMoreElements() {
checkNotClosed();
return iterator.hasNext();
}
@Override
public TZipEntry nextElement() {
checkNotClosed();
return iterator.next();
}
};
}
public TZipEntry getEntry(String entryName) {
checkNotClosed();
if (entryName == null) {
throw new NullPointerException();
}
TZipEntry ze = mEntries.get(entryName);
if (ze == null) {
ze = mEntries.get(entryName + "/");
}
return ze;
}
public InputStream getInputStream(TZipEntry entry) throws IOException {
/*
* Make sure this TZipEntry is in this Zip file. We run it through
* the name lookup.
*/
entry = getEntry(entry.getName());
if (entry == null) {
return null;
}
/*
* Create a TZipInputStream at the right part of the file.
*/
RandomAccessFile raf = mRaf;
// We don't know the entry data's start position. All we have is the
// position of the entry's local header. At position 28 we find the
// length of the extra data. In some cases this length differs from
// the one coming in the central header.
RAFStream rafstrm = new RAFStream(raf, entry.mLocalHeaderRelOffset + 28);
int localExtraLenOrWhatever = ler.readShortLE(rafstrm);
// Skip the name and this "extra" data or whatever it is:
rafstrm.skip(entry.nameLen + localExtraLenOrWhatever);
rafstrm.mLength = rafstrm.mOffset + entry.compressedSize;
if (entry.compressionMethod == java.util.zip.ZipEntry.DEFLATED) {
rafstrm.dummyByte = true;
int bufSize = Math.max(1024, (int) Math.min(entry.getSize(), 65535L));
return new ZipInflaterInputStream(rafstrm, new TInflater(true), bufSize, entry);
} else {
return rafstrm;
}
}
public String getName() {
return fileName;
}
public int size() {
checkNotClosed();
return mEntries.size();
}
/**
* Find the central directory and read the contents.
*
* <p>The central directory can be followed by a variable-length comment
* field, so we have to scan through it backwards. The comment is at
* most 64K, plus we have 18 bytes for the end-of-central-dir stuff
* itself, plus apparently sometimes people throw random junk on the end
* just for the fun of it.
*
* <p>This is all a little wobbly. If the wrong value ends up in the EOCD
* area, we're hosed. This appears to be the way that everybody handles
* it though, so we're in good company if this fails.
*/
private void readCentralDir() throws IOException {
/*
* Scan back, looking for the End Of Central Directory field. If
* the archive doesn't have a comment, we'll hit it on the first
* try.
*
* No need to synchronize mRaf here -- we only do this when we
* first open the Zip file.
*/
long scanOffset = mRaf.length() - ENDHDR;
if (scanOffset < 0) {
throw new TZipException();
}
long stopOffset = scanOffset - 65536;
if (stopOffset < 0) {
stopOffset = 0;
}
while (true) {
mRaf.seek(scanOffset);
if (TZipEntry.readIntLE(mRaf) == 101010256L) {
break;
}
scanOffset--;
if (scanOffset < stopOffset) {
throw new TZipException();
}
}
/*
* Found it, read the EOCD.
*
* For performance we want to use buffered I/O when reading the
* file. We wrap a buffered stream around the random-access file
* object. If we just read from the RandomAccessFile we'll be
* doing a read() system call every time.
*/
RAFStream rafs = new RAFStream(mRaf, mRaf.getFilePointer());
BufferedInputStream bin = new BufferedInputStream(rafs, ENDHDR);
int diskNumber = ler.readShortLE(bin);
int diskWithCentralDir = ler.readShortLE(bin);
int numEntries = ler.readShortLE(bin);
int totalNumEntries = ler.readShortLE(bin);
/*centralDirSize =*/ ler.readIntLE(bin);
long centralDirOffset = ler.readIntLE(bin);
/*commentLen =*/ ler.readShortLE(bin);
if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
throw new TZipException();
}
/*
* Seek to the first CDE and read all entries.
* However, when Z_SYNC_FLUSH is used the offset may not point directly
* to the CDE so skip over until we find it.
* At most it will be 6 bytes away (one or two bytes for empty block, 4 bytes for
* empty block signature).
*/
scanOffset = centralDirOffset;
stopOffset = scanOffset + 6;
while (true) {
mRaf.seek(scanOffset);
if (TZipEntry.readIntLE(mRaf) == CENSIG) {
break;
}
scanOffset++;
if (scanOffset > stopOffset) {
throw new TZipException();
}
}
// If CDE is found then go and read all the entries
rafs = new RAFStream(mRaf, scanOffset);
bin = new BufferedInputStream(rafs, 4096);
for (int i = 0; i < numEntries; i++) {
TZipEntry newEntry = new TZipEntry(ler, bin);
mEntries.put(newEntry.getName(), newEntry);
}
}
static class RAFStream extends InputStream {
RandomAccessFile mSharedRaf;
long mOffset;
long mLength;
boolean dummyByte;
public RAFStream(RandomAccessFile raf, long pos) throws IOException {
mSharedRaf = raf;
mOffset = pos;
mLength = raf.length();
}
@Override
public int available() throws IOException {
if (mLength > mOffset) {
if (mLength - mOffset < Integer.MAX_VALUE) {
return (int) (mLength - mOffset);
} else {
return Integer.MAX_VALUE;
}
} else {
return 0;
}
}
@Override
public int read() throws IOException {
byte[] singleByteBuf = new byte[1];
if (read(singleByteBuf, 0, 1) == 1) {
return singleByteBuf[0] & 0XFF;
} else {
return -1;
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
mSharedRaf.seek(mOffset);
if (len > mLength - mOffset) {
len = (int) (mLength - mOffset);
}
int count = mSharedRaf.read(b, off, len);
if (count > 0) {
mOffset += count;
return count;
} else if (dummyByte && len >= 0 && b.length > off) {
dummyByte = false;
b[off] = 0;
return 1;
} else {
return -1;
}
}
@Override
public long skip(long n) throws IOException {
if (n > mLength - mOffset) {
n = mLength - mOffset;
}
mOffset += n;
return n;
}
}
static class ZipInflaterInputStream extends TInflaterInputStream {
TZipEntry entry;
long bytesRead;
public ZipInflaterInputStream(InputStream is, TInflater inf, int bsize, TZipEntry entry) {
super(is, inf, bsize);
this.entry = entry;
}
@Override
public int read(byte[] buffer, int off, int nbytes) throws IOException {
int i = super.read(buffer, off, nbytes);
if (i != -1) {
bytesRead += i;
}
return i;
}
@Override
public int available() throws IOException {
return super.available() == 0 ? 0 : (int) (entry.getSize() - bytesRead);
}
}
}
@@ -0,0 +1,629 @@
/*
* 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.
*
* Modified for Incari (tools/teavm-patches/README.md): every function handed to JavaScript (an
* exported class's constructor, methods and properties, a module's functions) is also a function
* export of the module, named teavm.jsfn.<n>. JavaScript reaches them only through the function
* references given to the teavmJso imports, which Binaryen's closed-world optimizations (ADR 0034)
* take to be called by no one: remove-unused-module-elements emptied WebMain's main, and the
* signature passes may change what JavaScript calls. An export keeps a function and its signature.
*/
package org.teavm.jso.impl.wasmgc;
import static org.teavm.jso.impl.JSMethods.JS_OBJECT;
import static org.teavm.jso.impl.JSMethods.WASM_GC_JS_RUNTIME_CLASS;
import static org.teavm.jso.impl.wasmgc.WasmGCJSConstants.STRING_TO_JS;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import org.teavm.backend.javascript.rendering.AstWriter;
import org.teavm.backend.wasm.BaseWasmFunctionRepository;
import org.teavm.backend.wasm.WasmFunctionTypes;
import org.teavm.backend.wasm.generate.WasmGCInitializerRegistry;
import org.teavm.backend.wasm.generate.WasmGCNameProvider;
import org.teavm.backend.wasm.generate.classes.WasmGCTypeMapper;
import org.teavm.backend.wasm.generate.strings.WasmGCStringProvider;
import org.teavm.backend.wasm.model.WasmFunction;
import org.teavm.backend.wasm.model.WasmGlobal;
import org.teavm.backend.wasm.model.WasmLocal;
import org.teavm.backend.wasm.model.WasmModule;
import org.teavm.backend.wasm.model.WasmTag;
import org.teavm.backend.wasm.model.WasmType;
import org.teavm.backend.wasm.model.instruction.WasmExternConversionType;
import org.teavm.backend.wasm.model.instruction.WasmInstructionBuilder;
import org.teavm.backend.wasm.model.instruction.WasmInstructionList;
import org.teavm.backend.wasm.model.instruction.WasmNullConstant;
import org.teavm.jso.JSClass;
import org.teavm.jso.impl.AliasCollector;
import org.teavm.jso.impl.JSBodyAstEmitter;
import org.teavm.jso.impl.JSBodyBloatedEmitter;
import org.teavm.jso.impl.JSBodyEmitter;
import org.teavm.jso.impl.JSMarshallable;
import org.teavm.jso.impl.JSVararg;
import org.teavm.model.ClassReader;
import org.teavm.model.ClassReaderSource;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
class WasmGCJsoCommonGenerator {
private WasmGCJSFunctions jsFunctions;
private WasmFunctionTypes functionTypes;
private ClassReaderSource classes;
private BaseWasmFunctionRepository functions;
private WasmGCTypeMapper typeMapper;
private WasmGCNameProvider names;
private WasmGCStringProvider strings;
private WasmModule module;
private WasmTag exceptionTag;
private WasmGCInitializerRegistry initializerRegistry;
private String entryPoint;
private boolean initialized;
private List<Consumer<WasmFunction>> initializerParts = new ArrayList<>();
private boolean rethrowExported;
private Map<String, WasmGlobal> stringsConstants = new HashMap<>();
private WasmFunction createClassFunction;
private WasmFunction defineFunctionFunction;
private WasmFunction defineMethodFunction;
private WasmFunction defineStaticMethodFunction;
private WasmFunction definePropertyFunction;
private WasmFunction defineStaticPropertyFunction;
private WasmFunction exportClassFunction;
private WasmFunction javaObjectToJSFunction;
private WasmGlobal defaultWrapperClass;
private Map<String, WasmGlobal> definedClasses = new HashMap<>();
private Map<ImportDecl, WasmGlobal> importGlobals = new HashMap<>();
WasmGCJsoCommonGenerator(WasmGCJSFunctions jsFunctions, WasmFunctionTypes functionTypes,
ClassReaderSource classes, BaseWasmFunctionRepository functions, WasmGCTypeMapper typeMapper,
WasmGCNameProvider names, WasmGCStringProvider strings, WasmModule module, WasmTag exceptionTag,
WasmGCInitializerRegistry initializerRegistry, String entryPoint) {
this.jsFunctions = jsFunctions;
this.functionTypes = functionTypes;
this.classes = classes;
this.functions = functions;
this.typeMapper = typeMapper;
this.names = names;
this.strings = strings;
this.module = module;
this.exceptionTag = exceptionTag;
this.initializerRegistry = initializerRegistry;
this.entryPoint = entryPoint;
}
private void initialize() {
if (initialized) {
return;
}
initialized = true;
initializerRegistry.register(this::writeToInitializer);
exportRethrowException();
}
private void writeToInitializer(WasmFunction function) {
for (var part : initializerParts) {
part.accept(function);
}
}
private void addInitializerPart(Consumer<WasmFunction> part) {
initialize();
initializerParts.add(part);
}
WasmGlobal addJSBody(JSBodyEmitter emitter, boolean inlined) {
initialize();
var builder = new WasmInstructionList().builder();
var paramCount = emitter.method().parameterCount();
if (!emitter.isStatic()) {
paramCount++;
}
var imports = emitter.imports();
paramCount += imports.length;
var global = new WasmGlobal(names.suggestForMethod(emitter.method()), WasmType.EXTERN);
global.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
module.globals.add(global);
var body = "";
if (emitter instanceof JSBodyBloatedEmitter) {
body = ((JSBodyBloatedEmitter) emitter).script;
} else if (emitter instanceof JSBodyAstEmitter) {
var writer = new WasmGCJSBodyWriter();
if (inlined) {
writer.sb.append("return ");
}
var astEmitter = (JSBodyAstEmitter) emitter;
var astWriter = new AstWriter(writer, name -> (w, prec) -> w.append(name));
if (!emitter.isStatic()) {
astWriter.declareNameEmitter("this", (w, prec) -> w.append("__this__"));
}
astWriter.print(astEmitter.ast);
if (inlined) {
writer.sb.append(";");
}
body = writer.sb.toString();
} else {
throw new IllegalArgumentException();
}
var paramNames = new ArrayList<String>();
for (var importDecl : imports) {
paramNames.add(importDecl.alias);
}
if (!emitter.isStatic()) {
paramNames.add("__this__");
}
paramNames.addAll(List.of(emitter.parameterNames()));
for (var parameter : paramNames) {
builder
.getGlobal(strings.getStringConstant(parameter).global)
.call(stringToJsFunction());
}
builder
.getGlobal(strings.getStringConstant(body).global)
.call(stringToJsFunction());
builder.call(jsFunctions.getFunctionConstructor(paramCount));
if (imports.length > 0) {
for (var importDecl : imports) {
var importGlobal = getImportGlobal(importDecl.fromModule, "__self__");
builder.getGlobal(importGlobal);
}
builder.call(jsFunctions.getBind(imports.length));
}
builder.setGlobal(global);
initializerParts.add(initializer -> initializer.getBody().transferFrom(builder.list));
return global;
}
WasmGlobal getImportGlobal(String module, String id) {
return importGlobals.computeIfAbsent(new ImportDecl(module, id), m -> {
var name = names.topLevel(WasmGCNameProvider.sanitize("teavm.js@imports:" + module + "#" + id));
var global = new WasmGlobal(name, WasmType.EXTERN);
global.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
global.setImmutable(true);
this.module.globals.add(global);
global.setImportModule(module);
global.setImportName(id);
return global;
});
}
private WasmFunction stringToJsFunction() {
var fun = functions.forStaticMethod(STRING_TO_JS);
if (fun.getExportName() == null) {
fun.setExportName("teavm.stringToJs");
}
return fun;
}
private void exportRethrowException() {
if (rethrowExported) {
return;
}
rethrowExported = true;
var fn = functions.forStaticMethod(new MethodReference(WASM_GC_JS_RUNTIME_CLASS, "wrapException",
JS_OBJECT, ValueType.object("java.lang.Throwable")));
fn.setExportName("teavm.js.wrapException");
fn = functions.forStaticMethod(new MethodReference(WASM_GC_JS_RUNTIME_CLASS, "extractException",
ValueType.object("java.lang.Throwable"), JS_OBJECT));
fn.setExportName("teavm.js.extractException");
createThrowExceptionFunction();
}
private void createThrowExceptionFunction() {
var fn = new WasmFunction(functionTypes.of(null, WasmType.EXTERN));
fn.setName(names.topLevel("teavm@throwException"));
fn.setExportName("teavm.js.throwException");
module.functions.add(fn);
var exceptionLocal = new WasmLocal(WasmType.EXTERN);
fn.add(exceptionLocal);
var throwableType = (WasmType.Reference) typeMapper.mapType(ValueType.parse(Throwable.class));
fn.getBody().builder()
.getLocal(exceptionLocal)
.externConvert(WasmExternConversionType.EXTERN_TO_ANY)
.cast(throwableType)
.throw_(exceptionTag);
}
WasmGlobal jsStringConstant(String str) {
return stringsConstants.computeIfAbsent(str, s -> {
var javaGlobal = strings.getStringConstant(s).global;
var function = functions.forStaticMethod(STRING_TO_JS);
var index = stringsConstants.size();
var brief = str.length() > 16 ? str.substring(0, 16) : str;
var name = names.topLevel("teavm.js.strings<" + index + ">:"
+ WasmGCNameProvider.sanitize(brief));
var jsGlobal = new WasmGlobal(name, WasmType.EXTERN);
jsGlobal.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
module.globals.add(jsGlobal);
addInitializerPart(initializer -> initializer.getBody().builder()
.getGlobal(javaGlobal)
.call(function)
.setGlobal(jsGlobal));
return jsGlobal;
});
}
WasmGlobal getDefaultWrapperClass() {
if (defaultWrapperClass == null) {
var name = names.topLevel("teavm.js@defaultWrapperClass");
defaultWrapperClass = new WasmGlobal(name, WasmType.EXTERN);
defaultWrapperClass.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
module.globals.add(defaultWrapperClass);
addInitializerPart(initializer -> initializer.getBody().builder()
.nullConst(WasmType.EXTERN)
.nullConst(WasmType.EXTERN)
.nullConst(WasmType.FUNC)
.call(createClassFunction())
.setGlobal(defaultWrapperClass));
}
return defaultWrapperClass;
}
WasmGlobal getDefinedClass(String className) {
var result = definedClasses.get(className);
if (result == null) {
result = defineClass(className);
definedClasses.put(className, result);
}
return result;
}
private WasmGlobal defineClass(String className) {
var name = names.topLevel(names.suggestForClass(className + "@js"));
var global = new WasmGlobal(name, WasmType.EXTERN);
global.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
module.globals.add(global);
var body = new WasmInstructionList().builder();
var cls = classes.get(className);
var isModule = entryPoint.equals(className);
var members = AliasCollector.collectMembers(cls, AliasCollector::isInstanceMember);
var staticMembers = AliasCollector.collectMembers(cls, AliasCollector::isStaticMember);
var simpleName = className.substring(className.lastIndexOf('.') + 1);
var javaClassName = strings.getStringConstant(simpleName);
var exportedParent = parentExportedClass(cls.getParent());
var needsExport = !className.equals(entryPoint)
&& (!staticMembers.methods.isEmpty() || !staticMembers.properties.isEmpty());
WasmFunction constructorFn = null;
if (members.constructor != null) {
constructorFn = functions.forStaticMethod(members.constructor);
exportToJs(constructorFn);
needsExport = true;
}
body.getGlobal(javaClassName.global).call(stringToJsFunction());
if (exportedParent != null) {
body.getGlobal(getDefinedClass(exportedParent));
} else {
body.nullConst(WasmType.EXTERN);
}
if (constructorFn != null) {
body.funcRef(constructorFn);
} else {
body.nullConst(WasmType.FUNC);
}
body.call(createClassFunction()).setGlobal(global);
defineMethods(members, cls, global, body);
defineProperties(members, cls, global, body);
var globalForStatic = global;
if (needsExport) {
globalForStatic = exportClass(cls, global, body);
}
defineStaticMethods(staticMembers, cls, globalForStatic, body, isModule);
defineStaticProperties(staticMembers, cls, globalForStatic, body);
initializerRegistry.register(f -> f.getBody().transferFrom(body.list));
return global;
}
private void defineMethods(AliasCollector.Members members, ClassReader cls, WasmGlobal global,
WasmInstructionBuilder builder) {
for (var aliasEntry : members.methods.entrySet()) {
if (!aliasEntry.getValue().getClassName().equals(cls.getName())) {
continue;
}
var fn = functions.forStaticMethod(aliasEntry.getValue());
var methodReader = classes.getMethod(aliasEntry.getValue());
exportToJs(fn);
var methodName = strings.getStringConstant(aliasEntry.getKey());
builder.getGlobal(global)
.getGlobal(methodName.global).call(stringToJsFunction())
.funcRef(fn)
.i32Const(varargValue(methodReader))
.call(defineMethodFunction());
}
}
private void defineProperties(AliasCollector.Members members, ClassReader cls, WasmGlobal global,
WasmInstructionBuilder builder) {
for (var aliasEntry : members.properties.entrySet()) {
var property = aliasEntry.getValue();
if (!property.getter.getClassName().equals(cls.getName())) {
continue;
}
var getter = functions.forStaticMethod(property.getter);
exportToJs(getter);
WasmFunction setter = null;
if (property.setter != null) {
setter = functions.forStaticMethod(property.setter);
exportToJs(setter);
}
var methodName = strings.getStringConstant(aliasEntry.getKey());
builder.getGlobal(global)
.getGlobal(methodName.global).call(stringToJsFunction())
.funcRef(getter);
if (setter != null) {
builder.funcRef(setter);
} else {
builder.nullConst(WasmType.FUNC);
}
builder.call(definePropertyFunction());
}
}
private void defineStaticMethods(AliasCollector.Members members, ClassReader cls, WasmGlobal global,
WasmInstructionBuilder builder, boolean isModule) {
for (var aliasEntry : members.methods.entrySet()) {
if (!aliasEntry.getValue().getClassName().equals(cls.getName())) {
continue;
}
var fn = functions.forStaticMethod(aliasEntry.getValue());
exportToJs(fn);
var methodReader = classes.getMethod(aliasEntry.getValue());
if (isModule) {
var globalName = names.topLevel("teavm.js.export.function@" + aliasEntry.getKey());
var functionGlobal = new WasmGlobal(globalName, WasmType.EXTERN);
functionGlobal.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
functionGlobal.setExportName(aliasEntry.getKey());
module.globals.add(functionGlobal);
builder.funcRef(fn)
.i32Const(varargValue(methodReader))
.call(defineFunctionFunction())
.setGlobal(functionGlobal);
}
var methodName = strings.getStringConstant(aliasEntry.getKey());
builder.getGlobal(global)
.getGlobal(methodName.global).call(stringToJsFunction())
.funcRef(fn)
.i32Const(varargValue(methodReader))
.call(defineStaticMethodFunction());
}
}
private int varargValue(MethodReader methodReader) {
return methodReader.getAnnotations().get(JSVararg.class.getName()) != null ? 1 : 0;
}
private void defineStaticProperties(AliasCollector.Members members, ClassReader cls,
WasmGlobal global, WasmInstructionBuilder builder) {
for (var aliasEntry : members.properties.entrySet()) {
var property = aliasEntry.getValue();
if (!property.getter.getClassName().equals(cls.getName())) {
continue;
}
var getter = functions.forStaticMethod(property.getter);
exportToJs(getter);
WasmFunction setter = null;
if (property.setter != null) {
setter = functions.forStaticMethod(property.setter);
exportToJs(setter);
}
var methodName = strings.getStringConstant(aliasEntry.getKey());
builder.getGlobal(global)
.getGlobal(methodName.global).call(stringToJsFunction())
.funcRef(getter);
if (setter != null) {
builder.funcRef(setter);
} else {
builder.nullConst(WasmType.FUNC);
}
builder.call(defineStaticPropertyFunction());
}
}
private WasmGlobal exportClass(ClassReader cls, WasmGlobal global, WasmInstructionBuilder builder) {
var exportName = getClassAliasName(cls);
var globalName = names.topLevel("teavm.js.export.class@" + exportName);
var exportGlobal = new WasmGlobal(globalName, WasmType.EXTERN);
exportGlobal.getInitialValue().add(new WasmNullConstant(WasmType.EXTERN));
exportGlobal.setExportName(exportName);
module.globals.add(exportGlobal);
builder.getGlobal(global).call(exportClassFunction()).setGlobal(exportGlobal);
return exportGlobal;
}
private String parentExportedClass(String className) {
while (className != null) {
var cls = classes.get(className);
if (cls == null) {
return null;
}
if (cls.getInterfaces().contains(JSMarshallable.class.getName())) {
return className;
}
className = cls.getParent();
}
return null;
}
private WasmFunction createClassFunction() {
if (createClassFunction == null) {
createClassFunction = new WasmFunction(functionTypes.of(WasmType.EXTERN, WasmType.EXTERN,
WasmType.EXTERN, WasmType.FUNC));
createClassFunction.setName(names.topLevel("teavm.jso@createClass"));
createClassFunction.setImportName("createClass");
createClassFunction.setImportModule("teavmJso");
module.functions.add(createClassFunction);
}
return createClassFunction;
}
private int jsFunctionExports;
// Incari: marks a function as handed to JavaScript, and exports it (see the header).
private void exportToJs(WasmFunction fn) {
fn.setReferenced(true);
if (fn.getExportName() == null) {
fn.setExportName("teavm.jsfn." + jsFunctionExports++);
}
}
private WasmFunction defineFunctionFunction() {
if (defineFunctionFunction == null) {
defineFunctionFunction = new WasmFunction(functionTypes.of(WasmType.EXTERN, WasmType.FUNC,
WasmType.INT32));
defineFunctionFunction.setName(names.topLevel("teavm.jso@defineFunction"));
defineFunctionFunction.setImportName("defineFunction");
defineFunctionFunction.setImportModule("teavmJso");
module.functions.add(defineFunctionFunction);
}
return defineFunctionFunction;
}
private WasmFunction defineMethodFunction() {
if (defineMethodFunction == null) {
defineMethodFunction = new WasmFunction(functionTypes.of(null, WasmType.EXTERN, WasmType.EXTERN,
WasmType.FUNC, WasmType.INT32));
defineMethodFunction.setName(names.topLevel("teavm.jso@defineMethod"));
defineMethodFunction.setImportName("defineMethod");
defineMethodFunction.setImportModule("teavmJso");
module.functions.add(defineMethodFunction);
}
return defineMethodFunction;
}
private WasmFunction defineStaticMethodFunction() {
if (defineStaticMethodFunction == null) {
defineStaticMethodFunction = new WasmFunction(functionTypes.of(null, WasmType.EXTERN, WasmType.EXTERN,
WasmType.FUNC, WasmType.INT32));
defineStaticMethodFunction.setName(names.topLevel("teavm.jso@defineStaticMethod"));
defineStaticMethodFunction.setImportName("defineStaticMethod");
defineStaticMethodFunction.setImportModule("teavmJso");
module.functions.add(defineStaticMethodFunction);
}
return defineStaticMethodFunction;
}
private WasmFunction definePropertyFunction() {
if (definePropertyFunction == null) {
definePropertyFunction = new WasmFunction(functionTypes.of(null, WasmType.EXTERN,
WasmType.EXTERN, WasmType.FUNC, WasmType.FUNC));
definePropertyFunction.setName(names.topLevel("teavm.jso@defineProperty"));
definePropertyFunction.setImportName("defineProperty");
definePropertyFunction.setImportModule("teavmJso");
module.functions.add(definePropertyFunction);
}
return definePropertyFunction;
}
private WasmFunction defineStaticPropertyFunction() {
if (defineStaticPropertyFunction == null) {
defineStaticPropertyFunction = new WasmFunction(functionTypes.of(null, WasmType.EXTERN, WasmType.EXTERN,
WasmType.FUNC, WasmType.FUNC));
defineStaticPropertyFunction.setName(names.topLevel("teavm.jso@defineStaticProperty"));
defineStaticPropertyFunction.setImportName("defineStaticProperty");
defineStaticPropertyFunction.setImportModule("teavmJso");
module.functions.add(defineStaticPropertyFunction);
}
return defineStaticPropertyFunction;
}
private WasmFunction exportClassFunction() {
if (exportClassFunction == null) {
exportClassFunction = new WasmFunction(functionTypes.of(WasmType.EXTERN, WasmType.EXTERN));
exportClassFunction.setName(names.topLevel("teavm.jso@exportClass"));
exportClassFunction.setImportName("exportClass");
exportClassFunction.setImportModule("teavmJso");
module.functions.add(exportClassFunction);
}
return exportClassFunction;
}
WasmFunction javaObjectToJSFunction() {
if (javaObjectToJSFunction == null) {
javaObjectToJSFunction = new WasmFunction(functionTypes.of(WasmType.EXTERN,
typeMapper.mapType(ValueType.parse(Object.class)), WasmType.EXTERN));
javaObjectToJSFunction.setName(names.topLevel("teavm.jso@javaObjectToJS"));
javaObjectToJSFunction.setImportName("javaObjectToJS");
javaObjectToJSFunction.setImportModule("teavmJso");
module.functions.add(javaObjectToJSFunction);
}
return javaObjectToJSFunction;
}
private String getClassAliasName(ClassReader cls) {
var name = cls.getSimpleName();
if (name == null) {
name = cls.getName().substring(cls.getName().lastIndexOf('.') + 1);
}
var jsExport = cls.getAnnotations().get(JSClass.class.getName());
if (jsExport != null) {
var nameValue = jsExport.getValue("name");
if (nameValue != null) {
var nameValueString = nameValue.getString();
if (!nameValueString.isEmpty()) {
name = nameValueString;
}
}
}
return name;
}
private static class ImportDecl {
final String module;
final String name;
ImportDecl(String module, String name) {
this.module = module;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ImportDecl)) {
return false;
}
var that = (ImportDecl) o;
return Objects.equals(module, that.module) && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(module, name);
}
}
}
@@ -0,0 +1,97 @@
/*
* Copyright 2016 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.
*
* Modified for Incari (tools/teavm-patches/README.md): only a static call proves its class
* initialized (an instance call through an interface doesn't initialize the interface), and an
* exception handler inherits only what was initialized when its dominating block began, since
* the exception may leave that block before the rest of it runs.
*/
package org.teavm.model.optimization;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import org.teavm.common.DominatorTree;
import org.teavm.common.Graph;
import org.teavm.common.GraphUtils;
import org.teavm.model.BasicBlock;
import org.teavm.model.Instruction;
import org.teavm.model.Program;
import org.teavm.model.instructions.InitClassInstruction;
import org.teavm.model.instructions.InvokeInstruction;
import org.teavm.model.util.ProgramUtils;
public class ClassInitElimination implements MethodOptimization {
@Override
public boolean optimize(MethodOptimizationContext context, Program program) {
Graph cfg = ProgramUtils.buildControlFlowGraph(program);
DominatorTree dom = GraphUtils.buildDominatorTree(cfg);
Graph domGraph = GraphUtils.buildDominatorGraph(dom, program.basicBlockCount());
Set<Integer> handlers = new HashSet<>();
for (int i = 0; i < program.basicBlockCount(); ++i) {
for (var tryCatch : program.basicBlockAt(i).getTryCatchBlocks()) {
handlers.add(tryCatch.getHandler().getIndex());
}
}
Step start = new Step(0);
Deque<Step> stack = new ArrayDeque<>();
stack.push(start);
while (!stack.isEmpty()) {
Step step = stack.pop();
int node = step.node;
BasicBlock block = program.basicBlockAt(node);
Set<String> atEntry = new HashSet<>(step.initializedClasses);
Instruction nextInsn;
for (Instruction insn = block.getFirstInstruction(); insn != null; insn = nextInsn) {
nextInsn = insn.getNext();
if (insn instanceof InitClassInstruction) {
InitClassInstruction initClass = (InitClassInstruction) insn;
if (!step.initializedClasses.add(initClass.getClassName())) {
insn.delete();
}
continue;
}
if (insn instanceof InvokeInstruction) {
InvokeInstruction invoke = (InvokeInstruction) insn;
if (invoke.getInstance() == null) {
step.initializedClasses.add(invoke.getMethod().getClassName());
}
}
}
for (int successor : domGraph.outgoingEdges(node)) {
Step next = new Step(successor);
next.initializedClasses.addAll(handlers.contains(successor) ? atEntry : step.initializedClasses);
stack.push(next);
}
}
return false;
}
static class Step {
int node;
Set<String> initializedClasses = new HashSet<>();
Step(int node) {
this.node = node;
}
}
}
@@ -0,0 +1,92 @@
/*
* Copyright 2017 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.
*
* Modified for Incari (tools/teavm-patches/README.md): a class's static initializer now first
* initializes its superclass (the nearest one with a dynamic initializer), as the JLS requires
* (12.4.2, step 7). TeaVM only initialized a class at the entry of its own constructors and static
* members, so "new Sub()" ran Sub's static initializer before its superclass's.
*/
package org.teavm.model.transformation;
import org.teavm.model.BasicBlock;
import org.teavm.model.ClassReader;
import org.teavm.model.ClassReaderSource;
import org.teavm.model.ElementModifier;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodReader;
import org.teavm.model.Program;
import org.teavm.model.analysis.ClassInitializerInfo;
import org.teavm.model.instructions.InitClassInstruction;
public class ClassInitializerInsertionTransformer {
private static final MethodDescriptor clinitDescriptor = new MethodDescriptor("<clinit>", void.class);
private ClassReaderSource classes;
private ClassInitializerInfo classInitializerInfo;
public ClassInitializerInsertionTransformer(ClassReaderSource classes, ClassInitializerInfo classInitializerInfo) {
this.classes = classes;
this.classInitializerInfo = classInitializerInfo;
}
public void apply(MethodReader method, Program program) {
if (program.basicBlockCount() == 0) {
return;
}
ClassReader cls = classes.get(method.getOwnerName());
if (method.getName().equals("<clinit>") && method.hasModifier(ElementModifier.STATIC)
&& !cls.hasModifier(ElementModifier.INTERFACE)) {
// Incari: the superclass first. Its own initializer does the same for its superclass.
String superclass = nearestDynamicInitializer(cls.getParent());
if (superclass != null) {
InitClassInstruction initInsn = new InitClassInstruction();
initInsn.setClassName(superclass);
program.basicBlockAt(0).addFirst(initInsn);
}
}
boolean hasClinit = cls.getMethod(clinitDescriptor) != null
&& classInitializerInfo.isDynamicInitializer(cls.getName());
if (hasClinit && needsClinitCall(method)) {
BasicBlock entryBlock = program.basicBlockAt(0);
InitClassInstruction initInsn = new InitClassInstruction();
initInsn.setClassName(method.getOwnerName());
entryBlock.addFirst(initInsn);
}
}
// Incari: the nearest class from className up whose static initializer runs at run time.
private String nearestDynamicInitializer(String className) {
while (className != null) {
ClassReader cls = classes.get(className);
if (cls == null) {
return null;
}
if (cls.getMethod(clinitDescriptor) != null && classInitializerInfo.isDynamicInitializer(className)) {
return className;
}
className = cls.getParent();
}
return null;
}
private static boolean needsClinitCall(MethodReader method) {
if (method.getName().equals("<clinit>")) {
return false;
}
if (method.getName().equals("<init>")) {
return true;
}
return method.hasModifier(ElementModifier.STATIC);
}
}
@@ -0,0 +1,297 @@
/*
* Copyright 2015 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.
*
* Modified for Incari (tools/teavm-patches/README.md): with the system property incari.jspi set,
* finds no async methods, for a WebAssembly GC build whose suspensions use JSPI (see Fiber).
*/
package org.teavm.model.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.teavm.callgraph.CallGraph;
import org.teavm.callgraph.CallGraphNode;
import org.teavm.callgraph.CallSite;
import org.teavm.dependency.DependencyInfo;
import org.teavm.interop.Async;
import org.teavm.model.ClassReader;
import org.teavm.model.ElementModifier;
import org.teavm.model.ListableClassReaderSource;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.ProgramReader;
import org.teavm.model.VariableReader;
import org.teavm.model.instructions.AbstractInstructionReader;
import org.teavm.runtime.Fiber;
public class AsyncMethodFinder {
private Set<MethodReference> asyncMethods = new HashSet<>();
private DependencyInfo dependency;
private Map<MethodReference, Boolean> asyncFamilyMethods = new HashMap<>();
private Set<MethodReference> readonlyAsyncMethods = Collections.unmodifiableSet(asyncMethods);
private Set<MethodReference> readonlyAsyncFamilyMethods = Collections.unmodifiableSet(asyncFamilyMethods.keySet());
private CallGraph callGraph;
private ListableClassReaderSource classSource;
private boolean hasAsyncMethods;
public AsyncMethodFinder(CallGraph callGraph, DependencyInfo dependency) {
this.callGraph = callGraph;
this.dependency = dependency;
}
public Set<MethodReference> getAsyncMethods() {
return readonlyAsyncMethods;
}
public Set<MethodReference> getAsyncFamilyMethods() {
return readonlyAsyncFamilyMethods;
}
public void find(ListableClassReaderSource classSource) {
this.classSource = classSource;
// Incari: in a JSPI build (WebAssembly JavaScript Promise Integration) the engine suspends
// the whole stack itself, so no method is compiled as a coroutine.
if (Boolean.getBoolean("incari.jspi")) {
hasAsyncMethods = false;
return;
}
hasAsyncMethods = findAsyncMethods();
for (String clsName : classSource.getClassNames()) {
ClassReader cls = classSource.get(clsName);
for (MethodReader method : cls.getMethods()) {
if (!dependency.getReachableMethods().contains(method.getReference())
|| asyncMethods.contains(method.getReference())) {
continue;
}
if (method.getAnnotations().get(Async.class.getName()) != null) {
add(method.getReference(), new CallStack(method.getReference(), null));
}
}
}
if (hasAsyncMethods) {
for (String clsName : classSource.getClassNames()) {
ClassReader cls = classSource.get(clsName);
for (MethodReader method : cls.getMethods()) {
if (!dependency.getReachableMethods().contains(method.getReference())
|| asyncMethods.contains(method.getReference()) || method.getProgram() == null) {
continue;
}
if (hasMonitor(method)) {
add(method.getReference(), new CallStack(method.getReference(), null));
}
}
}
}
for (MethodReference method : asyncMethods) {
addOverriddenToFamily(method);
}
for (String clsName : classSource.getClassNames()) {
ClassReader cls = classSource.get(clsName);
for (MethodReader method : cls.getMethods()) {
addToFamily(method.getReference());
}
}
for (Map.Entry<MethodReference, Boolean> entry : new ArrayList<>(asyncFamilyMethods.entrySet())) {
if (!entry.getValue()) {
asyncFamilyMethods.remove(entry.getKey());
}
}
}
private boolean findAsyncMethods() {
boolean result = false;
loop: for (String clsName : classSource.getClassNames()) {
ClassReader cls = classSource.get(clsName);
for (MethodReader method : cls.getMethods()) {
if (!asyncMethods.contains(method.getReference()) || method.getProgram() == null) {
continue;
}
if (hasMonitor(method)) {
result = true;
break loop;
}
}
}
boolean hasThreads = dependency.getReachableMethods().contains(new MethodReference(
Thread.class, "start", void.class));
return result && hasThreads;
}
public boolean hasAsyncMethods() {
return hasAsyncMethods;
}
private boolean hasMonitor(MethodReader method) {
if (method.hasModifier(ElementModifier.SYNCHRONIZED)) {
return true;
}
ProgramReader program = method.getProgram();
AsyncInstructionReader insnReader = new AsyncInstructionReader();
for (int i = 0; i < program.basicBlockCount(); ++i) {
program.basicBlockAt(i).readAllInstructions(insnReader);
if (insnReader.async) {
return true;
}
}
return false;
}
private void add(MethodReference methodRef, CallStack stack) {
if (methodRef.getClassName().equals(Fiber.class.getName())) {
return;
}
if (!asyncMethods.add(methodRef)) {
return;
}
CallGraphNode node = callGraph.getNode(methodRef);
if (node == null) {
return;
}
ClassReader cls = classSource.get(methodRef.getClassName());
if (cls == null) {
return;
}
MethodReader method = cls.getMethod(methodRef.getDescriptor());
if (method == null) {
return;
}
if (!hasAsyncMethods && methodRef.getClassName().equals("java.lang.Object")
&& (methodRef.getName().equals("monitorEnter") || methodRef.getName().equals("monitorExit"))
&& methodRef.parameterCount() == 1) {
return;
}
for (CallSite callSite : node.getCallerCallSites()) {
for (CallGraphNode caller : callSite.getCallers()) {
add(caller.getMethod(), new CallStack(caller.getMethod(), stack));
}
}
}
static class CallStack {
MethodReference method;
CallStack next;
CallStack(MethodReference method, CallStack next) {
this.method = method;
this.next = next;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
CallStack stack = this;
while (stack != null) {
sb.append("\n calling " + stack.method);
stack = stack.next;
}
return sb.toString();
}
}
private void addOverriddenToFamily(MethodReference methodRef) {
asyncFamilyMethods.put(methodRef, true);
ClassReader cls = classSource.get(methodRef.getClassName());
if (cls == null) {
return;
}
for (MethodReference overriddenMethod : findOverriddenMethods(cls, methodRef.getDescriptor())) {
addOverriddenToFamily(overriddenMethod);
}
}
private boolean addToFamily(MethodReference methodRef) {
Boolean cachedResult = asyncFamilyMethods.get(methodRef);
if (cachedResult != null) {
return cachedResult;
}
boolean result = addToFamilyCacheMiss(methodRef);
asyncFamilyMethods.put(methodRef, result);
return result;
}
private boolean addToFamilyCacheMiss(MethodReference methodRef) {
if (asyncMethods.contains(methodRef)) {
return true;
}
ClassReader cls = classSource.get(methodRef.getClassName());
if (cls == null) {
return false;
}
for (MethodReference overriddenMethod : findOverriddenMethods(cls, methodRef.getDescriptor())) {
if (addToFamily(overriddenMethod)) {
return true;
}
}
return false;
}
private Set<MethodReference> findOverriddenMethods(ClassReader cls, MethodDescriptor methodDesc) {
List<String> parents = new ArrayList<>();
if (cls.getParent() != null) {
parents.add(cls.getParent());
}
parents.addAll(cls.getInterfaces());
Set<String> visited = new HashSet<>();
Set<MethodReference> overridden = new HashSet<>();
for (String parent : parents) {
findOverriddenMethods(parent, methodDesc, overridden, visited);
}
return overridden;
}
private void findOverriddenMethods(String className, MethodDescriptor methodDesc, Set<MethodReference> result,
Set<String> visited) {
if (!visited.add(className)) {
return;
}
if (methodDesc.getName().equals("<init>") || methodDesc.getName().equals("<clinit>")) {
return;
}
ClassReader cls = classSource.get(className);
if (cls == null) {
return;
}
MethodReader method = cls.getMethod(methodDesc);
if (method != null) {
if (!method.hasModifier(ElementModifier.STATIC) && !method.hasModifier(ElementModifier.FINAL)) {
result.add(method.getReference());
}
} else {
if (cls.getParent() != null) {
findOverriddenMethods(cls.getParent(), methodDesc, result, visited);
}
for (String iface : cls.getInterfaces()) {
findOverriddenMethods(iface, methodDesc, result, visited);
}
}
}
static class AsyncInstructionReader extends AbstractInstructionReader {
boolean async;
@Override
public void monitorEnter(VariableReader objectRef) {
async = true;
}
}
}
@@ -0,0 +1,541 @@
/*
* Copyright 2018 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.
*
* Modified for Incari (tools/teavm-patches/README.md): adds Fiber.Jspi, fibers on WebAssembly
* JavaScript Promise Integration for builds that compile no coroutines.
*/
package org.teavm.runtime;
import java.util.Arrays;
import org.teavm.interop.Address;
import org.teavm.interop.AsyncCallback;
import org.teavm.interop.Export;
import org.teavm.interop.Import;
import org.teavm.interop.StaticInit;
import org.teavm.interop.Unmanaged;
@StaticInit
public final class Fiber {
public static final int STATE_RUNNING = 0;
public static final int STATE_SUSPENDING = 1;
public static final int STATE_RESUMING = 2;
public static int userThreadCount = 1;
private int[] intValues;
private int intTop;
private long[] longValues;
private int longTop;
private float[] floatValues;
private int floatTop;
private double[] doubleValues;
private int doubleTop;
private Object[] objectValues;
private int objectTop;
private int state;
private FiberRunner runner;
private Object result;
private Throwable exception;
private boolean isPendingResume;
private boolean daemon;
private static Fiber current;
private static PendingCall lastPendingCall;
private Fiber(FiberRunner runner, boolean daemon) {
this.runner = runner;
this.daemon = daemon;
}
public void push(int value) {
if (intValues == null) {
intValues = new int[4];
} else if (intTop + 1 == intValues.length) {
intValues = Arrays.copyOf(intValues, intValues.length * 3 / 2);
}
intValues[intTop++] = value;
}
public void push(long value) {
if (longValues == null) {
longValues = new long[4];
} else if (longTop + 1 == longValues.length) {
longValues = Arrays.copyOf(longValues, longValues.length * 3 / 2);
}
longValues[longTop++] = value;
}
public void push(float value) {
if (floatValues == null) {
floatValues = new float[4];
} else if (floatTop + 1 == floatValues.length) {
floatValues = Arrays.copyOf(floatValues, floatValues.length * 3 / 2);
}
floatValues[floatTop++] = value;
}
public void push(double value) {
if (doubleValues == null) {
doubleValues = new double[4];
} else if (doubleTop + 1 == doubleValues.length) {
doubleValues = Arrays.copyOf(doubleValues, doubleValues.length * 3 / 2);
}
doubleValues[doubleTop++] = value;
}
public void push(Object value) {
if (objectValues == null) {
objectValues = new Object[4];
} else if (objectTop + 1 == objectValues.length) {
objectValues = Arrays.copyOf(objectValues, objectValues.length * 3 / 2);
}
objectValues[objectTop++] = value;
}
public static void reversePush(int value, Fiber fiber) {
fiber.push(value);
}
public static void reversePush(long value, Fiber fiber) {
fiber.push(value);
}
public static void reversePush(float value, Fiber fiber) {
fiber.push(value);
}
public static void reversePush(double value, Fiber fiber) {
fiber.push(value);
}
public static void reversePush(Object value, Fiber fiber) {
fiber.push(value);
}
public static void reversePush(PlatformObject value, Fiber fiber) {
fiber.push(new PlatformObjectWrapper(value));
}
public static void reversePush(PlatformFunction value, Fiber fiber) {
fiber.push(new PlatformFunctionWrapper(value));
}
public static void reversePush(PlatformException value, Fiber fiber) {
fiber.push(new PlatformExceptionWrapper(value));
}
@Unmanaged
public int popInt() {
return intValues[--intTop];
}
@Unmanaged
public long popLong() {
return longValues[--longTop];
}
@Unmanaged
public float popFloat() {
return floatValues[--floatTop];
}
@Unmanaged
public double popDouble() {
return doubleValues[--doubleTop];
}
@Unmanaged
public Object popObject() {
Object result = objectValues[--objectTop];
objectValues[objectTop] = null;
return result;
}
public PlatformObject popPlatformObject() {
var wrapper = (PlatformObjectWrapper) popObject();
return wrapper.object;
}
public PlatformFunction popPlatformFunction() {
var wrapper = (PlatformFunctionWrapper) popObject();
return wrapper.object;
}
public PlatformException popPlatformException() {
var wrapper = (PlatformExceptionWrapper) popObject();
return wrapper.object;
}
@Unmanaged
public static Fiber current() {
return current;
}
@Unmanaged
public boolean isSuspending() {
return state == STATE_SUSPENDING;
}
@Unmanaged
public static boolean isPresentAndSuspending(Fiber fiber) {
return fiber != null && fiber.isSuspending();
}
@Unmanaged
public boolean isResuming() {
return state == STATE_RESUMING;
}
@Unmanaged
public static boolean isPresentAndResuming(Fiber fiber) {
return fiber != null && fiber.isResuming();
}
@Unmanaged
public static boolean getBoolean(Object v) {
return v != null ? (Boolean) v : false;
}
@Unmanaged
public static byte getByte(Object v) {
return v != null ? (Byte) v : 0;
}
@Unmanaged
public static short getShort(Object v) {
return v != null ? (Short) v : 0;
}
@Unmanaged
public static int getInt(Object v) {
return v != null ? (Integer) v : 0;
}
@Unmanaged
public static char getChar(Object v) {
return v != null ? (Character) v : 0;
}
@Unmanaged
public static long getLong(Object v) {
return v != null ? (Long) v : 0;
}
@Unmanaged
public static float getFloat(Object v) {
return v != null ? (Float) v : 0;
}
@Unmanaged
public static double getDouble(Object v) {
return v != null ? (Double) v : 0;
}
public static Object suspend(AsyncCall call) throws Throwable {
Fiber fiber = current();
if (fiber == null) {
throw new IllegalStateException("Suspension point reached from non-threading context "
+ "(perhaps, from native JS method). See https://teavm.org/docs/runtime/coroutines.html "
+ "('Interaction with JavaScript' section)");
}
Thread javaThread = Thread.currentThread();
if (fiber.isResuming()) {
fiber.state = STATE_RUNNING;
if (fiber.exception != null) {
throw fiber.exception;
}
return fiber.result;
}
PendingCall pendingCall = new PendingCall(call, lastPendingCall);
if (lastPendingCall != null) {
lastPendingCall.next = pendingCall;
}
lastPendingCall = pendingCall;
fiber.state = STATE_SUSPENDING;
pendingCall.callback = new AsyncCallbackImpl(pendingCall, javaThread, fiber);
call.run(pendingCall.callback);
return null;
}
static class AsyncCallbackImpl implements AsyncCallback<Object> {
PendingCall pendingCall;
Thread javaThread;
Fiber fiber;
AsyncCallbackImpl(PendingCall pendingCall, Thread javaThread, Fiber fiber) {
this.pendingCall = pendingCall;
this.javaThread = javaThread;
this.fiber = fiber;
}
@Override
public void complete(Object result) {
if (Fiber.current == this.fiber) {
fiber.result = result;
fiber.isPendingResume = true;
removePendingCall();
} else {
setCurrentThread(javaThread);
javaThread = null;
Fiber fiber = this.fiber;
this.fiber = null;
fiber.result = result;
removePendingCall();
fiber.resume();
}
}
@Override
public void error(Throwable e) {
if (Fiber.current == this.fiber) {
fiber.exception = e;
fiber.isPendingResume = true;
removePendingCall();
} else {
setCurrentThread(javaThread);
javaThread = null;
Fiber fiber = this.fiber;
this.fiber = null;
fiber.exception = e;
removePendingCall();
fiber.resume();
}
}
private void removePendingCall() {
if (pendingCall.previous != null) {
pendingCall.previous.next = pendingCall.next;
}
if (pendingCall.next != null) {
pendingCall.next.previous = pendingCall.previous;
}
if (pendingCall == lastPendingCall) {
lastPendingCall = pendingCall.previous;
}
pendingCall = null;
}
}
static native void setCurrentThread(Thread thread);
public static void start(FiberRunner runner, boolean daemon) {
new Fiber(runner, daemon).start();
}
static void startMain(String[] args) {
start(() -> runMain(args), false);
}
public static native void runMain(String[] args);
private void start() {
Fiber former = current;
current = this;
while (true) {
runner.run();
if (!isPendingResume) {
break;
}
isPendingResume = false;
state = STATE_RESUMING;
}
current = former;
if (!isSuspending() && !daemon && --userThreadCount == 0) {
EventQueue.stop();
}
}
void resume() {
state = STATE_RESUMING;
start();
}
public interface FiberRunner {
void run();
}
public interface AsyncCall {
void run(AsyncCallback<?> callback);
}
static class PendingCall {
AsyncCall value;
PendingCall next;
PendingCall previous;
AsyncCallbackImpl callback;
PendingCall(AsyncCall value, PendingCall previous) {
this.value = value;
this.next = null;
this.previous = previous;
}
}
public static class PlatformObjectWrapper {
public final PlatformObject object;
PlatformObjectWrapper(PlatformObject object) {
this.object = object;
}
}
public static class PlatformFunctionWrapper {
public final PlatformFunction object;
PlatformFunctionWrapper(PlatformFunction object) {
this.object = object;
}
}
public static class PlatformExceptionWrapper {
public final PlatformException object;
PlatformExceptionWrapper(PlatformException object) {
this.object = object;
}
}
public static class PlatformObject {
}
public static class PlatformFunction {
}
public static class PlatformException {
}
// Incari: fibers on WebAssembly JavaScript Promise Integration (JSPI). A build with the
// system property incari.jspi set compiles no method as a coroutine (AsyncMethodFinder), and
// routes suspend and start here (tools/webbuild's JspiTransformer). Each fiber runs in its own
// call of the module's "teavm.jspi.run" export through WebAssembly.promising, and suspends by
// calling the "teavmJspi.await" import, wrapped in WebAssembly.Suspending, which hands the
// engine a promise: the engine keeps the fiber's whole stack and returns to whoever started
// the fiber, and resumes the stack once the promise settles. Nothing here is reachable
// without that routing, so other builds import nothing from teavmJspi.
public static final class Jspi {
private static FiberRunner[] runners = new FiberRunner[16];
private static boolean[] daemons = new boolean[16];
private static int[] freeIds = new int[16];
private static int freeCount;
private static int nextId;
private Jspi() {
}
public static void start(FiberRunner runner, boolean daemon) {
int id;
if (freeCount > 0) {
id = freeIds[--freeCount];
} else {
id = nextId++;
if (id == runners.length) {
runners = Arrays.copyOf(runners, id * 2);
daemons = Arrays.copyOf(daemons, id * 2);
freeIds = Arrays.copyOf(freeIds, id * 2);
}
}
runners[id] = runner;
daemons[id] = daemon;
Thread former = Thread.currentThread();
// Returns when the fiber ends or first suspends.
runFiber(id);
setCurrentThread(former);
}
@Export(name = "teavm.jspi.run")
public static void run(int id) {
FiberRunner runner = runners[id];
boolean daemon = daemons[id];
runners[id] = null;
freeIds[freeCount++] = id;
runner.run();
if (!daemon && --userThreadCount == 0) {
EventQueue.stop();
}
}
public static Object suspend(AsyncCall call) throws Throwable {
Thread javaThread = Thread.currentThread();
Callback callback = new Callback();
callback.promise = createPromise();
call.run(callback);
if (!callback.done) {
// Completed later, from a callback: wait for it with the stack kept.
callback.waiting = true;
if (awaitPromise(callback.promise) != 0) {
// The page is going away. The engine never frees a suspended stack, nor
// anything it reaches (the whole program), so every fiber is resumed to end
// here: a trap, which no Java handler can catch, unwinds the fiber's stack.
Address.fromInt(-1).getInt();
}
setCurrentThread(javaThread);
} else {
dropPromise(callback.promise);
}
if (callback.exception != null) {
throw callback.exception;
}
return callback.result;
}
static final class Callback implements AsyncCallback<Object> {
int promise;
boolean done;
boolean waiting;
Object result;
Throwable exception;
@Override
public void complete(Object result) {
if (done) {
return;
}
done = true;
this.result = result;
if (waiting) {
resolvePromise(promise);
}
}
@Override
public void error(Throwable e) {
if (done) {
return;
}
done = true;
exception = e;
if (waiting) {
resolvePromise(promise);
}
}
}
@Import(module = "teavmJspi", name = "create")
private static native int createPromise();
/** Waits for the promise; nonzero when the page is going away and the fiber must end. */
@Import(module = "teavmJspi", name = "await")
private static native int awaitPromise(int promise);
@Import(module = "teavmJspi", name = "resolve")
private static native void resolvePromise(int promise);
@Import(module = "teavmJspi", name = "drop")
private static native void dropPromise(int promise);
@Import(module = "teavmJspi", name = "run")
private static native void runFiber(int id);
}
}
@@ -0,0 +1,116 @@
package incari.tools.teavmpatches;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.teavm.classlib.java.util.TFormatter;
/**
* Runs the patched {@link TFormatter} on the JVM and checks it against the JDK's own
* {@code String.format}. The browser build's {@code String.format} is this class.
*/
class FormatterTest {
private static final long MIB = 1024L * 1024L;
/** Integer conversions: widths, zero padding, the ',' flag, signs, and extreme values. */
static Object[][] decimalCases() {
return new Object[][] {
{"%d", new Object[] {Long.MIN_VALUE}},
{"%d", new Object[] {Long.MAX_VALUE}},
{"%d", new Object[] {Integer.MIN_VALUE}},
{"%d", new Object[] {Integer.MAX_VALUE}},
{"%d", new Object[] {(short) -32768}},
{"%d", new Object[] {(byte) -128}},
{"%d", new Object[] {-7L}},
{"%d", new Object[] {0}},
{"%25d", new Object[] {Long.MIN_VALUE}},
{"%-25d|", new Object[] {Long.MIN_VALUE}},
{"%025d", new Object[] {Long.MIN_VALUE}},
{"%(d", new Object[] {Long.MIN_VALUE}},
{"%+d %+d", new Object[] {5L, -5L}},
{"% d % d", new Object[] {5, -5}},
{"%03d", new Object[] {7L}},
{"%03d", new Object[] {-7L}},
{"%03d", new Object[] {123456L}},
{"%2d", new Object[] {100L}},
{"%,d", new Object[] {Long.MIN_VALUE}},
{"%,d", new Object[] {Long.MAX_VALUE}},
{"%,d", new Object[] {Integer.MIN_VALUE}},
{"%,d", new Object[] {-1234567}},
{"%,d", new Object[] {999}},
{"%,d", new Object[] {1000}},
{"%,15d|", new Object[] {-1234567L}},
{"%-,15d|", new Object[] {1234567L}},
{"%(,d", new Object[] {-1234567L}},
// Memory figures as a heap reports them, in bytes and in MiB.
{"%d %d", new Object[] {4_294_967_296L, 2_147_483_647L}},
{"%03d/%03d", new Object[] {4_294_967_296L / MIB, 2_147_483_647L / MIB}},
{"%03d", new Object[] {Long.MAX_VALUE / MIB}},
};
}
@ParameterizedTest
@MethodSource("decimalCases")
void formatsIntegersLikeTheJdk(String format, Object[] args) {
assertThat(teavm(format, args)).isEqualTo(String.format(Locale.ROOT, format, args));
}
/** '%%' and '%n' take no argument: the conversions after them read the right one. */
static Object[][] literalCases() {
return new Object[][] {
{"%d%%", new Object[] {50L}},
{"%2d%% %03d/%03d", new Object[] {3L, 120L, 4096L}},
{"%2d%% %03d", new Object[] {100L, 2048L}},
{"%%%d%%%s%%", new Object[] {1, "x"}},
{"%5%|%-5%|", new Object[] {}},
{"%d%n%d", new Object[] {1, 2}},
{"%s %<s %% %s", new Object[] {"a", "b"}},
};
}
@ParameterizedTest
@MethodSource("literalCases")
void literalsTakeNoArgument(String format, Object[] args) {
assertThat(teavm(format, args)).isEqualTo(String.format(Locale.ROOT, format, args));
}
@Test
void aMemoryLineFromRuntimeFiguresFormats() {
// What the debug screen computes from Runtime's figures, including the degenerate ones
// a heap without real numbers reports (everything free, nothing used).
long[][] figures = {
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE},
{4_294_705_152L, 268_435_456L, 12_582_912L},
{Long.MAX_VALUE, Long.MAX_VALUE, 0L},
};
for (long[] f : figures) {
long max = f[0];
long total = f[1];
long used = total - f[2];
Object[] args = {used * 100L / max, used / MIB, max / MIB};
String format = "Mem: %2d%% %03d/%03dMiB";
assertThat(teavm(format, args)).isEqualTo(String.format(Locale.ROOT, format, args));
}
}
@Test
void tooFewArgumentsStillFails() {
assertThatThrownBy(() -> teavm("%d %d", 1)).isInstanceOf(RuntimeException.class);
}
@Test
void percentRejectsPrecision() {
assertThatThrownBy(() -> teavm("%.2%")).isInstanceOf(RuntimeException.class);
}
private static String teavm(String format, Object... args) {
return new TFormatter(new StringBuilder(), Locale.ROOT)
.format(format, args)
.toString();
}
}
@@ -0,0 +1,99 @@
package incari.tools.teavmpatches;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.teavm.classlib.java.util.TSpliterator;
import org.teavm.classlib.java.util.stream.impl.TStreamOverSpliterator;
/**
* Runs the patched stream classes on the JVM. The tab list's {@code sorted().limit(80).toList()}
* over a fastutil set crashed: the sorted stream reported its drained source's size, 0, and
* {@code toArray} overflowed an array of that size.
*/
class StreamToArrayTest {
@Test
void sortedThenLimitedOverACountingDownSourceKeepsEveryElement() {
var stream = new TStreamOverSpliterator<>(new CountingDown<>(List.of(5, 3, 9, 1, 7)));
Object[] result = stream.sorted(Comparator.naturalOrder()).limit(80).toArray();
assertThat(result).containsExactly(1, 3, 5, 7, 9);
}
@Test
void sortedThenLimitedStopsAtTheLimit() {
var stream = new TStreamOverSpliterator<>(new CountingDown<>(List.of(5, 3, 9, 1, 7)));
Object[] result = stream.sorted(Comparator.naturalOrder()).limit(2).toArray();
assertThat(result).containsExactly(1, 3);
}
@Test
void anEstimateThatIsTooSmallStillFillsTheArray() {
var elements = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
var stream = new TStreamOverSpliterator<>(new Underestimating<>(elements));
Integer[] result = stream.toArray(Integer[]::new);
assertThat(result).containsExactlyElementsOf(elements);
}
/** Estimates what's left, as fastutil's hash set spliterators do. */
private static class CountingDown<T> implements TSpliterator<T> {
private final List<T> elements;
private int index;
CountingDown(List<T> elements) {
this.elements = elements;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
if (index == elements.size()) {
return false;
}
action.accept(elements.get(index++));
return true;
}
@Override
public @Nullable TSpliterator<T> trySplit() {
return null;
}
@Override
public long estimateSize() {
return (long) elements.size() - index;
}
@Override
public int characteristics() {
return SIZED;
}
}
/** Estimates one element, however many there are. */
private static final class Underestimating<T> extends CountingDown<T> {
Underestimating(List<T> elements) {
super(elements);
}
@Override
public long estimateSize() {
return 1;
}
@Override
public int characteristics() {
return 0;
}
}
}
@@ -0,0 +1,32 @@
package org.teavm.classlib.java.nio;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* The patched {@link TByteBuffer}'s absolute bulk put, on the JVM: it copies the range it's given
* from a source whose position is at its end (a buffer read through before), which TeaVM's skipped.
* The page's decoded sprites came out empty that way.
*/
class AbsoluteBulkPutTest {
@Test
void copiesFromASourceReadToItsEnd() {
TByteBuffer source = TByteBuffer.wrap(new byte[] {1, 2, 3, 4, 5});
source.position(source.limit());
TByteBuffer target = TByteBuffer.allocate(4);
target.put(1, source, 2, 3);
assertThat(target.array()).containsExactly(0, 3, 4, 5);
assertThat(source.position()).isEqualTo(5);
}
@Test
void anEmptyRangeCopiesNothing() {
TByteBuffer target = TByteBuffer.allocate(2);
target.put(0, TByteBuffer.wrap(new byte[0]), 0, 0);
assertThat(target.array()).containsExactly(0, 0);
}
}
@@ -0,0 +1,34 @@
package org.teavm.classlib.java.util;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/**
* The patched {@link TTemplateCollections}' map with no entries, on the JVM: looking a key up in it
* answered with a division by zero, which WebAssembly traps on (the End's biome sounds did
* it). In TeaVM's package, since the map class is package-private.
*/
class EmptyTemplateMapTest {
@Test
void anEmptyMapAnswersLookups() {
TTemplateCollections.NEtriesMap<String, String> empty = new TTemplateCollections.NEtriesMap<>();
assertThat(empty.get("anything")).isNull();
assertThat(empty.containsKey("anything")).isFalse();
assertThat(empty.entrySet().contains(new TTemplateCollections.ImmutableEntry<>("a", "b")))
.isFalse();
assertThat(empty.isEmpty()).isTrue();
}
@Test
void aFullMapStillFindsItsKeys() {
TTemplateCollections.NEtriesMap<String, Integer> map = new TTemplateCollections.NEtriesMap<>(
new TTemplateCollections.ImmutableEntry<>("a", 1), new TTemplateCollections.ImmutableEntry<>("b", 2));
assertThat(map.get("a")).isEqualTo(1);
assertThat(map.get("b")).isEqualTo(2);
assertThat(map.get("c")).isNull();
}
}
@@ -0,0 +1,57 @@
package org.teavm.classlib.java.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
/**
* The patched {@link TCollections}' unmodifiable views, on the JVM: they answer lookups by asking
* the collection they wrap rather than walking it (which made the game's model loading
* quadratic), and are still unmodifiable.
*/
class UnmodifiableViewsTest {
/** A map whose entry set can't be walked: a lookup that walks it fails the test. */
private static TMap<String, Integer> unwalkableMap() {
THashMap<String, Integer> map = new THashMap<>() {
@Override
public TSet<Entry<String, Integer>> entrySet() {
throw new AssertionError("walked the entry set");
}
};
map.put("a", 1);
map.put("b", 2);
return map;
}
@Test
void anUnmodifiableMapAsksTheMapItWraps() {
TMap<String, Integer> view = TCollections.unmodifiableMap(unwalkableMap());
assertThat(view.get("a")).isEqualTo(1);
assertThat(view.get("c")).isNull();
assertThat(view.containsKey("b")).isTrue();
assertThat(view.containsKey("c")).isFalse();
assertThat(view.size()).isEqualTo(2);
assertThat(view.isEmpty()).isFalse();
assertThatThrownBy(() -> view.remove("a")).isInstanceOf(UnsupportedOperationException.class);
}
@Test
void anUnmodifiableSetAsksTheSetItWraps() {
THashSet<String> set = new THashSet<>() {
@Override
public TIterator<String> iterator() {
throw new AssertionError("walked the set");
}
};
set.add("a");
TSet<String> view = TCollections.unmodifiableSet(set);
assertThat(view.contains("a")).isTrue();
assertThat(view.contains("b")).isFalse();
assertThat(view.isEmpty()).isFalse();
assertThat(TCollections.unmodifiableCollection(set).contains("a")).isTrue();
}
}