Tern

iOS and Android

Tern compiles for iPhones and iPads (arm64 devices and the iOS Simulator) and for Android (arm64 and x86-64). This guide shows what you need installed, how to build command-line programs and libraries for each platform, how Swift and Kotlin/Java call a Tern library, and how the runtime behaves inside an app: when it starts, which threads may call it, and what happens on a runtime error. The examples come from examples/mobile/ in the repository, and tern run tests/runner/main.tn -- run --mobile runs them.

The targets

Pick a platform with --target:

--targetBuilds forC toolchain
iosiPhone / iPad, arm64, iOS 15.0 or laterXcode (xcrun --sdk iphoneos clang)
ios-simthe iOS Simulator on an Apple-silicon MacXcode (xcrun --sdk iphonesimulator clang)
android (or android-arm64)Android arm64, API level 24 or laterthe Android NDK
android-x86_64x86-64 Android (emulators on Intel machines, Chromebooks)the Android NDK

What each one needs:

  • iOS: Xcode, with an iOS Simulator runtime installed if you use ios-sim (Xcode > Settings > Components). tern calls xcrun, so the command-line tools must point at Xcode.
  • Android: the NDK. tern uses $ANDROID_NDK_HOME (or $ANDROID_NDK_ROOT), and otherwise the newest version under $ANDROID_HOME/ndk/ (default ~/Library/Android/sdk/ndk/). Running programs also needs adb (the SDK's platform-tools) and a connected device or a running emulator.

Your Tern code doesn't change between targets. The same program builds everywhere, and the race checks and everything else in the language are the same. This one runs as is on your machine, and unchanged on a phone:

fn main():
    squares = [0] * 8
    parallel for i in 0..len(squares):
        squares[i] = i * i
    total = 0
    for s in squares:
        total += s
    print("squares", squares, "total", total)
Output
squares [0, 1, 4, 9, 16, 25, 36, 49] total 140

Command-line programs

build and run take --target like any other flag:

tern run   --target ios-sim squares.tn                        # build, then run in the booted Simulator
tern build --target ios     squares.tn -o squares              # an arm64 iOS executable
tern run   --target android squares.tn                        # build, push with adb, run, clean up
tern build --target android squares.tn -o squares              # an arm64 Android (ELF) executable

What run does on each target:

  • ios-sim: if no Simulator is booted, it boots one (the last iPhone in xcrun simctl list, or the device whose UDID is in $TERN_IOS_DEVICE), then runs the program with xcrun simctl spawn booted. TERN_* environment variables such as TERN_STATS=1 are passed through.
  • android: it pushes the binary to /data/local/tmp with adb, runs it there (again passing TERN_* variables), prints its output, and deletes it. If no device or emulator is connected, it says so; start one first, for example emulator -avd Pixel_9a -no-window & then adb wait-for-device.
  • ios: a device build can't run on the Mac. tern refuses and suggests ios-sim, or building a library and linking it into an Xcode app.

Exit codes work as on the desktop: a runtime error prints runtime error in f (prog.tn:N): ... and the program exits with status 2, on the Simulator and on Android alike.

Command-line programs are mostly for testing. On a phone, Tern code normally lives inside an app, as a library.

Libraries for apps

A library is a .tn file with export fn functions. Only int, float, bool, and str cross in and out; the rest of the program uses any types it likes. See Calling C, and Tern as a library for the full rules; this section is the mobile side of it.

A library may also have a fn main(). build --lib leaves it out of the library (it isn't exported), so you can test the library's functions from the desktop with tern run:

struct Stats:
    count: int
    best: int

fn parse(csv: str) [int]:
    out: [int] = []
    for part in csv.split(","):
        out.push(part.trim().to_int(0))
    return out

fn stats(xs: [int]) Stats:
    s = Stats(0, 0)
    for x in xs:
        s.count += 1
        s.best = max(s.best, x)
    return s

export fn best_score(csv: str) int:
    return stats(parse(csv)).best

export fn summary(csv: str) str:
    s = stats(parse(csv))
    return f"{s.count} games, best {s.best}"

export fn score_at(csv: str, i: int) int:
    return parse(csv)[i]

fn main():
    print(best_score("12, 40, 7"))
    print(summary("12, 40, 7"))
Output
40
3 games, best 40

Build it for each platform. The output directory must already exist.

# iOS: a static library for Xcode (use --target ios-sim for the Simulator)
tern build --lib --target ios scores.tn -o build/libscores.a

# Android: a static library to link with your JNI glue...
tern build --lib --target android scores.tn -o build/libscores.a
# ...or a shared library directly
tern build --lib --shared --target android scores.tn -o build/libscores.so

Each build also writes a C header named after the library, here build/scores.h:

int64_t best_score(const char* csv);
char* summary(const char* csv);   // returns a malloc'd string: free it with tern_free()
int64_t score_at(const char* csv, int64_t i);   // can fail: check tern_last_error()

// After a call to a function marked "can fail": the message of its runtime error, or NULL.
// (A runtime error returns 0 / NULL / false from the call instead of ending the process.)
const char* tern_last_error(void);
void tern_free(void* p);

The shared library exports exactly these functions (plus tern_alloc and tern_stats); everything else is hidden.

Swift on iOS

examples/mobile/ios/ builds examples/embed/lib.tn for the Simulator and calls it from Swift. In an Xcode app, add the .a and the .h to the target and #include the header in the bridging header. From the command line, run.sh does the equivalent:

tern build --lib --target ios-sim examples/embed/lib.tn -o build/libstats.a
xcrun --sdk iphonesimulator swiftc -O -target arm64-apple-ios15.0-simulator \
    -import-objc-header build/stats.h main.swift build/libstats.a -o build/host
xcrun simctl spawn booted "$PWD/build/host"

The Swift side calls the exported functions directly. Numbers arrive as Int64, Swift Strings convert to const char* automatically, and a returned string is a C string you copy and then free with tern_free:

import Foundation

func describeNumbers(_ csv: String) -> String {
    guard let p = describe(csv) else { return "" }
    defer { tern_free(p) }
    return String(cString: p)
}

print("describe:", describeNumbers("3, 1, 4, 1, 5, 9, 2, 6"))
print("sum_csv:", sum_csv("10, 20, 12"))

// Tern runs on whatever thread calls it (Grand Central Dispatch threads here)
let group = DispatchGroup()
for t in 0..<4 {
    DispatchQueue.global().async(group: group) {
        _ = sum_csv("1,2,3,\(t)")
    }
}
group.wait()

let v = nth("5,6,7", 10)
print("nth(10) =", v, "error:", tern_last_error().map { String(cString: $0) } ?? "none")

The full main.swift prints:

describe: 8 numbers, total 31, largest 9
sum_csv: 42
squares_total(1000): 332833500
from 4 GCD threads: [3000, 3500, 4000, 4500]
nth(10) = 0 error: runtime error (line 40): index 10 out of bounds (length 3)

For a device, build with --target ios instead. The library is arm64 only; it isn't a universal binary or an .xcframework, so build the Simulator and device versions separately.

Kotlin and Java on Android

The JVM calls native code through JNI, which looks up functions by special names (Java_<package>_<class>_<method>). So an Android library has two parts: the Tern code, and a small C file of JNI glue that converts Java strings and forwards each call. examples/mobile/android/tern_jni.c is that glue for examples/embed/lib.tn:

#include <jni.h>
#include "stats.h"

static void rethrow(JNIEnv *env) {
    const char *err = tern_last_error();
    if (err) (*env)->ThrowNew(env, (*env)->FindClass(env, "java/lang/RuntimeException"), err);
}

JNIEXPORT jstring JNICALL Java_com_example_tern_Stats_describe(JNIEnv *env, jclass cls, jstring csv) {
    const char *s = (*env)->GetStringUTFChars(env, csv, NULL);
    char *out = describe(s);
    (*env)->ReleaseStringUTFChars(env, csv, s);
    rethrow(env);
    jstring r = (*env)->NewStringUTF(env, out ? out : "");
    tern_free(out);
    return r;
}

On the Kotlin side, the class loads the library and declares the functions:

package com.example.tern

object Stats {
    init { System.loadLibrary("stats") }
    external fun sumCsv(csv: String): Long
    external fun describe(csv: String): String      // throws RuntimeException on a Tern error
}

Build the Tern static library, then link it with the glue into one .so (--whole-archive keeps every Tern function in it). This is what run.sh does:

NDK=${ANDROID_NDK_HOME:-$(ls -d "$HOME"/Library/Android/sdk/ndk/* | tail -1)}
CC="$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang --target=aarch64-linux-android24"
tern build --lib --target android examples/embed/lib.tn -o build/libstats.a
$CC -O2 -shared -fPIC -Ibuild tern_jni.c \
    -Wl,--whole-archive build/libstats.a -Wl,--no-whole-archive -lm -o build/libstats.so

Copy build/libstats.so to app/src/main/jniLibs/arm64-v8a/ in the app. For x86-64 emulators, build a second copy with --target android-x86_64 (and --target=x86_64-linux-android24 for the glue) into jniLibs/x86_64/.

run.sh checks the result without an app: host.c loads libstats.so with dlopen, the way the JVM does, and calls it from two threads on a device or emulator:

describe: 8 numbers, total 31, largest 9
thread 1,2,3 -> 6000
thread 4,5,6 -> 15000
nth(10) = 0, error: runtime error (line 40): index 10 out of bounds (length 3)
JNI entry point present: yes

Threads and runtime startup

Apps have their own threads (the main thread, GCD queues, Java threads), so the runtime works differently from a Tern program that owns main:

  • No setup call. The runtime starts on the first call into any exported function, on whatever thread makes it. If several threads make their first call at once, it still starts exactly once.
  • Any thread may call, and several may call at once. Each host thread gets its own Tern heap on its first allocation. When the thread ends, its free memory goes back to a shared pool for other threads to reuse.
  • parallel runs on Tern's own worker threads, one per core (set TERN_THREADS in the environment to change the count). An exported function that uses parallel for waits for its loop before returning, as usual.
  • Callbacks. In a library, a C callback into a Tern closure may run on any thread; see Calling C.

This is the portable runtime, which every target except the native desktop one uses: the current thread's heap is found through thread-local storage, rather than from the stack address as in the fast desktop runtime. It costs about 20% on allocation-heavy code and nothing measurable elsewhere.

Runtime errors in a library

A runtime error inside an exported call (an index out of bounds, a missing map key, division by zero) doesn't end the app. The call returns 0, NULL, or false, and tern_last_error() returns the message on that thread. The header marks which functions can fail; the others skip the error handling entirely.

  • The message is per thread: read it on the thread that made the call.
  • It is cleared at the start of each call to a function marked "can fail", so check it right after that call. Calls to functions that can't fail leave it unchanged.
  • The Swift example reads it with tern_last_error().map { String(cString: $0) }; the JNI glue turns it into a RuntimeException.
  • The call's string arguments (the Tern copies of the const char*s) are released when an error unwinds.

Limits

  • Architectures. iOS builds are arm64 only, for devices and for the Simulator on Apple-silicon Macs. Android builds are arm64 or x86-64; there is no 32-bit ARM target.
  • Minimum versions. iOS 15.0 and Android API level 24, fixed by the compiler's target triples.
  • SQLite. On iOS, sqlite links against the SDK's SQLite. The NDK has no SQLite, so import sqlite is a compile error on Android: `import sqlite` is not available on android.
  • The web server. http.serve runs on Android (the epoll server path). The repository has no iOS example or test that uses it.
  • Heap size. Phones limit address space, so the runtime reserves the largest heap region it can get, starting at 32GB and halving down to 256MB, and maps more as the heap outgrows it. See How memory works.
  • What crosses the boundary. Numbers, bool, and str for exported functions; no structs, arrays, or maps. Pass structured data as text (JSON with json.encode, or CSV as above), or as several calls.
  • Packaging is up to you. tern makes the .a, .so, and header; adding them to an Xcode project or a Gradle build is done by hand, as described above.

The complete language reference for targets is in section 18 of the reference.

Source: docs/guides/mobile.md. Every example on this page is compiled and run by tern x test docs.