Skip to content

Script plugin ​

A small imperative language for computing over models. Its main job is supplying the objective and constraint functions of an optimisation, but scripts can also be run on their own.

At a glance ​

Plugin idscript-service
Display nameScript
DescriptionLanguage support for script definitions (the manifest string still says .s files; the extension is .fn)
Default URL/plugin/script
Sourceapp/packages/service-script, app/packages/language-script, app/packages/language-expression
Depends onThe Metamodel plugin; executions go to script-execution

Languages contributed ​

Language idNameExtensionTextual editorGraphical editorGenerated
scriptScript.fn✅❌❌

The script language ​

A .fn file optionally names a metamodel, may import functions and records from other script files, and defines functions and records.

fn
using "./tasks.mm"

// Total effort of every task that nobody has picked up yet.
fun unassignedEffort(): int {
    var total = 0
    for (task in Task.all()) {
        if (task.assignee == null) {
            total = total + task.effort
        }
    }
    return total
}

// How much the busiest developer is overloaded beyond their capacity.
fun maxOverload(): int {
    var worst = 0
    for (developer in Developer.all()) {
        var assigned = 0
        for (task in developer.tasks) {
            assigned = assigned + task.effort
        }
        var overload = assigned - developer.capacity
        if (overload > worst) {
            worst = overload
        }
    }
    return worst
}

// Constraint: every high priority task has to be assigned.
// 0 means satisfied, any larger value is the magnitude of the violation.
fun unassignedHighPriority(): int {
    var violations = 0
    for (task in Task.all()) {
        if (task.priority == Priority.HIGH && task.assignee == null) {
            violations = violations + 1
        }
    }
    return violations
}

Functions ​

fn
fun name(parameter: Type, other: Type): ReturnType {
    return value
}

The return type may be omitted for a function that returns nothing, or written as void.

A parameter can have a default value, used when a call leaves the parameter out. It may refer to the parameters declared before it:

fn
fun scale(value: double, factor: double = 2.0, offset: double = factor / 2): double {
    return value * factor + offset
}

Arguments are passed by position or by name. Named arguments come after positional ones, may be in any order, and are evaluated in the order they are written:

fn
scale(1.0)                          // factor = 2.0, offset = 1.0
scale(1.0, offset = 0.0)
scale(offset = 0.0, value = 1.0)

Named arguments work for every function and method, with the parameter names their signatures declare, except for functions taking a variable number of arguments, such as listOf, and lambdas.

Functions and records from another file are imported by name, and either can be renamed. A renamed record is known by its new name only, both as a constructor and as a type, so two records of the same name from different files can be used side by side:

fn
import { unassignedEffort, maxOverload as overload } from "./objectives.fn"
import { Point as GeoPoint } from "./geometry.fn"

Records ​

A record is a data structure with named fields, declared like a constructor. Fields can have default values, like parameters:

fn
record Point(x: double, y: double = 0.0, label: string = "")

A record is created by calling its name, with positional or named arguments. Its fields are read and assigned like properties, and with copies it with some fields changed:

fn
val p = Point(1.0, label = "start")
p.y = 2.0
val q = p.with(x = 3.0)             // Point(x=3.0, y=2.0, label=start)
  • Records are compared by content with ==, and by identity with ===. Two records are equal when they are of the same record and all their fields are equal, so equal records are one element of a set. Changing a record that is an element of a set or a key of a map does not move it there, so it is no longer found; change a copy made with with instead.
  • with copies only the record itself: a list field of the copy is the same list as the original's.
  • A record can be used as a type anywhere a type is expected, including Point?, and checked with is and as.
  • A field cannot be named with, and a record cannot have the name of a function of its file, of a builtin type such as List, or of a class or enum of the metamodel.

Contributions can define records of their own, which scripts use the same way.

fn
// A record is a data structure with named fields, declared like a constructor.
record Point(x: double, y: double = 0.0)

