RuneScript

Examples

Every program here is in the examples folder, and the test suite checks its output, so what you see is what the compiler does today.

hello.rscRuns

The minimal program

examples/hello.rsc
// The smallest complete RuneScript program.
package main;

protected int main() {
    trace("Hello, RuneScript!");
    return 0;
}

Output

$ runescript run examples/hello.rsc
Hello, RuneScript!

variables.rscRuns

Declarations, assignment, compound assignment, sint/uint/bool/string

examples/variables.rsc
// Declarations, assignment, and compound assignment.
package examples.variables;

protected int main() {
    int count = 10;
    sint offset = -3;          // 'sint' is another spelling of 'int'
    uint total = 0;
    string label = "count";
    bool ready = true;

    count = count + offset;    // 7
    count *= 2;                // 14
    count++;                   // 15
    total += 40;

    trace(label, count);
    trace("total", total);
    trace("ready", ready);
    return 0;
}

Output

$ runescript run examples/variables.rsc
count 15
total 40
ready true

conditionals.rscRuns

if / else if / else, comparisons, boolean logic

examples/conditionals.rsc
// if / else if / else, comparisons, and boolean operators.
package examples.conditionals;

public string classify(int n) {
    if (n < 0) {
        return "negative";
    } else if (n == 0) {
        return "zero";
    } else if (n % 2 == 0 && n > 100) {
        return "large even";
    } else {
        return "positive";
    }
}

protected int main() {
    trace(-5, classify(-5));
    trace(0, classify(0));
    trace(7, classify(7));
    trace(200, classify(200));

    bool a = true;
    bool b = !a || 3 >= 2;
    trace("b is", b);
    return 0;
}

Output

$ runescript run examples/conditionals.rsc
-5 negative
0 zero
7 positive
200 large even
b is true

loops.rscRuns

for, while, break, continue

examples/loops.rsc
// while, for, break, and continue.
package examples.loops;

public void sayHi(string message, int times) {
    for (int i = 0; i < times; i++) {
        trace(message);
    }
}

protected int main() {
    sayHi("Hello world", 3);

    int n = 0;
    while (n < 10) {
        n++;
        if (n % 2 == 0) {
            continue;
        }
        if (n > 7) {
            break;
        }
        trace("odd", n);
    }
    return 0;
}

Output

$ runescript run examples/loops.rsc
Hello world
Hello world
Hello world
odd 1
odd 3
odd 5
odd 7

functions.rscRuns

Parameters, return values, recursion, calling before declaration

examples/functions.rsc
// Functions: parameters, return values, recursion, and calls before declaration.
package examples.functions;

protected int main() {
    trace("5! =", factorial(5));
    trace("fib(20) =", fib(20));
    trace("gcd(84, 36) =", gcd(84, 36));
    return 0;
}

public int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

public int fib(int n) {
    int a = 0;
    int b = 1;
    for (int i = 0; i < n; i++) {
        int next = a + b;
        a = b;
        b = next;
    }
    return a;
}

public uint gcd(uint a, uint b) {
    uint x = a;
    uint y = b;
    while (y != 0) {
        uint t = x % y;
        x = y;
        y = t;
    }
    return x;
}

Output

$ runescript run examples/functions.rsc
5! = 120
fib(20) = 6765
gcd(84, 36) = 12

fizzbuzz.rscRuns

Putting the basics together

examples/fizzbuzz.rsc
// The classic.
package examples.fizzbuzz;

public void fizzbuzz(int limit) {
    for (int i = 1; i <= limit; i++) {
        if (i % 15 == 0) {
            trace("FizzBuzz");
        } else if (i % 3 == 0) {
            trace("Fizz");
        } else if (i % 5 == 0) {
            trace("Buzz");
        } else {
            trace(i);
        }
    }
}

protected int main() {
    fizzbuzz(15);
    return 0;
}

Output

$ runescript run examples/fizzbuzz.rsc
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

strings.rscRuns

The std:string standard library

examples/strings.rsc
// The std:string standard library package (Go's strings, camelCase names).
package examples.strings;

use "std:string";

public string slug(string title) {
    string s = string.toLower(string.trimSpace(title));
    return string.replaceAll(s, " ", "-");
}

protected int main() {
    string title = "   Hello RuneScript World   ";
    trace("slug:", slug(title));

    string path = "assets/runescript.svg";
    if (string.hasSuffix(path, ".svg")) {
        trace("image:", string.trimSuffix(path, ".svg"));
    }

    int slash = string.index(path, "/");
    trace("first slash at byte", slash);
    trace("vowels in title:", string.count(title, "o") + string.count(title, "e"));
    trace(string.repeat("=", 20));
    return 0;
}

