Relational sublanguage

SCL contains a small logic programming language. A query asks for every way to make a set of facts true. The facts come from relations: a few built-in ones, relations defined by rules written with :-, and, in Simantics, the relations of the semantic graph. enforce does the opposite of a query and makes facts true, and mapping rules, run by a transformation, build one structure from another.

This is an advanced feature. Nothing here is needed for ordinary SCL programming. The CHR engine of 4.02 Constraint Handling Rules is a separate mechanism that shares some syntax with this one; Relational queries and CHR at the end of this page compares the two.

Imports

The code that the compiler generates for these constructs calls functions of library modules, and a module that uses the constructs must import those modules:

Construct Modules it needs
select, select distinct ArrayList
select first, enforce none
tc MSet
relations defined in a block MList, MSet
transformation MList, MSet, Unification

Without them, the compiler reports the construct where it is written and names the modules that are missing, for example select needs the ArrayList module, for example through import "StandardLibrary". or A relation defined in a block needs the MList and MSet modules, ... Any import of a module will do, even import "ArrayList" (), and an import of MSet also brings in MList. The simplest is to import StandardLibrary, which brings in all four. The module examples on this page assume

import "StandardLibrary"

A script, and the SCL Console, import StandardLibrary automatically (see 1.18 Modules vs. scripts).

Queries

main = select ?x where
    ?x <- [1, 2, 3]
    ?x > 1
// [2, 3]

A select expression has the form select result where query. It finds every solution of the query and returns a list of the values that the result expression has in them.

Names that start with ? are query variables. A query variable is introduced by using it, and it is local to its select. Every solution gives a value to each query variable, and both the result expression and the query can use them:

select (?x * ?x) where ?x <- [1, 2, 3]          // [1, 4, 9]

The query is a block of literals, one per line, or several on one line separated by ;. A solution must satisfy all of them. A literal is one of

Literal Holds when
pattern <- list an element of the list matches the pattern; there is one solution for each such element
pattern = expression the value of the expression matches the pattern
R a1 ... an the relation R holds, see Relations
tc R a1 ... an the transitive closure of R holds, see Transitive closure
<&>, <|>, <!> or <?>, followed by a block see Combining queries
any other Boolean expression it is True; such a literal is a guard

Patterns are written as in match. They may contain query variables, _, constants and variables bound elsewhere, and a value that does not match is skipped:

pairs = [(1, "one"), (2, "two"), (3, "three")]

select ?name where (2, ?name) <- pairs                          // ["two"]
select ?n where (?n, ?name) <- pairs; ?name == "three"          // [3]
select ?y where ?m <- [Just 1, Nothing, Just 3]; Just ?y = ?m   // [1, 3]

Query variables exist only in queries and rules. A ?x anywhere else is New existential variables can be defined only in queries., and a _ in an expression outside a query is Blank variables can be used only in queries.

Order of evaluation

The literals are not evaluated in the order in which they are written. The compiler plans the order itself, from estimates of how many solutions each literal has, given the variables that are known at that point. A guard can therefore come before the list it filters:

select ?x where
    ?x > 1
    ?x <- [1, 2, 3]
// [2, 3]

The order of the results follows the plan and is not specified. Here the compiler loops over ?b outermost:

select (?a, ?b) where
    ?a <- [1, 2, 3]
    ?b <- [2, 3]
// [(1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3)]

Sort the result if the order matters.

The plan must give every query variable a value. A guard never does: it only tests values that other literals have computed. A <- literal needs its list, and = one of its sides. When no order works, the compilation fails with Failed to compile the query. and Unsolved variables:, followed by the variables that could not be solved. The list is empty if the variable occurs only in guards:

select ?x where ?x > 1
// Failed to compile the query.
// Unsolved variables:

select first and select distinct

select first returns the first solution as a Maybe, and stops searching when it has found one:

firstBig :: [Integer] -> Maybe Integer
firstBig l = select first ?x where
    ?x <- l
    ?x > 5

// firstBig [3, 7, 9]  ==  Just 7
// firstBig [1, 2]     ==  Nothing

select distinct leaves out repeated results. Of equal results it keeps the first, in the order in which the solutions are found:

select distinct ?x where ?x <- [1, 1, 2, 1]         // [1, 2]
select distinct ?x where ?x <- [3, 1, 3, 2, 1]      // [3, 1, 2]