record Route(
    name: string,
    stops: List<Point> = emptyList<Point>(),
    closed: boolean = false
)

// Parameters can have default values, which may use the parameters before them.
fun scale(point: Point, factor: double, yFactor: double = factor): Point {
    return Point(point.x * factor, point.y * yFactor)
}

fun length(route: Route): double {
    var total = 0.0
    var previous: Point? = null
    for (stop in route.stops) {
        if (previous != null) {
            val dx = stop.x - previous!!.x
            val dy = stop.y - previous!!.y
            total = total + dx * dx + dy * dy
        }
        previous = stop
    }
    return total
}

fun planRoute(): double {
    // A record is created by calling its name, positionally or with named arguments.
    val route = Route("tour", closed = true)
    route.stops.add(Point(1.0))
    route.stops.add(Point(y = 2.0, x = 3.0))

    // Fields are mutable, and `with` copies a record with some fields changed.
    val start = route.stops.first()
    start.y = 1.0
    val shifted = start.with(x = start.x + 1.0)
    route.stops.add(scale(shifted, 2.0))

    // A `val` is assigned exactly once, possibly later on each branch.
    val bonus: double
    if (route.closed) {
        bonus = 1.0
    } else {
        bonus = 0.0
    }
    return length(route) + bonus
}

A larger example spreads records and functions over three files that import each other. It uses default values that refer to earlier fields, named arguments to imported and renamed functions, with, val, record equality in a set, and ?. on an optional record field:

fn
// Records and functions the other files of this project import.

// A location on the map, in kilometres. `y` can be left out.
record Point(x: double, y: double = 0.0)

// A place a tour visits, and how many minutes the delivery takes there.
record Stop(name: string, location: Point, minutes: int = 15)

// Straight-line distance between two points.
fun distance(a: Point, b: Point): double {
    val dx = b.x - a.x
    val dy = b.y - a.y
    return (dx * dx + dy * dy).sqrt()
}
fn
import { Point, Stop, distance } from "./geometry.fn"

// A default value may use the fields declared before it: a tour returns to its depot unless it is
// told to end somewhere else.
record Tour(
    name: string,
    depot: Point,
    stops: List<Stop> = emptyList<Stop>(),
    end: Point = depot
)

// Adds a stop to a tour. Parameters with a default value can be left out.
fun visit(
    tour: Tour,
    name: string,
    x: double,
    y: double = 0.0,
    minutes: int = 15
): Tour {
    tour.stops.add(Stop(name, Point(x, y), minutes))
    return tour
}

// Length of a tour in kilometres, with or without the way from the last stop to its end.
fun length(tour: Tour, toEnd: boolean = true): double {
    var total = 0.0
    var here = tour.depot
    for (stop in tour.stops) {
        total = total + distance(here, stop.location)
        here = stop.location
    }
    if (toEnd) {
        total = total + distance(here, tour.end)
    }
    return total
}

// Driving and delivery time in minutes, at an average speed in km/h.
fun duration(tour: Tour, speed: double = 40.0, toEnd: boolean = true): double {
    var delivering = 0
    for (stop in tour.stops) {
        delivering = delivering + stop.minutes
    }
    return length(tour, toEnd) / speed * 60.0 + delivering
}
fn
import { Point, Stop } from "./geometry.fn"
import { Tour, visit, length, duration as minutes } from "./tours.fn"

// The outcome of planning one tour.
record Summary(
    tour: string,
    kilometres: double,
    minutes: double,
    late: boolean = false,
    longest: Stop? = null
)

fun summarize(tour: Tour, deadline: double = 120.0): Summary {
    // Named arguments can be passed in any order, after the positional ones.
    val total = minutes(tour, toEnd = true, speed = 30.0)

    // A `val` cannot be assigned again, but it can be assigned later: once on every branch.
    val name: string
    if (tour.stops.isEmpty()) {
        name = tour.name + " (empty)"
    } else {
        name = tour.name
    }

    val summary = Summary(name, length(tour), total, late = total > deadline)
    for (stop in tour.stops) {
        // Record fields are mutable, and `?.` reads a field of a record that may be null.
        if (stop.minutes > (summary.longest?.minutes ?? 0)) {
            summary.longest = stop
        }
    }
    return summary
}