Output

$ runescript run examples/strings.rsc
slug: hello-runescript-world
image: assets/runescript
first slash at byte 6
vowels in title: 4
====================

callbacks.rscRuns

Function types, callbacks, lambdas, nested functions, prototypes, returning functions

examples/callbacks.rsc
// Advanced functions: callbacks, lambdas, nested functions, prototypes,
// and functions that return functions.
package examples.callbacks;

// A prototype: the definition is further down.
public int sumWith(int(int) f, int n);

public void forEach(int from, int to, void(int) body) {
    for (int i = from; i <= to; i++) {
        body(i);
    }
}

public int(int) multiplier(int factor) {
    // Functions do not capture variables, so each factor gets its own function.
    private int times2(int x) { return x * 2; }
    private int times3(int x) { return x * 3; }
    if (factor == 2) {
        return times2;
    }
    if (factor == 3) {
        return times3;
    }
    return (int x) => x;
}

protected int main() {
    // Pass a lambda as a callback.
    forEach(1, 3, (int i) => trace("item", i));

    // Store functions in variables and pass named functions around.
    int(int) square = (int x) => x * x;
    trace("sum of squares 1..4:", sumWith(square, 4));
    trace("sum of triples 1..5:", sumWith(multiplier(3), 5));
    trace("double 21:", multiplier(2)(21));

    // Nested functions, with a prototype for mutual recursion.
    private bool isEven(int n);
    private bool isOdd(int n) {
        if (n == 0) { return false; }
        return isEven(n - 1);
    }
    private bool isEven(int n) {
        if (n == 0) { return true; }
        return isOdd(n - 1);
    }
    trace("7 is odd:", isOdd(7));
    return 0;
}

public int sumWith(int(int) f, int n) {
    int total = 0;
    for (int i = 1; i <= n; i++) {
        total += f(i);
    }
    return total;
}

Output

$ runescript run examples/callbacks.rsc
item 1
item 2
item 3
sum of squares 1..4: 30
sum of triples 1..5: 45
double 21: 42
7 is odd: true

primes.rscRuns

Predicate callbacks, a lambda, a nested helper, and string.repeat

examples/primes.rsc
// Counting and charting primes with predicate callbacks, a lambda,
// a nested helper function, and std:string.
package examples.primes;

use "std:string";

public bool isPrime(int n) {
    if (n < 2) {
        return false;
    }
    for (int d = 2; d * d <= n; d++) {
        if (n % d == 0) {
            return false;
        }
    }
    return true;
}

// Counts the numbers in [from, to] for which pred returns true.
public int countWhere(int from, int to, bool(int) pred) {
    int count = 0;
    for (int n = from; n <= to; n++) {
        if (pred(n)) {
            count++;
        }
    }
    return count;
}

protected int main() {
    trace("primes up to 100:", countWhere(1, 100, isPrime));
    trace("twin primes up to 100:", countWhere(1, 100, (int n) => isPrime(n) && isPrime(n + 2)));

    private void bar(int from, int count) {
        trace(from, string.repeat("#", count), count);
    }
    trace("primes per hundred:");
    for (int from = 0; from < 500; from += 100) {
        bar(from, countWhere(from, from + 99, isPrime));
    }
    return 0;
}

Output

$ runescript run examples/primes.rsc
primes up to 100: 25
twin primes up to 100: 8
primes per hundred:
0 ######################### 25
100 ##################### 21
200 ################ 16
300 ################ 16
400 ################# 17

brainfuck.rscRuns

A Brainfuck interpreter with 32,768 cells: std:fs, std:io, std:process, structs, Array<uint8>. Programs to run are in [bf/](bf/): hello.bf, alphabet.bf, cat.bf, rot13.bf

examples/brainfuck.rsc
// A Brainfuck interpreter with 32,768 cells.
//
//   runescript run examples/brainfuck.rsc examples/bf/hello.bf
//   echo "Hello, World!" | runescript run examples/brainfuck.rsc examples/bf/rot13.bf
//   runescript run examples/brainfuck.rsc -e "++++++++[>++++++++<-]>+."
//
// Without arguments it runs a built-in Hello World.
//
// The tape has 32,768 cells of 8 bits, which wrap around (255 + 1 is 0).
// Moving off either end of the tape is an error. ',' reads one byte of
// standard input, and leaves the cell unchanged at the end of the input.
// '.' writes one byte; bytes that form UTF-8 characters print as those
// characters.
//
// The program is compiled first: runs of + and - (and of > and <) become
// one operation, [-] and [+] become "set to zero", and every bracket
// learns where its partner is, so an unmatched one is reported, with its
// line and column, before anything runs.
//
// Shows std:fs, std:io, and std:process, structs, Array<T>, uint8,
// char, and errors.
package examples.brainfuck;