Types

A select is an ordinary expression of type [a], or Maybe a for select first. It has no effect of its own, so it can be used in a pure function:

evens :: [Integer] -> [Integer]
evens l = select ?x where
    ?x <- l
    ?x `mod` 2 == 0

Where another type is expected, the error is Select expression produces a list of values. or Select first expression produces an optional value.

The query block extends as far as the layout allows, so a select inside a tuple, a list or a function argument must be put in parentheses. Without them, the comma that follows the query is a syntax error:

((select ?x where ?x <- [1, 2]), 3)             // ([1, 2], 3)

Queries can be nested, and the inner query can use the variables of the outer one:

select (?x, ?ys) where
    ?x <- [1, 2]
    ?ys = select ?y where ?y <- [1, 2, 3]; ?y > ?x
// [(1, [2, 3]), (2, [3])]

Combining queries

Four operators combine the literals of the block that follows them:

  • <&>: all the literals hold, as in a plain block. Use it to group several literals into one alternative of <|>.
  • <|>: one of the lines holds. The solutions of all the alternatives are returned, and duplicates are kept.
  • <!>: the block has no solution.
  • <?>: parsed, but not implemented. The compiler crashes with UnsupportedOperationException.

Disjunction

select (?x, ?kind) where
    ?x <- [1 .. 6]
    <|> <&> ?x < 3
            ?kind = "small"
        <&> ?x > 4
            ?kind = "big"
// [(1, "small"), (2, "small"), (5, "big"), (6, "big")]

Every alternative must give a value to the same new variables. If one of them does not, the compiler crashes with Variable ?y_temp (with type ...) is not given value anywhere.

The alternatives can also be guards alone, which test values that the rest of the query computes:

select ?x where
    ?x <- [1 .. 6]
    <|> ?x < 2
        ?x > 4
// [1, 5, 6]

A solution is returned once for each alternative that it satisfies, so here 2 comes twice:

select ?x where
    ?x <- [1 .. 6]
    <|> ?x < 3
        ?x `mod` 2 == 0
// [1, 2, 2, 4, 6]

To return each solution once, write a single guard with || instead:

select ?x where
    ?x <- [1 .. 6]
    ?x < 3 || ?x `mod` 2 == 0
// [1, 2, 4, 6]

Negation

select ?x where
    ?x <- [1 .. 5]
    <!> ?x <- [2, 4]
// [1, 3, 5]

A negated block can only test variables that the rest of the query gives values to. A query variable or a _ that occurs only inside the block cannot be solved:

select ?x where
    ?x <- [1 .. 3]
    <!> (?x, ?y) <- [(1, 10), (2, 20)]
// Failed to compile the query.
// Unsolved variables: ?y

To say "there is no y such that ...", declare y local to the block with exists. It must be the first literal of the block, and its variables are ordinary names, without ?:

select ?x where
    ?x <- [1 .. 3]
    <!> exists a b
        (a, b) <- [(1, 10), (2, 20)]
        a == ?x
// [3]

exists can start any query block. Inside <!>, two cases currently fail. A relation defined in a block (see Relations defined in a block) whose arguments are not all known outside the negation crashes the compiler with iterateMSet could not handle mode CHECK. A pattern that mixes an exists variable with an outer variable, such as (?x, y) <- list, produces a module that fails to load with a VerifyError. Match with new variables and compare them in a guard, as above, or negate a helper relation whose arguments are all known, as under Negation in rules.

Transitive closure

tc R a b holds when b can be reached from a through a chain of zero or more R facts. Either a or b must be known. A relation with more than two arguments can be used too: the first and the last argument are the ends of the chain, and the arguments between them must be known and stay the same in every step.

do
    Edge ?a ?b :- (?a, ?b) <- [(1, 2), (2, 3), (4, 5)]
    ((sort (select ?x where tc Edge 4 ?x)),
     (sort (select ?x where tc Edge ?x 3)))
// ([4, 5], [1, 2, 3])

The closure includes the starting point itself. With both ends unknown, the compiler crashes with UnsupportedOperationException: boundVariables = 0. The current compiler also prints debugging lines to the standard output whenever it compiles a tc literal.

# is not a query operator