fun tours(): List<Tour> {
    val depot = Point(0.0)

    // A record is created by calling its name, with positional or named arguments.
    val north = Tour("north", depot)
    visit(north, "bakery", 3.0, y = 4.0)
    visit(north, "market", x = 6.0, y = 8.0, minutes = 45)

    // `with` copies a record with some fields changed. Without a new list, the copy would share
    // the stops of the original.
    val south = north.with(
        name = "south",
        stops = emptyList<Stop>(),
        end = Point(10.0)
    )
    visit(south, "harbour", 6.0, minutes = 20)

    return listOf(north, south, Tour(name = "west", depot = depot))
}

fun plan(): string {
    val summaries = tours().map((tour) => summarize(tour, deadline = 60.0))

    var report = ""
    for (summary in summaries.sortedBy(iterator = (it) => it.kilometres)) {
        val longest = summary.longest?.name ?? "none"
        report = report + summary.tour + ": " + summary.kilometres + " km, " + summary.minutes + " min"
        if (summary.late) {
            report = report + ", late"
        }
        report = report + ", longest stop " + longest + "\n"
    }
    return report
}

// Records are equal when they are the same record with equal fields, so a set keeps one of each.
fun depots(): int {
    val points = emptySet<Point>()
    for (tour in tours()) {
        points.add(tour.depot)
        points.add(tour.end)
    }
    return points.size()
}

fun copies(): string {
    val stop = Stop("bakery", Point(3.0, 4.0))
    val same = Stop("bakery", Point(3.0, 4.0))
    val later = stop.with(minutes = 30)

    // `==` compares records by content, `===` by identity. A record prints its fields.
    val equal = stop == same
    val identical = stop === same
    return "" + equal + " " + identical + " " + (stop == later) + " " + later
}

plan() reports the three tours, shortest first:

text
west (empty): 0.0 km, 0.0 min, longest stop none
south: 10.0 km, 40.0 min, longest stop harbour
north: 20.0 km, 100.0 min, late, longest stop market

Reaching the model ​

A script that declares using "./tasks.mm" gets one accessor per class in that metamodel: Task.all() returns every Task in the model being evaluated. From there you navigate through the properties and associations the metamodel declares.

fn
for (task in Task.all()) {
    if (task.assignee == null) { }
}

Types ​

CategoryTypes
Numbersint, long, float, double
Other primitivesstring, boolean
CollectionsCollection<T>, List<T>, Set<T>, Bag<T>, OrderedSet<T>, Iterable<T>
DomainEvery class and enum of the imported metamodel, and every record the file declares or imports
Lambdas(A, B) => R
Top typeAny

A ? suffix makes a type nullable: Shape?, (Int) => Int?.

Number literals are written as in Kotlin and Java: 42 is an int, 42L a long, 1.5, 1.0e300, 2.5E-3 and 1e3 are doubles (an optional d suffix), and the same with an f suffix — 1.5f, 2e-3f — are floats. The transformation language shares these literals.

Statements and expressions ​

fn
using "./shapes.mm"

// Literals of every supported kind.
fun literals(): int {
    var integer = 42
    var big = 42L
    var single = 1.5f
    var precise = 1.5
    var text = "with \"escapes\" and \n newlines"
    var flag = true
    var nothing: string? = null
    var numbers = listOf(1, 2, 3)
    println(text)
    return integer
}

// Operators, grouped by precedence from tightest to loosest.
fun operators(a: int, b: int): boolean {
    var arithmetic = a * b / 2 + a - b % 3
    var comparison = arithmetic < 100 && arithmetic >= 0
    var equality = a == b || a != b
    var ternary = comparison ? arithmetic : 0
    return equality && ternary >= 0
}

