### Basic CMake Project Setup Source: https://github.com/konsoletyper/teavm/blob/master/tools/junit/src/main/resources/teavm-CMakeLists.txt Initializes CMake, sets the C standard, and defines the output directory for the runtime. This is a standard starting point for C projects using CMake. ```cmake cmake_minimum_required(VERSION 3.9) project(run_test C) set(CMAKE_C_STANDARD 11) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}) ``` -------------------------------- ### TeaVM Promise Example Main Method Source: https://github.com/konsoletyper/teavm/blob/master/samples/promise/src/main/webapp/index.html The main entry point for the TeaVM Promise example. It orchestrates the execution of various promise-related tests and functional interface demonstrations. ```java import java.util.Arrays; import org.teavm.jso.JSBody; import org.teavm.jso.browser.Window; import org.teavm.jso.core.JSArray; import org.teavm.jso.core.JSPromise; import org.teavm.jso.core.JSString; import org.teavm.jso.util.function.JSConsumer; import org.teavm.jso.util.function.JSFunction; import org.teavm.jso.util.function.JSSupplier; public final class PromiseExample { private static long start = System.currentTimeMillis(); private PromiseExample() { } public static void main(String[] args) throws InterruptedException { report(Arrays.toString(args)); report(""); checkFunctionalInterface(); runSimplePromise(); runComplexPromise(); final var lock = new Object(); runLongRunningPromise(lock); synchronized (lock) { report("Lock acquired"); lock.wait(20000); } combinePromises(lock); synchronized (lock) { report("Lock acquired"); lock.wait(20000); } testNativePromises(lock); report("Finished main thread"); } private static void report(String message) { var current = System.currentTimeMillis() - start; System.out.println("[" + Thread.currentThread().getName() + "]/" + current + ": " + message); } private static void checkFunctionalInterface() { JSSupplier supplier = () -> 23; JSFunction addTwenty = value -> value + 20; JSFunction subTwenty = value -> value - 20; JSFunction isPositive = value -> value >= 0; JSConsumer print = value -> report("My value: " + value.toString()); JSConsumer print2 = value -> report("My value plus 10: " + Integer.valueOf(value + 10).toString()); var value = supplier.get(); report("Supplied value: " + value.toString()); value = addTwenty.apply(value); report("Value plus 20: " + value.toString()); value = subTwenty.apply(value); report("Value minus 20: " + value.toString()); var value2 = isPositive.apply(value); report("Value is positive: " + value2.toString()); var subFourty = subTwenty.andThen(subTwenty); value = subFourty.apply(value); report("Value minus 40: " + value.toString()); var plusFourty = addTwenty.compose(addTwenty).andThen(addTwenty.compose(subTwenty)); value = plusFourty.apply(value); report("Value plus 40: " + value.toString()); value2 = subFourty.andThen(isPositive).apply(value); report("Value minus 40 is positive: " + value2.toString()); print.accept(value); var printExtended = print.andThen(print2); printExtended.accept(value); } private static void runSimplePromise() { var promise = JSPromise.create((resolve, reject) -> { report("Simple promise execution"); report("Resolving with 'success'"); resolve.accept("success"); }); } private static void runComplexPromise() { var promise = JSPromise.create((resolve, reject) -> { report("Complex promise execution"); report("Resolving with 'step1'"); resolve.accept("step1"); }) .then(value -> { report("Resolved with '" + value + "'"); report("... and resolve with 'step2'"); return "step2"; }) .then(value -> { report("Resolved with '" + value + "'"); report("... and throw exception"); throw new RuntimeException("Exception in promise handler"); }, reason -> { report("Failed unexpectedly with reason: " + reason.toString()); return reason.toString(); }) .then(value -> { report("Resolved unexpectedly with '" + value + "'"); return value; }, reason -> { report("Failed expectedly with reason: " + reason.toString()); return reason.toString(); }) .flatThen(value -> { report("Resolved with '" + value + "'"); report("... and resolve with resolved promise"); return JSPromise.resolve("step3"); }) .flatThen(value -> { report("Resolved with '" + value + "'"); report("... and resolve with rejected promise"); return JSPromise.reject("step4"); }) .catchError(reason -> { report("Catched reject reason '" + reason.toString() + "'"); ``` -------------------------------- ### Build and Run Native Linux Benchmark Source: https://github.com/konsoletyper/teavm/blob/master/samples/benchmark/README.md Execute this command on Linux to build and run the benchmark natively. Ensure cmake and gtk-devel are installed. ```bash $ gradle runNativeLinux ``` -------------------------------- ### KonsoleTyper Control Flow Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/irreduciblePhiLoop.original.txt Illustrates basic control flow using labels, goto statements, and phi functions for variable merging. This example demonstrates a loop structure with conditional exits. ```konsoleTyper var @this as this $start @init := 'qwe' @n := null @xInit := 0 goto $head $head @a := phi @init from $start, @b from $bodyEnd @x := phi @xInit from $start, @xUpdate from $bodyEnd @twenty := 20 @xCmp := @x compareTo @twenty as int if @xCmp == 0 then goto $exit else goto $body $body @ten := 10 @cmp := @x compareTo @ten as int if @cmp == 0 then goto $update else goto $bodyEnd $update goto $bodyEnd $bodyEnd @b := phi @a from $body, @n from $update @one := 1 @xUpdate := @x + @one as int goto $head $exit return ``` -------------------------------- ### Control Flow Example in Teavm Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/branch.extended.txt Demonstrates conditional logic and null checks within Teavm's intermediate representation. Use this for understanding basic control flow. ```teavm var @this as this $start @v := invokeStatic `Foo.get()LFoo;` if @v === null then goto $ifNull else goto $ifNotNull $ifNull invokeVirtual `Foo.bar()V` @v_1 @v_3 := nullCheck @v_1 goto $join $ifNotNull invokeVirtual `Foo.baz()V` @v_2 @v_4 := nullCheck @v_2 goto $join $join return // NULLABLE v // NULL v_1 // NOT_NULL v_3 ``` -------------------------------- ### Basic IR Control Flow Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/mergeInAliasAnalysis.original.txt This IR code initializes variables, accesses fields, uses conditional branching based on a field's value, and merges control flow using a phi node before assigning a value to a field and returning. It's a fundamental example of IR structure. ```ir var @this as this $start @o := new Foo @p := new Foo @q := new Foo @a := field Foo.intField @o as I @b := field Foo.intField @p as I @c := field Foo.intField @q as I if @a == 0 then goto $zero else goto $nonzero $zero goto $join $nonzero goto $join $join @j := phi @o from $zero, @p from $nonzero @v := 23 field Foo.intField @j := @v as I @a1 := field Foo.intField @o as I @b1 := field Foo.intField @p as I @c1 := field Foo.intField @q as I return ``` -------------------------------- ### KonsoleTyper Control Flow Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/irreduciblePhiLoop.extended.txt Illustrates basic KonsoleTyper syntax, including variable initialization, goto statements for control flow, phi nodes for merging values, and conditional branching. ```konsoleTyper var @this as this $start @init := 'qwe' @n := null @xInit := 0 goto $head $head @a := phi @init from $start, @b from $bodyEnd @x := phi @xInit from $start, @xUpdate from $bodyEnd @twenty := 20 @xCmp := @x compareTo @twenty as int if @xCmp == 0 then goto $exit else goto $body $body @ten := 10 @cmp := @x compareTo @ten as int if @cmp == 0 then goto $update else goto $bodyEnd $update goto $bodyEnd $bodyEnd @b := phi @a from $body, @n from $update @one := 1 @xUpdate := @x + @one as int goto $head $exit return // NULLABLE a // NULLABLE b ``` -------------------------------- ### KonsoleTyper IR Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/mergeInAliasAnalysis.expected.txt This snippet demonstrates basic KonsoleTyper IR constructs. It initializes variables, accesses fields, uses conditional branching, and assigns values. ```konsoletyper var @this as this $start @o := new Foo @p := new Foo @q := new Foo @a := field Foo.intField @o as I @b := field Foo.intField @p as I @c := field Foo.intField @q as I if @a == 0 then goto $zero else goto $nonzero $zero goto $join $nonzero goto $join $join @j := phi @o from $zero, @p from $nonzero @v := 23 field Foo.intField @j := @v as I @a1 := field Foo.intField @o as I @b1 := field Foo.intField @p as I @c1 := @c return ``` -------------------------------- ### TeaVM IR Control Flow Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/nonDominatedBranch.extended.txt Illustrates conditional branching and variable assignment within TeaVM's IR. Pay attention to null checks and phi nodes for merging values. ```java var @this as this $start @a := invokeStatic `Foo.f()LBar;` if @a === null then goto $joint else goto $ifNonNull $ifNonNull @b := invokeStatic `Foo.g()LBar;` if @b !== null then goto $joint else goto $ifNull $ifNull return @a_1 $joint @c := phi @a_2 from $start, @b_2 from $ifNonNull return @c // NULLABLE c // NULL a_2 // NOT_NULL a_1 ``` -------------------------------- ### KonsoleTyper Field Access Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/copy.original.txt Demonstrates how to declare a variable, assign values to its fields, and retrieve those values using KonsoleTyper syntax. Ensure variables are properly initialized before accessing their fields. ```konsole var @this as this $start @a := new A @tmp1 := 23 field A.foo @a := @tmp1 as I @b := @a @tmp2 := 42 field A.bar @b := @tmp2 as I @r := field A.foo @b as I @s := field A.bar @b as I return @r ``` -------------------------------- ### TeaVM Switch Statement Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/switchInsn.txt Demonstrates the basic structure of a switch statement in TeaVM assembly. Use this for conditional branching based on the value of a variable. ```teavm switch @a case 0 goto $0 case 1 goto $1 else goto $else $0 return @v0 $1 return @v1 $else return @default ``` -------------------------------- ### TeaVM Bytecode Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/alwaysInvalidateExternalObject.expected.txt This snippet demonstrates basic TeaVM bytecode operations including object instantiation, static method invocation, field access, and variable assignment. It shows how to interact with Java classes and fields within the TeaVM environment. ```teavm var @this as this $start @o := new Foo @p := new Foo @q := invokeStatic `Foo.getFoo()LFoo;` @a := field Foo.intField @p as I @b := field Foo.intField @q as I @v := 23 field Foo.intField @o := @v as I @a1 := @a @b1 := field Foo.intField @q as I return ``` -------------------------------- ### Basic Control Flow and Variable Assignment in TeaVM IR Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/util/phi-updater/exceptionPhi.expected.txt This snippet demonstrates basic control flow with labels like $start, $catch, and $end, along with static method invocation and variable assignment. It includes a try-catch block structure. ```java @a := invokeStatic `Foo.bar()I` @a_1 := invokeStatic `Foo.baz()I` goto $end catch java.lang.RuntimeException goto $catch $catch @a_2 := phi @a from $start, @a_1 from $start @b := 1 @a_3 := @a_2 + @b as int goto $end $end @a_4 := phi @a_1 from $start, @a_3 from $catch return @a_4 ``` -------------------------------- ### TeaVM Field Access Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/simple.expected.txt Demonstrates accessing and modifying fields of an object in TeaVM. Ensure the 'Foo' class and 'intField' are accessible. ```teavm var @this as this $start @o := new Foo @a := field Foo.intField @o as I @b := @a @c := 23 field Foo.intField @o := @c as I @d := @c return ``` -------------------------------- ### Working with Thai Buddhist Dates and Available Calendars Source: https://github.com/konsoletyper/teavm/blob/master/classlib/src/main/java/org/threeten/bp/chrono/package.html Demonstrates how to get the current date in the Thai Buddhist calendar, extract date components, enumerate all available calendar systems and print their current dates, and calculate the first and last day of a year in a specific calendar. ```java // Print the Thai Buddhist date ChronoLocalDate now1 = ThaiBuddhistChronology.INSTANCE.now(); int day = now1.get(ChronoField.DAY_OF_MONTH); int dow = now1.get(ChronoField.DAY_OF_WEEK); int month = now1.get(ChronoField.MONTH_OF_YEAR); int year = now1.get(ChronoField.YEAR); System.out.printf(" Today is %s %s %d-%s-%d%n", now1.getChronology().getId(), dow, day, month, year); // Enumerate the list of available calendars and print today for each Set names = Chronology.getAvailableIds(); for (String name : names) { Chronology chrono = Chronology.of(name); ChronoLocalDate date = chrono.now(); System.out.printf(" %20s: %s%n", chrono.getId(), date.toString()); } // Print today's date and the last day of the year for the Thai Buddhist Calendar. ChronoLocalDate first = now1 .with(ChronoField.DAY_OF_MONTH, 1) .with(ChronoField.MONTH_OF_YEAR, 1); ChronoLocalDate last = first .plus(1, ChronoUnit.YEARS) .minus(1, ChronoUnit.DAYS); System.out.printf(" %s: 1st of year: %s; end of year: %s%n", last.getChronology().getId(), first, last); ``` -------------------------------- ### Conditional Branching and Phi Node Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/util/phi-updater/phiIncoming.expected.txt This snippet demonstrates conditional logic using labels and goto statements, culminating in a phi node to select a value based on the execution path. It is written in a custom intermediate language. ```custom var @this as this $start @cond := invokeStatic `Foo.bar()I` if @cond == 0 then goto $zero else goto $nonzero $zero @a := 0 goto $joint $nonzero @b := 1 @b_1 := 2 goto $joint $joint @c := phi @a from $zero, @b_1 from $nonzero return @c ``` -------------------------------- ### TeaVM IR Control Flow Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/phiPropagation.extended.txt This snippet demonstrates conditional branching and control flow within the TeaVM IR. It handles different conditions for string extraction and processing. ```java var @this as this $start @a := invokeStatic `Value.extract()Ljava/lang/String;` @cond := invokeStatic `Cond.invoke()I` if @cond == 0 then goto $if0 else goto $else $if0 @len := invokeStatic `Value.extractLen()I` if @len == 0 then goto $ifEmpty else goto $ifNotEmpty $ifEmpty invokeStatic `Foo.f(Ljava/lang/String;)V` @a goto $joinIf0 $ifNotEmpty invokeVirtual `java.lang.String.trim()Ljava/lang/String;` @a @a_1 := nullCheck @a goto $joinIf0 $joinIf0 @a_2 := phi @a from $ifEmpty, @a_1 from $ifNotEmpty invokeStatic `Foo.g(Ljava/lang/String;)V` @a_2 goto $join $else invokeStatic `Foo.bar(Ljava/lang/String;)V` @a goto $join $join @a_3 := phi @a_2 from $joinIf0, @a from $else invokeStatic `Foo.baz(Ljava/lang/String;)V` @a_3 return ``` -------------------------------- ### KonsoleTyper IR Example Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/escapingPhiSource.original.txt This snippet demonstrates the KonsoleTyper intermediate representation (IR) syntax. It showcases conditional branching, object creation, field assignment, and return values. Use this IR for defining program logic before code generation. ```konsole var @this as this $start @cond := invokeStatic `Foo.bar()I` if @cond == 0 then goto $zero else goto $nonzero $zero @a := new A @tmp1 := null field A.foo @a := @tmp1 as `Ljava/lang/Object;` goto $joint $nonzero @b := new B @tmp2 := 23 field B.bar @b := @tmp2 as I field B.boo @b := @tmp2 as I field B.s := @b as `LB;` goto $joint $joint @c := phi @a from $zero, @b from $nonzero @tmp3 := 12.0F field C.baz @c := @tmp3 as F @r := field B.bar @c as I return @r ``` -------------------------------- ### Invoke Static Method and Parse Integer Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/exception.extended.txt This snippet demonstrates invoking a static method to get a string and then parsing it into an integer. It includes basic error handling for runtime exceptions. ```KonsoleTyper var @this as this $start @str := invokeStatic `Foo.getData()Ljava/lang/String;` @n := invokeStatic `java.lang.Integer.parseInt(Ljava/lang/String;)I` @str return @n catch java.lang.RuntimeException goto $handle $handle @e := exception @m := invoke `java.lang.Throwable.getMessage()Ljava/lang/String;` @e @z := invoke `java.lang.String.length()I` @m @m_1 := nullCheck @m return @z ``` -------------------------------- ### Accessing and Reading Fields in TeaVM Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/invocationInvalidates.original.txt This snippet demonstrates how to invoke a static method to get an object instance and then access its fields. Ensure the `Foo` class and its `intField` are accessible. ```teavm var @this as this $start @o := invokeStatic `Foo.getFoo()LFoo;` @a := field Foo.intField @o as I invokeStatic `Foo.getFoo()LFoo;` @b := field Foo.intField @o as I return ``` -------------------------------- ### Pass Java Promises to Native Methods Source: https://github.com/konsoletyper/teavm/blob/master/samples/promise/src/main/webapp/index.html This snippet demonstrates passing promises created in Java using `JSPromise.create` to native JavaScript methods for handling. It shows examples of both resolving and rejecting promises from the Java side. ```Java handlePromise(JSPromise.create((resolve, reject) -> { resolve.accept(JSString.valueOf("Resolved from Java")); })); handlePromise(JSPromise.create((resolve, reject) -> { reject.accept(JSString.valueOf("Rejected from Java")); })); ``` -------------------------------- ### Field Assignment and Method Invocation in TeaVM Bytecode Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/readAfterException.expected.txt This snippet demonstrates invoking static methods to get an object and an integer, then assigning the integer to a field of the object. It includes basic control flow with goto and exception handling. ```bytecode var @this as this $start @o := invokeStatic `Foo.getFoo()LFoo;` @v := invokeStatic `Foo.getIntValue()I` field Foo.intField @o := @v as I goto $exit catch java.lang.RuntimeException goto $handler $handler goto $exit $exit @x := field Foo.intField @o as I return ``` -------------------------------- ### Build and Run Web Benchmark Source: https://github.com/konsoletyper/teavm/blob/master/samples/benchmark/README.md Use this command to build the application and run the web-based benchmark, comparing TeaVM and GWT JavaScript outputs. ```bash $ gradle appStartWar ``` -------------------------------- ### Configure C Project Build with CMake Source: https://github.com/konsoletyper/teavm/blob/master/samples/pi/CMakeLists.txt Sets up the C project, specifies the C standard, and defines the runtime output directory. Ensures a Release build type if not specified. ```cmake cmake_minimum_required(VERSION 3.9) project(calc_pi C) set(CMAKE_C_STANDARD 11) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build/dist) if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3") ``` -------------------------------- ### JavaScript for PI Calculation Source: https://github.com/konsoletyper/teavm/blob/master/samples/pi/src/main/webapp/js.html This JavaScript function is triggered by a button click to get the digit count from an input field and initiate the PI calculation. ```javascript function calculate() { var count = parseInt(document.getElementById("digit-count").value); main([count.toString()]); } ``` -------------------------------- ### Build TeaVM with Gradle Source: https://github.com/konsoletyper/teavm/blob/master/README.md Clone the source code and use Gradle to build and publish TeaVM to your local Maven repository. Samples should be built separately. ```bash git clone https://github.com/konsoletyper/teavm.git ./gradlew publishToMavenLocal ``` ```bash gradlew.bat publishToMavenLocal ``` -------------------------------- ### Field Access and Assignment in TeaVM Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/fieldStoreInDifferentObjects.original.txt Demonstrates how to instantiate objects, access fields, and assign values to fields within the TeaVM environment. Ensure the 'Foo' class and its 'intField' are properly defined. ```java var @this as this $start @o := new Foo @p := new Foo @a := field Foo.intField @o as I @v := 23 field Foo.intField @p := @v as I @b := field Foo.intField @o as I return ``` -------------------------------- ### Java String and Array Initialization in TeaVM Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/create.txt Demonstrates the initialization of a Java String object and two types of arrays (String array and integer array) within a TeaVM context. Note the use of specific TeaVM syntax for array creation. ```java @a := new java.lang.String @b := newArray `Ljava/lang/String;` [@size] @c := newArray I [@h, @w] return ``` -------------------------------- ### Basic Variable Assignment and Return Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/copy.expected.txt This snippet demonstrates basic variable assignment, including copying values between variables and returning a final result. It uses a custom scripting syntax. ```konsole var @this as this $start @a$foo := 0 @a$bar := 0 @tmp1 := 23 @a$foo_1 := @tmp1 @b$foo := @a$foo_1 @b$bar := @a$bar @tmp2 := 42 @b$bar_1 := @tmp2 @r := @b$foo @s := @b$bar_1 return @r ``` -------------------------------- ### Get Next Monday using TemporalAdjusters Source: https://github.com/konsoletyper/teavm/blob/master/classlib/src/main/java/org/threeten/bp/temporal/package.html Find the first occurrence of a specific day of the week, such as Monday, after a given date. This utilizes the TemporalAdjusters class for date-time adjustments. ```java date.with(next(MONDAY)) ``` -------------------------------- ### Basic Assembly Operations in TeaVM Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/simple.txt Demonstrates variable declaration, assignment, array manipulation, and control flow (goto) within a TeaVM assembly-like syntax. Ensure variables are declared before use and types are specified for assignments. ```assembly var @a as a_debug var @b as b_debug // it's a simple comment $first nop @a_1 := @a @a_1[@b] := @c as int goto $second $second return @c ``` -------------------------------- ### Get Aligned Week of Month using ChronoField Source: https://github.com/konsoletyper/teavm/blob/master/classlib/src/main/java/org/threeten/bp/temporal/package.html Retrieve the aligned week of the month for a given date using the ChronoField enum. This is useful for less common fields where convenience methods are not available. ```java date.get(ChronoField.ALIGNED_WEEK_OF_MONTH) ``` -------------------------------- ### Variable Declaration and Field Assignment in TeaVM Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/fieldStoreInDifferentObjects.expected.txt Demonstrates variable declaration, object instantiation, and field assignment using TeaVM's syntax. Ensure Foo class is defined with an intField. ```teavm var @this as this $start @o := new Foo @p := new Foo @a := field Foo.intField @o as I @v := 23 field Foo.intField @p := @v as I @b := @a return ``` -------------------------------- ### Conditional Branching and Phi Operation Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/phi.txt Demonstrates conditional branching using goto statements and the phi operation for selecting values based on control flow. Ensure parameters are correctly defined before execution. ```konsole if @param == 0 then goto $whenzero else goto $whennonzero $whenzero goto $joint $whennonzero goto $joint $joint @u := phi @a from $whenzero, @b from $whennonzero @v := phi @x from $whenzero, @y from $whennonzero @result := @u + @v as int return @result ``` -------------------------------- ### Basic Control Flow with Exception Handling Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/exceptions.txt This snippet demonstrates basic control flow in KonsoleTyper, including variable assignment, static method invocation, and exception handling using `catch` and `goto`. ```KonsoleTyper @a_1 := 0 invokeStatic `foo.Bar.baz()I` @a_2 := 1 invokeStatic `foo.Bar.baz()I` @a_3 := 2 return @a_3 catch java.lang.Exception goto $handler $handler @a_h := phi @a_1 from $start, @a_2 from $start, @a_3 from $start @e := exception @out := field `java.lang.String.out` as `Ljava/io/PrintStream;` invokeVirtual `java.io.PrintStream.println(Ljava/lang/Object;)V` @out, @e return @a_h ``` -------------------------------- ### CMake Build Configuration for TeaVM C Benchmark Source: https://github.com/konsoletyper/teavm/blob/master/samples/benchmark/CMakeLists.txt This CMakeLists.txt file sets up the build environment for the TeaVM C benchmark. It configures C standards, output paths, build types (Debug/Release), finds and links GTK+ 3 libraries, and defines the executable target. ```cmake cmake_minimum_required(VERSION 3.9) project(teavm_benchmark C) set(CMAKE_C_STANDARD 11) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/build/dist/) if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3") find_package(PkgConfig REQUIRED) pkg_check_modules(GTK3 REQUIRED gtk+-3.0) include_directories(${GTK3_INCLUDE_DIRS}) link_directories(${GTK3_LIBRARY_DIRS}) add_definitions(${GTK3_CFLAGS_OTHER}) add_executable(teavm_benchmark build/generated/teavm-c/all.c) target_link_libraries(teavm_benchmark ${GTK3_LIBRARIES} m rt) ``` -------------------------------- ### Initialize Deobfuscator in Browser Source: https://github.com/konsoletyper/teavm/blob/master/tools/browser-runner/src/main/resources/test-server/index.html Imports a deobfuscator function and exposes it globally. Assumes 'LOGGING' and 'DEOBFUSCATION' are defined elsewhere, possibly as build-time variables. ```javascript import { create } from './deobfuscator.js' window.createDeobfuscator = create; logging = "{{LOGGING}}"; deobfuscation = "{{DEOBFUSCATION}}"; tryConnect(); ``` -------------------------------- ### Traverse Linked List in TeaVM IR Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/loop.original.txt This IR code traverses a linked list, accessing fields like 'first', 'last', 'next', and 'value'. It handles null checks and uses control flow labels like $start, $head, $body, and $exit. ```ir var @this as this $start @first := field `Foo.first` @this as `LBar;` @checkedFirst := nullCheck @first goto $head $head @current := phi @checkedFirst from $start, @checkedNext from $body @isLast := field `Bar.last` @current as Z if @isLast == 0 then goto $exit else goto $body $body @next := field `Bar.next` @current as `LBar;` @checkedNext := nullCheck @next goto $head $exit @value := field `Bar.value` @current as `Ljava/lang/Object;` return @value ``` -------------------------------- ### Linked List Traversal and Value Extraction Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/analysis/nullness/loop.extended.txt This code defines a control flow for traversing a linked list. It starts by initializing a field, then enters a loop that checks for the last element. If it's not the last element, it proceeds to the next. Finally, it extracts the value from the current element. ```konsole var @this as this $start @first := field `Foo.first` @this as `LBar;` @checkedFirst := nullCheck @first goto $head $head @current := phi @checkedFirst from $start, @checkedNext from $body @isLast := field `Bar.last` @current as Z @current_2 := nullCheck @current if @isLast == 0 then goto $exit else goto $body $body @next := field `Bar.next` @current_2 as `LBar;` @checkedNext := nullCheck @next goto $head $exit @value := field `Bar.value` @current_2 as `Ljava/lang/Object;` return @value // NOT_NULL current // NOT_NULL current_2 ``` -------------------------------- ### Launch jbox2d Benchmark with TeaVM WASM GC Source: https://github.com/konsoletyper/teavm/blob/master/samples/benchmark/src/main/webapp/teavm-wasm-gc.html Use this function to load the WebAssembly module for the jbox2d benchmark and initiate its execution. Ensure the 'wasm-gc/benchmark.wasm' file is accessible. ```javascript function launch() { TeaVM.wasmGC.load("wasm-gc/benchmark.wasm", { stackDeobfuscator: { enabled: true } }).then(teavm => teavm.exports.main(\[\])); } ``` -------------------------------- ### Import and Call JavaScript Module Functions Source: https://github.com/konsoletyper/teavm/blob/master/samples/module-test/src/main/webapp/index.html Imports 'foo' and 'bar' from a local JavaScript module and sets up event listeners for buttons to call these functions. Ensure the HTML has elements with IDs 'foo', 'bar', and 'bar-arg'. ```javascript import { foo, bar } from "./js/module-test.js" document.body.onload = () => { let fooButton = document.getElementById("foo"); fooButton.onclick = () => { foo(); } let barButton = document.getElementById("bar"); let barArgInput = document.getElementById("bar-arg"); barButton.onclick = () => { alert(bar(parseInt(barArgInput.value))); } }; ``` -------------------------------- ### Pseudocode for Array Copy with Gotos Source: https://github.com/konsoletyper/teavm/wiki/Decompilation This pseudocode demonstrates an array copying function using goto statements, which is a precursor to generating structured JavaScript. ```javascript function arrayCopy(arr, len) { $0: copy = new Array(len); copyLen = len; origLen = length(arr); if (copyLen > origLen) { goto $1; } else { goto $2; } $1: copyLen = origLen; goto $2; $2: i = 0; goto $3; $3: if (i < copyLen) { goto $4; } else { goto $5; } $4: elt = arr[i]; copy[i] = elt; tmp = 1; i = i + tmp; goto $3; $5: return copy; } ``` -------------------------------- ### Variable Assignment and Return Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/simple.expected.txt Demonstrates basic variable assignment, including null, integer, and string types, and returning a variable. This snippet is written in a custom scripting language. ```custom var @this as this $start @x$foo := null @x$bar := 0 @a := 'qwe' @x$foo_1 := @a @b := 123 @x$bar_1 := @b @y := @x$bar_1 return @y ``` -------------------------------- ### Conditional Branching and Variable Assignment in TeaVM IR Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/reachabilityByClasses.expected.txt Demonstrates conditional logic, variable initialization, and phi node usage for merging values from different control flow paths in TeaVM IR. ```java var @this as this $start @cond := invokeStatic `Foo.cond()I` if @cond == 0 then goto $then1 else goto $else1 $then1 @a1_then := new A @foo1 := 23 field A.foo @a1_then := @foo1 as I goto $joint1 $else1 @a1_else := new A @foo2 := 42 field A.foo @a1_else := @foo2 as I goto $joint1 $joint1 @a1 := phi @a1_then from $then1, @a1_else from $else1 @a2 := @a1 if @cond == 0 then goto $then2 else goto $else2 $then2 @a3_then := new A goto $joint2 $else2 @a3_else := @a2 goto $joint2 $joint2 @a3 := phi @a3_then from $then2, @a3_else from $else2 invokeStatic `Foo.accept(LA;)V` @a3 return ``` -------------------------------- ### Build Class Library Compatibility Report Source: https://github.com/konsoletyper/teavm/blob/master/README.md Use the Gradle task to build a Java class library compatibility report. The result is located in the specified directory. ```bash ./gradlew :tools:classlib-comparison-gen:build ``` -------------------------------- ### Conditional Branching and Object Initialization in TeaVM IR Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/scalar-replacement/escapingSharedPhiSource.expected.txt This snippet demonstrates conditional branching based on a method's return value. It initializes different objects and sets fields based on the condition, merging control flow at the end. ```ir var @this as this $start @cond := invokeStatic `Foo.bar()I` if @cond == 0 then goto $zero else goto $nonzero $zero @a := new A @tmp1 := null field A.foo @a := @tmp1 as `Ljava/lang/Object;` goto $joint $nonzero @b := new B @tmp2 := 23 field B.bar @b := @tmp2 as I field B.boo @b := @tmp2 as I @x := new B goto $joint $joint @c := phi @a from $zero, @b from $nonzero @d := phi @a from $zero, @x from $nonzero @tmp3 := 12.0F field C.baz @c := @tmp3 as F @r := field B.bar @c as I return @r ``` -------------------------------- ### Worker Initialization and Message Handling Source: https://github.com/konsoletyper/teavm/blob/master/samples/wasm-sab/src/main/webapp/index.html Sets up a Web Worker and defines message handling logic. It expects an 'init' message containing a SharedArrayBuffer and processes 'update' messages, using Atomics.load for memory synchronization. ```javascript async function waitLoop(buffer) { while (true) { } } let buffer; function launch() { let worker = new Worker("worker.js"); worker.onmessage = async e => { switch (e.data.type) { case "init": console.log("Received buffer from worker"); buffer = e.data.buffer; break; case "update": // memory fence Atomics.load(buffer, 0); console.log("Value in buffer: " + buffer[1]); break; } }; } ``` -------------------------------- ### Load and Run Kotlin WASM Module Source: https://github.com/konsoletyper/teavm/blob/master/samples/kotlin/src/main/webapp/index-wasm.html This snippet shows how to load a WASM module compiled from Kotlin and execute its main function. Ensure the 'wasm-gc/kotlin.wasm' path is correct and the necessary TeaVM configuration is applied. ```javascript async function main() { let module = await TeaVM.wasmGC.load("wasm-gc/kotlin.wasm", { stackDeobfuscator: { enabled: true } }); module.exports.main([]); } ``` -------------------------------- ### Main Application Logic Source: https://github.com/konsoletyper/teavm/blob/master/samples/async/src/main/webapp/index.html The main method orchestrates the execution of various asynchronous and synchronous tasks, including thread creation and synchronization. ```java public final class AsyncProgram { private static long start = System.currentTimeMillis(); private AsyncProgram() { } public static void main(String[] args) throws InterruptedException { report(Arrays.toString(args)); findPrimes(); withoutAsync(); report(""); withAsync(); report(""); final Object lock = new Object(); new Thread(() -> { try { doRun(lock); } catch (InterruptedException ex) { report("Exception caught: " + ex.getMessage()); } }, "Test Thread").start(); new Thread(() -> { try { doRun(lock); } catch (InterruptedException ex) { report("Exception caught: " + ex.getMessage()); } }, "Test Thread 2").start(); report("Should be main"); report("Now trying wait..."); synchronized (lock) { report("Lock acquired"); lock.wait(20000); } report("Finished main thread"); } private static void findPrimes() { report("Finding primes"); boolean[] prime = new boolean[1000]; prime[2] = true; prime[3] = true; nextPrime: for (int i = 5; i < prime.length; i += 2) { int maxPrime = (int) Math.sqrt(i); for (int j = 3; j <= maxPrime; j += 2) { Thread.yield(); if (prime[j] && i % j == 0) { continue nextPrime; } } prime[i] = true; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; ++i) { if (prime[i]) { sb.append(i).append(' '); } } report(sb.toString()); } private static void report(String message) { long current = System.currentTimeMillis() - start; System.out.println("[" + Thread.currentThread().getName() + "]/" + current + ": " + message); } private static void doRun(Object lock) throws InterruptedException { report("Executing timer task"); Thread.sleep(2000); report("Calling lock.notify()"); synchronized (lock) { lock.notify(); } report("Finished calling lock.notify()"); report("Waiting 5 seconds"); Thread.sleep(5000); report("Finished another 5 second sleep"); synchronized (lock) { report("Sleep inside locked section"); Thread.sleep(2000); report("Finished locked section"); } } private static void withoutAsync() { report("Start sync"); for (int i = 0; i < 20; ++i) { StringBuilder sb = new StringBuilder(); for (int j = 0; j <= i; ++j) { sb.append(j); sb.append(' '); } report(sb.toString()); } report("Complete sync"); } private static void withAsync() throws InterruptedException { report("Start async"); for (int i = 0; i < 20; ++i) { StringBuilder sb = new StringBuilder(); for (int j = 0; j <= i; ++j) { sb.append(j); sb.append(' '); } report(sb.toString()); if (i % 3 == 0) { report("Suspend for a second"); Thread.sleep(1000); } } report("2nd Thread.sleep in same method"); Thread.sleep(1000); report("Throwing exception"); try { throwException(); } catch (IllegalStateException e) { report("Exception caught"); } report("Complete async"); } private static void throwException() { Thread.yield(); report("Thread.yield called"); throw new IllegalStateException(); } } ``` -------------------------------- ### Handle Exceptions in KonsoleTyper Bytecode Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/util/phi-updater/exceptionPhi.original.txt This snippet demonstrates exception handling using 'catch' and 'goto' for control flow. It initializes a variable, attempts a static invocation, and if a RuntimeException occurs, it adds 1 to the variable before returning. ```konsoleTyper @a := invokeStatic `Foo.bar()I` @a := invokeStatic `Foo.baz()I` goto $end catch java.lang.RuntimeException goto $catch $catch @b := 1 @a := @a + @b as int goto $end $end return @a ``` -------------------------------- ### Combining Promises with JSPromise.any (All Failures) Source: https://github.com/konsoletyper/teavm/blob/master/samples/promise/src/main/webapp/index.html Demonstrates `JSPromise.any` when all input promises are rejected. The resulting promise will reject with an aggregate error containing all rejection reasons. ```java report("Start 3 rejected promises"); promises.set(0, JSPromise.reject("failure1")); promises.set(1, JSPromise.reject("failure2")); promises.set(2, JSPromise.reject("failure3")); anyPromise = JSPromise.any(promises); anyPromise.then(value -> { report("At least one promise resolved to: " + value); return "success"; }, reason -> { report("All promises rejected with: " + reason.toString()); return "failure"; }).onSettled(() -> { synchronized (lock) { lock.notify(); } return null; }); synchronized (lock) { report("Lock acquired"); lock.wait(20000); } ``` -------------------------------- ### TeaVM Bytecode for Field Manipulation Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/optimization/repeated-field-read-elimination/fieldStoreInvalidates.expected.txt This snippet illustrates fetching two instances of 'Foo', accessing and reading an integer field from the first instance, assigning a new value to the same field in the second instance, and then reading the field from the first instance again. ```teavm var @this as this $start @o := invokeStatic `Foo.getFoo()LFoo;` @p := invokeStatic `Foo.getFoo()LFoo;` @a := field Foo.intField @o as I @v := 23 field Foo.intField @p := @v as I @b := field Foo.intField @o as I return ``` -------------------------------- ### Declare and Initialize Variables in KonsoleTyper Source: https://github.com/konsoletyper/teavm/blob/master/core/src/test/resources/model/text/constant.txt Demonstrates the declaration and initialization of various variable types including integers, long integers, floats, doubles, strings with escape characters, and class types. The snippet concludes with a return statement. ```java @a := 23 @b := 42L @c := 3.14159F @d := 2.71828 @e := 'foo\'bar\nbaz\\boo\u0000123' @f := classOf `[Ljava/lang/String;` return @a ``` -------------------------------- ### Combining Promises with JSPromise.all (Mixed Success/Failure) Source: https://github.com/konsoletyper/teavm/blob/master/samples/promise/src/main/webapp/index.html Demonstrates `JSPromise.all` with a mix of successful and rejected promises. The `all` promise will reject if any of the input promises reject. ```java report("Start 1 successful and 2 rejected promise"); promises.set(0, JSPromise.resolve("success1")); promises.set(1, JSPromise.reject("failure2")); promises.set(2, JSPromise.reject("failure3")); allPromises = JSPromise.all(promises); allPromises.then(value -> { report("All promises resolved to: " + value); return "success"; }, reason -> { report("At least one promise rejected with: " + reason.toString()); return "failure"; }).onSettled(() -> { synchronized (lock) { lock.notify(); } return null; }); synchronized (lock) { report("Lock acquired"); lock.wait(20000); } ```