The grammar accepts # next to the query operators, but it belongs to the Simantics Variable API rather than to queries:

  • v#name, with no space around #, is the value of the property name of the Variable v, read with the <ReadGraph> effect, as v.name is its child name in a module without the fields feature. In a chain, v#a#b is the value of property b of property a.
  • #name alone refers to a value named #name. No module can define such a name, so it is Couldn't resolve #name. unless the context that compiles the expression provides it.
  • a # b, with a space after #, is an ordinary operator. Simantics/DB defines (#) :: Resource -> Resource -> <ReadGraph> [Resource], the objects of the statements of a with the predicate b.

Relations

A relation is a named set of facts. A query literal R a1 ... an tests the facts of R or searches them for the values of unknown arguments, and enforce can add facts to some relations.

Built-in relations

The Builtin module, which every module and script sees, defines four relations:

Relation Meaning
Eq a b a equals b; the literal a = b is this relation
Optional x m m is Just x
Execute action can only be enforced, which runs the action
Execute10 action as Execute, but in phase 10 of a transformation
lookupAll :: [Maybe Integer] -> [Integer]
lookupAll l = select ?x where
    ?m <- l
    Optional ?x ?m

// lookupAll [Just 1, Nothing, Just 3]  ==  [1, 3]

pattern <- list is a built-in relation as well, without a name. In a query, Execute and Execute10 cannot be solved (Failed to compile the query.).

Relations defined in a block

In a do, let or where block, a statement of the form Name arguments :- query is a rule that defines a relation local to the block, in the manner of Datalog:

reachable :: [(Integer, Integer)] -> Integer -> [Integer]
reachable edges start = do
    Edge ?a ?b :- (?a, ?b) <- edges
    Path ?a ?b :- Edge ?a ?b
    Path ?a ?c :- Path ?a ?b; Edge ?b ?c
    sort (select ?x where Path start ?x)

// reachable [(1, 2), (2, 3), (3, 1), (4, 5)] 1  ==  [1, 2, 3]

The head Name arguments holds for every solution of the body. Several rules for the same name add up, and rules may use each other and themselves. The arguments of the head are expressions over the variables of the body, and the body must give a value to every query variable in the head. A head variable without one crashes the compiler with Variable ?y (with type ...) is not given value anywhere. All the rules of a relation must have the same number of arguments (Different rules have different relation arity.), and a head that is not of the form Name arguments is Invalid rule head.

A rule with an empty body, written {}, is a fact:

do
    Parent "Ann" "Bob" :- {}
    Parent "Bob" "Cid" :- {}
    Parent "Bob" "Dan" :- {}
    Grandparent ?g ?c :- Parent ?g ?p; Parent ?p ?c
    sort (select ?c where Grandparent "Ann" ?c)
// ["Cid", "Dan"]

and a head may compute its arguments:

do
    Even 0 :- {}
    Odd (?n + 1) :- Even ?n; ?n < 9
    Even (?n + 1) :- Odd ?n; ?n < 9
    sort (select ?n where Even ?n)
// [0, 2, 4, 6, 8]

Adjacent rule statements form a group. The relations of a group can be used in all of its rules and in the rest of the block after it, but not in the statements before it.

When the block is evaluated, the relations of a group are computed completely, bottom up, until no rule adds anything new. The facts are kept in a set, so a fact is never repeated, and a query sees them in no particular order:

do
    R ?x :- ?x <- [1, 1, 2]
    R ?x :- ?x <- [2, 3]
    sort (select ?x where R ?x)
// [1, 2, 3]

Relations defined in a block add no effect to the function that defines them, so reachable above is a pure function. They have no sections, unlike the module-level relations below, and enforce cannot add facts to them.

Negation in rules

A rule can negate a relation of its block if the negated relation does not depend on the rule's own relation. Recursion through a negation is rejected with Recursion must not contain negations or aggragates. (sic).

do
    Edge ?a ?b :- (?a, ?b) <- [(1, 2), (2, 3), (3, 4)]
    Node ?a :- Edge ?a _
    Node ?b :- Edge _ ?b
    HasSuccessor ?a :- Edge ?a _
    Sink ?a :- Node ?a; <!> HasSuccessor ?a
    select ?a where Sink ?a
// [4]

HasSuccessor is a helper relation of the kind recommended under Negation: writing <!> Edge ?a _ in Sink would leave _ unsolved.