// Null handling: null-safe access, elvis and the non-null assertion.
fun nullHandling(shape: Shape?): string {
    var maybeName = shape?.name
    var name = maybeName ?? "unnamed"
    if (shape != null) {
        return shape!!.name
    }
    return name
}

// Type checks and casts.
fun area(shape: Shape): double {
    if (shape is Rectangle) {
        var rectangle = shape as Rectangle
        return rectangle.width * rectangle.height
    }
    var circle = shape as? Circle
    if (circle != null) {
        return 3.14159 * circle.radius * circle.radius
    }
    return 0.0
}

// Control flow and collection access through the generated `all()` accessor.
fun visibleShapeCount(): int {
    var count = 0
    for (shape in Shape.all()) {
        if (!shape.visible) {
            continue
        }
        if (shape.colour == Colour.RED) {
            count = count + 2
        } else if (shape.colour == Colour.GREEN) {
            count = count + 1
        } else {
            count = count + 1
        }
    }

    var guard = 0
    while (guard < 10) {
        guard = guard + 1
        if (guard > 5) {
            break
        }
    }
    return count
}

// Lambdas are ordinary expressions and can be passed to collection operations.
fun totalArea(): double {
    var total = 0.0
    for (shape in Shape.all()) {
        total = total + area(shape)
    }
    return total
}

Statements are variable declarations, assignments, if / else if / else, while, for … in, break, continue and return. Statements are separated by line breaks, not semicolons.

A variable is declared with var, which can be assigned again, or val, which cannot. A val without an initial value must be assigned exactly once before it is read, as in Kotlin: on each branch that does not end in return, break or continue, but not in a loop or a lambda.

fn
var count = 0
count = count + 1
val limit: int
if (strict) {
    limit = 10
} else {
    limit = 100
}

Operators, from tightest to loosest binding:

GroupOperators
Postfix., ?., !!, calls
Unary!, -
Castas, as?
Multiplicative*, /, %
Additive+, -
Elvis??
Type checkis, !is
Relational<, >, <=, >=
Equality==, !=, ===, !==
Conjunction&&
Disjunction||
Conditional? :

Lambdas are written (a, b) => expression or (a, b) => { … } and are ordinary expressions.

The standard library provides println, the collection constructors listOf, setOf, bagOf, orderedSetOf, and their empty counterparts emptyList, emptySet, emptyBag, emptyOrderedSet.

Objective and constraint functions ​

A function used as an objective or a constraint in a .config file has to satisfy two rules, enforced by validation in the editor:

  • it takes no parameters — it reads the model through the all() accessors;
  • it returns a numeric type (int, long, float or double).

For a constraint, 0 means satisfied and any larger value is the magnitude of the violation.

Contribution plugins contributed ​

Target languageWhat it adds
configThe script Function type export

Script functions for the config language ​

Like the metamodel plugin, the script plugin contributes no syntax to the config language. It exports its Function AST type so that contribution plugins which do add syntax can write rules referencing script functions — which is how minimize unassignedEffort in a goal section resolves to the function in your .fn file.

Contribution plugin idconfig-script
Short namescript
Sectionsnone
Exported typesFunction

Contributions the script language accepts ​

The script language is itself extensible. A plugin can register a script contribution plugin that adds:

  • functions — extra entries in the global scope, with signatures and an implementation given as a typed AST, or answered by the plugin's own service;
  • records and opaque classes — values its functions exchange with scripts;
  • expressions — new syntax, backed by a grammar rule and implemented by a function.

Nothing in the bundled set uses this yet, but it is the supported way to grow the standard library without changing the script language.

Server-side capabilities ​

File data keyContents
astThe serialised AST
typed-astThe type-annotated AST the execution service interprets

Execution. A script function can be run against a model. The plugin forwards the request to the script-execution service, configured through SCRIPT_EXECUTION_SERVICE_URL, which runs it in a sandboxed subprocess under a timeout.

Released under the terms of the repository licence.