use "std:fs";
use "std:io";
use "std:process";
use "std:string";

// One compiled operation.
public struct Op {
    char kind;    // '+', '>', '.', ',', '[', ']', or 'z' (set to zero)
    int arg;      // + : the amount (0 to 255); > : the distance, possibly
                  // negative; [ and ] : the index of the partner bracket
    int line;     // where it starts in the source
    int col;
}

// compile turns source into operations. An unmatched bracket throws an
// ArgumentError whose message starts with its line and column.
public Array<Op> compile(string source) {
    Array<Op> ops;
    Array<int> open;               // indexes of the [ not yet closed
    Array<string> chars = string.split(source, "");
    int line = 1;
    int col = 0;
    int i = 0;
    while (i < chars.length) {
        char c = (char) chars[i];
        col++;
        if (c == '\n') {
            line++;
            col = 0;
            i++;
            continue;
        }
        if (c == '+' || c == '-' || c == '>' || c == '<') {
            // A run of + and - (or > and <) is one operation.
            bool cells = c == '+' || c == '-';
            int startCol = col;
            int sum = 0;
            while (i < chars.length) {
                char d = (char) chars[i];
                if (cells && d == '+' || !cells && d == '>') {
                    sum++;
                } else if (cells && d == '-' || !cells && d == '<') {
                    sum--;
                } else {
                    break;
                }
                i++;
                col++;
            }
            col--;
            if (cells) {
                ops.push(Op{kind: '+', arg: (sum % 256 + 256) % 256, line: line, col: startCol});
            } else {
                ops.push(Op{kind: '>', arg: sum, line: line, col: startCol});
            }
            continue;
        }
        if (c == '[' && i + 2 < chars.length && (chars[i + 1] == "-" || chars[i + 1] == "+") && chars[i + 2] == "]") {
            ops.push(Op{kind: 'z', arg: 0, line: line, col: col});
            i += 3;
            col += 2;
            continue;
        }
        if (c == '[') {
            open.push(ops.length);
            ops.push(Op{kind: '[', arg: -1, line: line, col: col});
        } else if (c == ']') {
            if (open.length == 0) {
                throw new ArgumentError($"{line}:{col}: this ']' has no matching '['");
            }
            int start = open.pop();
            ops[start].arg = ops.length;
            ops.push(Op{kind: ']', arg: start, line: line, col: col});
        } else if (c == '.' || c == ',') {
            ops.push(Op{kind: c, arg: 0, line: line, col: col});
        }
        // Every other character is a comment.
        i++;
    }
    if (open.length > 0) {
        Op unclosed = ops[open.pop()];
        throw new ArgumentError($"{unclosed.line}:{unclosed.col}: this '[' has no matching ']'");
    }
    return ops;
}

// ---- output ----

// flush prints the bytes in out that form whole UTF-8 characters, and
// returns the bytes of a character that is not finished yet (none if done
// is set). Bytes that are not UTF-8 print as U+FFFD.
public Array<int> flush(Array<int> out, bool done) {
    string text = "";
    int i = 0;
    while (i < out.length) {
        int b = out[i];
        if (b < 0x80) {
            text += (string) (char) b;
            i++;
            continue;
        }
        int need = 0;
        int cp = 0;
        int least = 0;             // the smallest code point of that length
        if (b >= 0xC2 && b <= 0xDF) {
            need = 1;
            cp = b & 0x1F;
            least = 0x80;
        } else if (b >= 0xE0 && b <= 0xEF) {
            need = 2;
            cp = b & 0x0F;
            least = 0x800;
        } else if (b >= 0xF0 && b <= 0xF4) {
            need = 3;
            cp = b & 0x07;
            least = 0x10000;
        } else {
            text += "\u{FFFD}";
            i++;
            continue;
        }
        if (i + need >= out.length && !done) {
            // Maybe an unfinished character: wait for the rest of it,
            // unless what is there already cannot be one.
            bool possible = true;
            for (int j = i + 1; j < out.length; j++) {
                if (out[j] < 0x80 || out[j] > 0xBF) {
                    possible = false;
                }
            }
            if (possible) {
                break;
            }
        }
        int j = i + 1;
        while (j <= i + need && j < out.length && out[j] >= 0x80 && out[j] <= 0xBF) {
            cp = cp << 6 | out[j] & 0x3F;
            j++;
        }
        if (j == i + need + 1 && cp >= least && cp <= 0x10FFFF && (cp < 0xD800 || cp > 0xDFFF)) {
            text += (string) (char) cp;
            i = j;
        } else {
            text += "\u{FFFD}";
            i++;
        }
    }
    io.print(text);
    Array<int> rest;
    for (int k = i; k < out.length; k++) {
        rest.push(out[k]);
    }
    return rest;
}