A known defect affects recursive rules. When the body matches a pattern that mixes a variable bound by the recursive literal with a new variable, the compiler crashes with Variable ?b_temp (with type ...) is not given value anywhere. Match the whole element with new variables and compare them in a guard instead:

Below ?c :- Below ?b; (?b, ?c) <- edges                // crashes
Below ?c :- Below ?b; (?p, ?c) <- edges; ?p == ?b      // works

The same applies to mapping rules.

Relations defined at module level

At the top level of a module, :- defines a relation that other modules can import like a value. Its body is divided into sections, and each section starts with an annotation that says when the section is used:

Between ?lo ?hi ?x :-
    @bbb 0.5
    ?lo <= ?x
    ?x <= ?hi

    @bbf 10
    ?x <- [?lo .. ?hi]

main :: ([Integer], [Integer])
main = ((select ?x where Between 1 5 ?x; ?x > 3),
        (select ?x where ?x <- [0, 3, 9]; Between 1 5 ?x))
// ([4, 5], [3])

The letters name a binding pattern, one letter for each argument: b means that the argument is bound, that is, its value is known when the relation is used, and f that it is free and the section must compute it. The number after the pattern is optional. It estimates how many solutions the section has for one combination of bound values, and the compiler uses it to plan queries. The default is 10, and a number below 1 suits a section that only tests.

When a query uses the relation, the compiler takes the first section whose b arguments are all known at that point. Above, Between 1 5 ?x alone uses @bbf, while in ?x <- [0, 3, 9]; Between 1 5 ?x the compiler computes ?x first and uses the cheaper @bbb. Put the more specific sections first: a section that an earlier one covers would never be used, and it is rejected with Query section is redundant because the previous sections cover it. When no section fits, the query cannot be solved: select ?lo where Between ?lo 5 3 is Unsolved variables: ?lo.

A section can have query variables of its own:

Neighbour ?a ?b :-
    @bf 2
    ?d <- [-1, 1 :: Integer]
    ?b = ?a + ?d

// select ?b where Neighbour 5 ?b  ==  [4, 6]

An @enforce section says what enforce does for the relation, see enforce. Its optional number is the phase in which a transformation enforces the relation. A relation may have an @enforce section and no query sections at all.

The current compiler restricts module-level relations in several ways:

  • A relation has exactly one definition: Does not yet support definition of relations by more than one rule.
  • The head is the name of the relation followed by at least one argument, and the arguments must be variables. A head without arguments, or an operator such as ?x <~ ?y, is A relation definition starts with the relation name followed by its parameters, which are variables such as ?x., and an argument such as 1 is A parameter of a relation must be a variable, such as ?x.
  • Every literal of the body must follow a section annotation. A body that starts without one is The relation has no section annotation before its first query.
  • The estimate after a binding pattern must be written as a number, and the phase after @enforce as an integer. Otherwise the error is The selectivity of a query section must be a number. or The phase of @enforce must be an integer.
  • A relation cannot use itself, directly or through other module-level relations: the compiler crashes with a StackOverflowError. Define recursive relations in a block.
  • A relation cannot depend on a type class. The types of its arguments are inferred from its sections, and a class constraint such as Ring a cannot be part of them. A numeric literal therefore needs a type annotation, as in Neighbour. Without it the error is Constraint is not given and cannot be derived.

The Data/XML module defines its Element, Attribute and TextContent relations this way, with query sections for several binding patterns and @enforce sections that change the document.

enforce

enforce makes the literals of a block true, one after another in the order in which they are written, and returns ():

main = do
    enforce
        Execute (print "first")
        Execute (print "second")
    "done"

prints first and second. What making a literal true means depends on its relation:

Literal What enforce does
Execute action, Execute10 action runs the action
a module-level relation enforces the literals of its @enforce section
Statement s p o of Minigraph adds the statement to the graph
a relation of an ontology module claims the statement, or sets the property value

For example,

Logged ?message :-
    @enforce
    Execute (print ("log: " + ?message))

main = do
    enforce
        Logged "starting"
        Logged "stopping"
    "done"

prints log: starting and log: stopping.

Every value must be known: a query variable in an enforce block is QExists does not support enforcing. Other literals are not supported, and most of them crash the compiler:

Literal Result
pattern = expression UnsupportedOperationException: EqRelation does not support enforce.
pattern <- list UnsupportedOperationException: MemberRelation does not support enforce.
a guard UnsupportedOperationException: CheckRelation does not support enforce.
a relation defined in a block UnsupportedOperationException: LocalRelation does not support enforce.
a module-level relation without @enforce NullPointerException
a disjunction block QDisjunction does not support enforcing.

Phases do not matter to enforce itself: Execute10 runs in its place in the block like any other literal. Phases only order the actions of a transformation.

Known defect: the type checker does not see the effects of what enforce runs, nor the effects of the relations that a query reads. The function shout s = enforce Execute (print s) can be declared String -> (), and a query over graph relations does not require <ReadGraph>. Declare the effects yourself, and make sure that code using graph relations runs in a transaction.

Minigraph

The built-in module Minigraph contains a tiny in-memory graph for testing. It is enough to try queries and enforce on graph-shaped data without a database:

import "Minigraph"

main = withGraph do
    inverseOf = resource "Layer0/InverseOf"
    hasChild = resource "hasChild"
    hasParent = resource "hasParent"
    a = resource "a"
    b = resource "b"
    c = resource "c"
    enforce
        Statement hasChild inverseOf hasParent
        Statement a hasChild b
        Statement a hasChild c
    (sort (map uriOf (select ?x where Statement a hasChild ?x)),
     map uriOf (select ?p where Statement ?p hasChild c))
// (["b", "c"], ["a"])

withGraph runs an action with a new, empty graph. resource returns the resource with the given URI and creates it if needed; resources are integers. uriOf returns the URI, and Statement subject predicate object is the relation of the statements of the graph. As in the Simantics database, a query must know the predicate, and subjects can only be searched through an inverse relation, which is declared with Layer0/InverseOf.

Ontology relations

In Simantics, an ontology module exports the relations of the ontology as SCL relations, under the same names as their resources. With import "http://www.simantics.org/Layer0-1.1" as L0, the query literal L0.ConsistsOf ?parent ?child reads statements from the database, and enforcing it claims a statement. A functional property relation with a known value type, such as L0.HasName, relates a resource to the value of the property instead: a query reads the value and enforce sets it. The subjects of a statement can be searched only if the relation has an inverse, and a property relation cannot be searched by its value. Queries need a read transaction and enforce a write transaction, which the compiler does not check.

Mapping rules and transformations

A mapping relation is a function from source values to target values that a transformation builds up while it runs. It is declared at module level with its source and target types:

mapping relation PathOf String String

A mapping rule is a module-level declaration whose body is divided into sections. A transformation matches the literals of the rule's @when and @from sections, and for every match it enforces the literals of its @to and @where sections. A transformation expression runs the mapping rules of its module, starting from the mapping facts listed after where, its seeds:

childrenOf :: String -> [String]
childrenOf "root" = ["a", "b"]
childrenOf "a" = ["c"]
childrenOf _ = []

mapping relation PathOf String String

rule Children where
    @when
    PathOf ?node ?path

    @from
    ?child <- childrenOf ?node

    @where
    PathOf ?child (?path + "/" + ?child)

rule Report where
    @when
    PathOf ?node ?path

    @to
    Execute (print "\(?node) is at \(?path)")

main = transformation OneShotForward where
    PathOf "root" "/root"

prints

b is at /root/b
c is at /root/a/c
root is at /root
a is at /root/a

and returns (). A transformation runs in two steps:

  1. Matching. The seeds map their sources, here "root" to "/root". A mapping literal in a matched section, such as PathOf ?node ?path, matches every source that has been mapped. A mapping literal in an enforced section maps a new source, here each child of a matched node, and the new source can be matched in turn, by any rule. This repeats until nothing new is mapped.
  2. Enforcing. The other literals of the enforced sections are then enforced, as by enforce, once for every match of their rule. First come the literals of phase 0 of all the rules, rule by rule, then those of phase 10 (Execute10, and module-level relations whose @enforce section has phase 10), and so on. The rules of one module come in source order. The transformation expression below orders the rules of several modules.

The order in which the matches of a rule are enforced is not specified. As the output above shows, it need not be the order in which the sources were mapped.

The target of a mapping literal in a matched section, ?path above, can only be used in the enforced sections. A guard such as ?path != "/root" in @when cannot be solved (Unsolved variables: ?path).

Writing mapping rules

  • Literals before the first section annotation belong to @when.
  • In @where, a literal Name a b whose name is not a declared mapping relation declares one implicitly, with types inferred from its use, even if a relation of that name exists. Put all other literals in @to. Execute in a @where section, for instance, becomes a mapping relation and fails with An arity of mapping relation should always be 2.
  • The source of a mapping literal in an enforced section must be known from the matched sections: Cannot resolve the variable ?b using the source patterns.
  • A mapping relation is a function. Mapping a source to two different values fails at run time with a RuntimeUnificationException. The values are unified rather than compared, so two rules can each give a part of a structured value, such as (1, ?x) and (?y, 2), which together make (1, 2).
  • A query variable of an enforced section that the matched sections do not bind gets its value in one of two ways. If it is the target of a mapping literal, it is the value mapped to that source, shared with every other rule that maps the same source. Otherwise, or if no rule gives the source a value, it is a new default value: a new resource for Resource, "" for String, a new element for the Element type of Data/XML, and a tuple of default values for a tuple type. Any other type fails at run time with Cannot generated default instance for type ... (sic).

The sections that a mapping rule can have are

Section What a transformation does with it
@when matches it
@from matches it
@to enforces it
@where enforces it; also declares mapping relations implicitly
@fromCondition matches it
@fromEnforce, @fromDefault enforces it
@toCondition, @toEnforce, @toDefault ignores it

Any other name is Invalid section name foo. The names come from a design for transformations in both directions, in which @from and @to describe the source and target patterns, @when and @where the mappings that a rule needs and creates, and a backward transformation would match @to and enforce @from. Only the forward transformation is implemented, so apart from the implicit declarations in @where, @when works like @from and @where like @to.

Abstract rules

An abstract rule is not run by a transformation itself. Other rules include its sections with extends:

mapping relation M Integer Integer

abstract rule Positive where
    @when
    M ?a ?b
    ?a > 0

rule Report extends Positive where
    @to
    Execute (print "\(?a) -> \(?b)")

main = transformation OneShotForward where
    M 1 10
    M 0 20

prints 1 -> 10 only. A rule can extend several rules, rule R extends A, B where, and its sections and those of the rules it extends share variables by name. Each variable may come from only one of the extended rules (Variable ?a is defined in more than one base rule, which is not currently allowed.). An unknown name is Couldn't resolve rule name A., and a cycle of extends crashes the compiler with a StackOverflowError.

The transformation expression

  • Its type is (), and it has the <Proc> effect.
  • The name after transformation is only a label. Every transformation is a one-shot forward transformation, and the examples name it OneShotForward.
  • It runs the rules of the module in which it is written and of every module that this module imports, directly or indirectly, except the abstract ones. The import list does not matter: import "M" () brings in the rules of M too.
  • The rules of a module come in source order, and the modules in the order of their names. This order decides which literals of a phase are enforced first.
  • A rule without matched sections matches once. Such a rule in an imported module therefore runs in every transformation of the modules that import it.
  • The seeds must be mapping literals (Cannot use the query as a seed for the transformation.). The block of seeds may be empty.

Relational queries and CHR

The CHR engine of 4.02 Constraint Handling Rules also has rules, ?x variables and select, but it is a different mechanism:

Relational sublanguage CHR
Facts live in relations: lists, rules, graphs a constraint store
Rules Head :- body derives facts; mapping rules head => body or when head then body
Evaluation a query searches; block relations are computed to a fixed point forward chaining, which can remove facts
Negation <!>, stratified not supported
Writing facts enforce, transformations rule bodies add constraints
In a script queries, enforce, block relations and transformations work does not work

The two meet in a module whose header enables the chr feature. There a plain select is a CHR query. It cannot use the relations of this page, and on a relation defined in a block it crashes with LocalRelation does not support iterate. select first and select distinct remain relational queries, and :- relations and enforce keep working, but rule and transformation are ordinary identifiers, so a chr module cannot have mapping rules.

In scripts and the SCL Console

A script imports StandardLibrary, so queries need no imports:

> select ?x where ?x <- [1, 2, 3]; ?x > 1
[2, 3]
> select first ?x where ?x <- [1, 2, 3]; ?x > 1
Just 2
> enforce Execute (print "enforced")
enforced

A relation can be defined in a do block and used in the same block:

> do
      Small ?x :- ?x <- [1, 2, 3]
      select ?x where Small ?x; ?x > 1