// ---- running ----

// run executes ops on a tape of 32,768 cells, and returns the exit code.
public int run(Array<Op> ops, string name) {
    int cells = 32768;
    Array<uint8> tape;
    for (int i = 0; i < cells; i++) {
        tape.push(0);
    }
    Array<int> out;            // bytes written but not printed yet
    int ptr = 0;
    int pc = 0;
    while (pc < ops.length) {
        Op op = ops[pc];
        if (op.kind == '+') {
            tape[ptr] = (uint8) (((int) tape[ptr] + op.arg) % 256);
        } else if (op.kind == '>') {
            ptr += op.arg;
            if (ptr < 0 || ptr >= cells) {
                out = flush(out, true);
                io.error($"{name}:{op.line}:{op.col}: the data pointer moved off the tape (to cell {ptr}; the cells are 0 to {cells - 1})");
                return 1;
            }
        } else if (op.kind == 'z') {
            tape[ptr] = 0;
        } else if (op.kind == '[') {
            if (tape[ptr] == 0) {
                pc = op.arg;
            }
        } else if (op.kind == ']') {
            if (tape[ptr] != 0) {
                pc = op.arg;
            }
        } else if (op.kind == '.') {
            out.push((int) tape[ptr]);
            if (tape[ptr] == 10 || out.length >= 4096) {
                out = flush(out, false);
            }
        } else {
            // ',': show any prompt first, then read a byte.
            out = flush(out, false);
            int b = io.readByte();
            if (b >= 0) {
                tape[ptr] = (uint8) b;
            }
        }
        pc++;
    }
    out = flush(out, true);
    return 0;
}

protected int main() {
    Array<string> args = process.args();
    string name = "hello";
    string source = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
    if (args.length == 2 && args[0] == "-e") {
        name = "-e";
        source = args[1];
    } else if (args.length == 1 && args[0] != "-e") {
        name = args[0];
        try {
            source = fs.readFile(name);
        } catch (Error e) {
            io.error(e.message);
            return 1;
        }
    } else if (args.length != 0) {
        io.error("usage: brainfuck.rsc [<file.bf> | -e <code>]");
        return 2;
    }
    try {
        return run(compile(source), name);
    } catch (ArgumentError e) {
        io.error(name + ":" + e.message);
        return 1;
    }
}

Output

$ runescript run examples/brainfuck.rsc
Hello World!

errors.rscRuns

throw, try/catch/finally, error types, and catching a runtime error

examples/errors.rsc
// Errors: throw, try/catch/finally, and catching runtime errors.
package examples;

// parseAge turns text into an age, or throws.
public int parseAge(string text) {
    int age = (int) text; // a TypeError if text isn't a whole number
    if (age < 0 || age > 150) {
        throw new RangeError("not a plausible age", 100);
    }
    return age;
}

public void report(string text) {
    try {
        trace(text, "->", parseAge(text));
    } catch (RangeError e) {
        trace(text, "-> out of range:", e.message);
    } catch (TypeError e) {
        trace(text, "-> not a number");
    }
}

protected int main() {
    report("42");
    report("-7");
    report("forty");

    // Runtime errors are errors too, and finally always runs.
    int big = 2147483647;
    for (int step = 1; step <= 2; step++) {
        try {
            trace("adding", step);
            big = big + (2147483647 * (step - 1) + 1);
            trace("never printed");
        } catch (RangeError e) {
            trace("caught", e.name, e.errorID);
        } finally {
            trace("finally", step);
        }
    }
    return 0;
}

Output

$ runescript run examples/errors.rsc
42 -> 42
-7 -> out of range: not a plausible age
forty -> not a number
adding 1
caught RangeError 2
finally 1
adding 2
caught RangeError 2
finally 2

temperatures.rscRuns

float, float32, and checked conversions such as (int) f and (float) "98.6"