[3, 2]

At the top level of a script, a relation definition is accepted, but each statement is compiled on its own, so the next statement cannot see the relation:

> Small ?x :- ?x <- [1, 2, 3]
> select ?x where Small ?x
Couldn't resolve Small.

Module-level relations with sections, mapping relation and rule are syntax errors in a script. Put them in a module and import the module into the script. A transformation written in the script runs the rules of the modules that the script imports. If a module Paths contains childrenOf, PathOf and the two rules of Mapping rules and transformations,

> import "Paths"
> transformation OneShotForward where
      PathOf "root" "/root"
b is at /root/b
c is at /root/a/c
root is at /root
a is at /root/a

See also 1.18 Modules vs. scripts.

Diagnostics

Message Cause
select needs the ArrayList module, for example through import "StandardLibrary". a select in a module that does not import ArrayList, see Imports
tc needs the MSet module, ... a tc in a module that does not import MSet, see Imports
A relation defined in a block needs the MList and MSet modules, ... relations defined in a block in a module that imports neither, see Imports
transformation needs the MList, MSet and Unification modules, ... a transformation in a module that imports none of them, see Imports
Failed to compile the query. no evaluation order gives every variable a value; Unsolved variables lists them
New existential variables can be defined only in queries. ?x outside a query
Blank variables can be used only in queries. _ in an expression outside a query
Select expression produces a list of values. select where another type is expected
Select first expression produces an optional value. select first where another type is expected
Relation is applied with wrong number of parameters. a query literal with too many or too few arguments
Different rules have different relation arity. the rules of a block relation disagree
Invalid rule head. a block rule whose head is not Name arguments
Recursion must not contain negations or aggragates. recursion through <!>
A relation definition starts with the relation name followed by its parameters, ... a module-level relation without arguments, or with an operator head
A parameter of a relation must be a variable, such as ?x. a head argument of a module-level relation that is not a variable
The relation has no section annotation before its first query. ... a module-level relation body that does not start with a section annotation
Invalid section name 'q'. an unknown section in a module-level relation
The selectivity of a query section must be a number. a binding pattern followed by something other than a number
The phase of @enforce must be an integer. @enforce followed by something other than an integer
Query section is redundant because the previous sections cover it. sections in the wrong order
Does not yet support definition of relations by more than one rule. a module-level relation defined twice
Constraint is not given and cannot be derived. a module-level relation that needs a type annotation
QExists does not support enforcing. a query variable in enforce
QDisjunction does not support enforcing. a <|> block in enforce
Mapping relation M has already been defined. two declarations of one mapping relation
Rule R has already been defined. two rules with one name
Invalid section name foo. an unknown section in a mapping rule
Couldn't resolve rule name A. extends names no rule
Variable ?a is defined in more than one base rule, ... two extended rules share a variable
An arity of mapping relation should always be 2. usually a literal that is not a mapping in @where
Cannot use the query as a seed for the transformation. a seed that is not a mapping literal
Cannot resolve the variable ?b using the source patterns. the source of a mapping in an enforced section is not matched
Cannot generated default instance for type ... at run time: no default value for an unbound target variable

Known defects

The following are defects of the current compiler rather than design decisions. Each is described in its section above.

  • <?> crashes the compiler.
  • Inside <!>, a block relation with unknown arguments crashes the compiler, and a pattern that mixes an exists variable with an outer one produces a module that fails to load.
  • tc prints debugging output, and crashes the compiler if neither end is known.
  • A recursive rule that matches a pattern mixing a variable of the recursive literal with a new one crashes the compiler.
  • A recursive module-level relation crashes the compiler, and a module-level relation can have only one definition.
  • Several literals that enforce does not support crash the compiler instead of being reported as errors.
  • The effects of enforce and of the relations that a query reads are not checked.
  • A cycle of extends crashes the compiler.
  • A head variable that the body does not bind, and an alternative of <|> that leaves a variable without a value, crash the compiler instead of being reported as errors.

Further examples

The compiler's regression fixtures contain working queries, relations and transformations:

tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Select*.scl
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Relations*.scl
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Transformation*.scl

Each file contains the module text, a -- separator and the expected output. In the bundle org.simantics.scl.data, the Data/XML module defines module-level relations over XML documents, and the examples folder has transformations from one XML document to another.