examples/temperatures.rsc
// Floats and conversions: a temperature table.
package examples;

public float toFahrenheit(float celsius) {
    return celsius * 9 / 5 + 32;
}

protected int main() {
    for (int c = -40; c <= 100; c += 35) {
        float f = toFahrenheit((float) c);
        trace(c, "C is", f, "F");
    }

    // float32 keeps 32-bit precision; float keeps every digit.
    float exact = 1.0 / 3;
    float32 rounded = (float32) exact;
    trace(exact, rounded);

    // Conversions are checked and truncate toward zero.
    trace((int) toFahrenheit(37.5), (int) -2.9, (float) "98.6");
    return 0;
}

Output

$ runescript run examples/temperatures.rsc
-40 C is -40 F
-5 C is 23 F
30 C is 86 F
65 C is 149 F
100 C is 212 F
0.3333333333333333 0.33333334
99 -2 98.6

wordcount.rscRuns

A text report: Array<T>, char callbacks, +, $"…", and string.split/fields/map/join

examples/wordcount.rsc
// A small text report: split lines and words, count them, and build
// output with interpolated strings. Shows Array<T>, char callbacks, +,
// $"…", and std:string's split, fields, map, trimFunc, and join.
package examples;

use "std:string";

public bool isPunct(char c) {
    return c == ',' || c == '.' || c == '!' || c == '?';
}

public char lower(char c) {
    if (c >= 'A' && c <= 'Z') {
        return (char) ((int) c + 32);
    }
    return c;
}

// indexOf returns the position of word in words, or -1.
public int indexOf(Array<string> words, string word) {
    for (int i = 0; i < words.length; i++) {
        if (words[i] == word) {
            return i;
        }
    }
    return -1;
}

protected int main() {
    string text = "The cat sat.\nThe dog sat, too!\nA cat? A dog.";
    Array<string> lines = string.split(text, "\n");

    Array<string> seen = [];
    Array<int> counts = [];
    int total = 0;
    for (int i = 0; i < lines.length; i++) {
        Array<string> words = string.fields(lines[i]);
        trace($"line {i + 1}: {words.length} words");
        for (int j = 0; j < words.length; j++) {
            string word = string.map(lower, string.trimFunc(words[j], isPunct));
            int at = indexOf(seen, word);
            if (at < 0) {
                seen.push(word);
                counts.push(1);
            } else {
                counts[at] += 1;
            }
            total++;
        }
    }

    Array<string> report = [];
    for (int i = 0; i < seen.length; i++) {
        report.push(seen[i] + "=" + (string) counts[i]);
    }
    trace($"{total} words, {seen.length} different");
    trace(string.join(report, ", "));
    return 0;
}

Output

$ runescript run examples/wordcount.rsc
line 1: 3 words
line 2: 4 words
line 3: 4 words
11 words, 6 different
the=2, cat=2, sat=2, dog=2, too=1, a=2

boundary_error.rscRejected

ASX-NAME-009: nested functions don't capture outer variables

examples/boundary_error.rsc
// This program is intentionally rejected: nested functions and lambdas do
// not capture the variables of the function around them.
//
//   runescript check examples/boundary_error.rsc
package examples.errors;

protected int main() {
    int total = 0;
    private void add(int n) {
        total += n; // expect: ASX-NAME-009 10:9
    }
    add(5);
    return total;
}

Diagnostics

$ runescript check examples/boundary_error.rsc
examples/boundary_error.rsc:10:9: error ASX-NAME-009: 'total' belongs to an enclosing function and is not visible here
            total += n; // expect: ASX-NAME-009 10:9
            ^^^^^
  help: nested functions and lambdas do not capture outer variables; pass 'total' as a parameter

signedness_error.rscRejected

ASX-TYPE-004: a signed value can't go into a uint

examples/signedness_error.rsc
// This program is intentionally rejected: RuneScript never silently
// converts a signed integer to an unsigned one.
//
//   runescript check examples/signedness_error.rsc
package examples.errors;

protected int main() {
    sint signedValue = -10;
    uint unsignedValue = signedValue; // expect: ASX-TYPE-004 9:26
    return 0;
}

Diagnostics

$ runescript check examples/signedness_error.rsc
examples/signedness_error.rsc:9:26: error ASX-TYPE-004: Cannot assign signed integer 'sint' to unsigned integer 'uint'.
        uint unsignedValue = signedValue; // expect: ASX-TYPE-004 9:26
                             ^^^^^^^^^^^
  help: Use an explicit checked conversion, (uint) x, or change the destination type.