9. Expressions
An expression computes a value. Expressions appear in conditions, assignments, arguments, return
statements, initial values, values clauses, where clauses, annotations, and — through the binding entry
point — in the data bindings of user interfaces and inspectors.
FML expressions are evaluated by Connie, the expression language of the platform. They look like Java
expressions and mostly behave like them; the differences are specified in this chapter and are not details:
division is decimal and strings are never converted to numbers. As in Java, && and || short-circuit (§9.3), and a
path that does not resolve, or goes through a null value, is an error when it is evaluated (§9.8).
9.1 Syntax
expression = left_hand_side assignment_operator expression
| conditional_exp
conditional_exp = conditional_or_exp
| conditional_or_exp "?" expression ":" conditional_exp
conditional_or_exp = conditional_and_exp { "||" conditional_and_exp }
conditional_and_exp = inclusive_or_exp { "&&" inclusive_or_exp }
inclusive_or_exp = exclusive_or_exp { "|" exclusive_or_exp }
exclusive_or_exp = and_exp { "^" and_exp }
and_exp = equality_exp { "&" equality_exp }
equality_exp = relational_exp { ( "==" | "!=" ) relational_exp }
relational_exp = shift_exp
| shift_exp ( "<" | ">" | "<=" | ">=" ) shift_exp
| shift_exp "instanceof" type dim*
shift_exp = add_exp { ( "<<" | ">>" | ">>>" ) add_exp }
add_exp = mult_exp { ( "+" | "-" ) mult_exp }
mult_exp = unary_exp { ( "*" | "/" | "%" ) unary_exp }
unary_exp = "++" unary_exp | "--" unary_exp | "+" unary_exp | "-" unary_exp
| "~" unary_exp | "!" unary_exp
| "(" type dim* ")" unary_exp (* cast *)
| postfix_exp
postfix_exp = primary | postfix_exp "++" | postfix_exp "--"
primary = composite_ident | primary_no_id
primary_no_id = literal
| "(" expression ")"
| field_access
| method_invocation
| new_instance
9.2 Operators and precedence
From the tightest binding to the loosest:
| Level | Operators | Associativity |
|---|---|---|
| 1 | postfix ++ -- | left |
| 2 | ! ~ cast (T) | right |
| 3 | prefix ++ --, unary + - | right |
| 4 | * / % | left |
| 5 | + - | left |
| 6 | << >> >>> | left |
| 7 | < > <= >= instanceof | none |
| 8 | == != | left |
| 9 | & | left |
| 10 | ^ | left |
| 11 | | | left |
| 12 | && | left |
| 13 | || | left |
| 14 | ? : | right |
| 15 | = += -= *= /= %= <<= >>= >>>= &= ^= |= | right |
The relational operators are non-associative: a < b < c does not parse. Parentheses group:
2 + 3 * 4
(2 + 3) * 4
The conditional operator may be nested in either branch:
n > 0 ? "pos" : (n < 0 ? "neg" : "zero")
The operators supported by the evaluator are the binary && || == != < <= > >= + - * /
% << >> >>> & | ^ and =, +=, and the unary ! + - ++ -- ~.
9.3 Boolean operators short-circuit
As in Java, && does not evaluate its right operand when the left one is false, and || does not evaluate it when
the left one is true.
public int andOperands() {
touched = 0;
if (false && this.touch() == 1) {
touched = touched + 100;
}
return touched;
}
Here touch() is not called: the left operand is false, and andOperands() returns 0. So a guard can be written in
one expression: p != null && p.name == "Ann" does not evaluate p.name when
p is null.
Before 3.0 (CORE-F-11), both operands were evaluated, and a guard had to be written with
nested ifs.
9.4 Literals and values
An expression works with integers, decimals, strings, characters, booleans, null, and the instances of
concepts (§2.6). The null literal designates the absence of a value (§13.6).
9.5 Numbers and strings
9.5.1 Arithmetic
+,-and*between two integers give an integer. Between an integer and a decimal they give a decimal./and%give a decimal, even between integers:7 / 2is3.5,6 / 3is2.0,7 % 2is1.0. The declared type of the behaviour does not change this.- A cast
(int) dtruncates a decimal to an integer:(int) 3.7is3. The cast is the only way to obtain an integer from a division.
9.5.2 Strings
+concatenates when its left operand is a string; a number, a boolean, an instance ornullon the right is written as text ("a" + 1is"a1","x" + nullis"xnull"). An instance is written by its string representation (the@Rendererof its concept, §11.4).1 + "a"is a type error and stops the behaviour.- A string is never a number.
"4.5" * 1.0is an error. To convert, call a Java method: import the class and use the simple name —import java.lang.Double;thenDouble.parseDouble("4.5"). ==between two strings compares their contents, not their identity.- The Java methods of a string are available on a variable, a parameter or a property
(
s.toUpperCase(),s.replace("a", "b").length()).
A method called directly on a string literal, "hello".length(), does not resolve: an
execution error when it runs, a null without a message before 3.0 (CORE-D-19). Put the literal in a variable first.
9.5.3 Comparison
== and != compare numbers by value, strings by contents, and instances of concepts by identity. <, <=,
>, >= compare numbers. Comparing a value with null is written == null.
An enum value is compared with == to another value of the same enum. In a script, an enum read as a
property must be compared through toString() (§12.7).
9.5.4 Lists
A Java list is created with new ArrayList<Type>() and used with its Java methods (add, get, size,
contains). Multi-valued properties (§6.3) are lists.
9.6 Paths
A path designates a value by following properties and calls: guest.name, fiction.books.size,
this.container.label, shelf.newBook("x").title.
9.6.1 Syntax
composite_ident = identifier_prefix* ( lidentifier | cidentifier | escaped_identifier | keyword5 )
identifier_prefix = lidentifier "." | escaped_identifier "."
keyword5 = "concept" | "create" | "get" | "model" | "set"
field_access = "super" "." lidentifier
| composite_ident "." "super" "." lidentifier
| primary_no_id "." ( lidentifier | keyword5 )
method_invocation = primary "(" argument_list? ")"
| "super" "(" argument_list? ")"
| type "." lidentifier "(" argument_list? ")" (* static call *)
Three consequences of this syntax:
- every intermediate element of a dotted name is a
lidentifier(property names start with a lowercase letter or underscore); the last element may also be a constant identifier or one of the five keywords of §2.3.2; - a call is applied to a primary, so
a.b(1).canda.f().g()are paths; a call may follow a call; - a static call is
Type.method(args), with the type in the typing space (§4.8) or fully qualified (java.lang.Double.parseDouble(x)). There is no syntax to read a static field.
select … is not an expression: (select T from x).size does not parse. Assign the result, or put it in a
behaviour (§10.2).
9.6.2 Resolution
A path is resolved step by step against types. The first element is looked up in the binding model in scope (§9.6.3); each following element is looked up in the type of the previous one. The elements that can be found, in the order in which they are tried for a concept instance, are
- a property of the concept or of its ancestors;
- a behaviour of the concept or of its ancestors (for a call);
- a native property of the runtime object, such as
container(the instance that contains it), and, for lists,size,get(i), …
For an object of a Java type, the elements are the Java getters, fields and methods that the type exposes. For an object of a technology-specific type, they are those the adapter exposes (§4.7).
A concept instance exposes to a path only its properties and its behaviours (plus the native properties):
Java methods of the underlying runtime object — toString(), hashCode() — are invalid bindings on it. To display
an instance, use string concatenation; to reach a platform method, bind a cast to a local variable first (see
below).
((FMLRTVirtualModelInstance) this).refreshModelSlot("x") evaluates to null;
the cast must be bound to a local: FMLRTVirtualModelInstance vmi = (FMLRTVirtualModelInstance) this; vmi.refreshModelSlot("x");. Validation reports the inline form as an unresolved path element.
9.6.3 The scope of a bare name
A name that begins a path is looked up outward, from the innermost scope:
- the local variables of the enclosing blocks;
- the arguments of the behaviour;
- the properties of the concept, including inherited ones;
- the properties of the enclosing concept or model, outward to the model.
The built-in names are always available:
| Name | Denotes | Available in |
|---|---|---|
this | the current instance | every behaviour, expression property, invariant |
container | the instance that contains this | every behaviour |
parameters | the arguments of the running behaviour: parameters.x (deprecated, use x) | every behaviour |
super | the parent concept (§5.3.2) | behaviours of a concept with a parent |
evt | the event being handled | a listen body |
selected | the candidate under examination | a where clause of a select (§10.2) |
value | the value being assigned | a set body (§6.7) |
instance | the instance being rendered or inspected | a @Renderer expression (§11.4) |
The two forms to remember are
- an argument is designated by its name, and hides a property of the same name (
this.namereaches the property).parameters.nameis the deprecated notation of the same argument (§7.2.1); - a behaviour of the same instance is called on
this: a bare call is an invalid binding too.
A local variable, or an argument, hides a property of the same name; this.name still reaches the property. The property of a
nested concept hides that of its container; container.name reaches the container's.
For the model NameLookup, whose Item has name and label and whose model has owner and label, in a
behaviour of Item named Pen:
| Expression | Value |
|---|---|
name | "Pen", the property of the concept |
this.name | "Pen" |
owner | "Ann", the property of the model |
container.label | the label of the model |
label | the label of the item: the concept's property wins over the model's |
9.6.4 Calls
A call target.name(args) is resolved by name, number of arguments and types (§7.4). The call of a behaviour
of the same instance is this.name(args). A call may be used as a value or as a statement.
An argument list is a comma-separated list of expressions.
9.6.5 Lexical context: this, container, super
Inside a behaviour of a nested concept, two independent structures determine what a name designates:
- containment, which is the lexical nesting of the declarations (§5.2.1): a concept declared in a concept, declared in a model.
At run time each instance lives in an instance of its enclosing declaration, and
containerdesignates it; - inheritance (§5.3): a concept extending another one has its properties and behaviours, and may override them.
thisandsuperdesignate the current instance, at the level of its own concept and at the level of its parent.
The two never mix: what a concept contains, or what contains it, is not inherited, and a parent is not a container. The
model TestLexicalContext declares a behaviour toto() at each of the four places where it can be (excerpt):
public model TestLexicalContext {
public concept ConceptA {
public String toto() {
log "toto() in A";
return "A";
}
public concept IConceptB {
public String toto() {
log "toto() in IB";
return "IB";
}
}
public concept ConceptB extends IConceptB {
public String toto() {
log "toto() in B";
return "B";
}
public String testToto() {
log "Case 1 :";
String r1 = this.toto(); // B
log "Case 2 :";
String r2 = container.toto(); // A
log "Case 3 :";
String r3 = super.toto(); // IB
log "Case 4 :";
String r4 = container.container.toto(); // root
return r1 + "/" + r2 + "/" + r3 + "/" + r4;
}
}
}
public String toto() {
log "toto() in root";
return "root";
}
}
ConceptB is nested in ConceptA, which is nested in the model; ConceptB extends IConceptB, nested in ConceptA too.
On an instance b of ConceptB created in an instance a of ConceptA, itself in the instance root of the model,
b.testToto() logs the four cases in order and returns "B/A/IB/root":
Call in ConceptB | Receiver | Behaviour run | Why |
|---|---|---|---|
this.toto() | b | toto() of ConceptB | the concept of b declares it |
container.toto() | a | toto() of ConceptA | containment: one level up |
super.toto() | b, at the level of IConceptB | toto() of IConceptB | inheritance: the parent's version |
container.container.toto() | root | toto() of the model | containment: two levels up |
A call is resolved in two steps.
- When the unit is analysed, the receiver is typed:
thisby the current concept;containerby the enclosing concept, or the model for a concept declared at its root (for a contained model, its container model, §5.1.4);superby the parent concept (§5.3.2);x.containeris the native propertycontainerof the instancex(§9.6.2). The behaviour named by the call is looked up in that type and its ancestors (§7.4). This decides whether the call is valid and what type it has. - When it runs, the receiver gives an instance, and the behaviour run is the most specialized version of the one found in
step 1 for the concept of that instance (late binding, §5.3.1). So
this.toto(), written inIConceptBand called on aConceptB, runs thetoto()ofConceptB. The one exception issuper: it designates the same instance, but the lookup starts at the parent concept, sosuper.toto()runs thetoto()ofIConceptBalthoughbis aConceptB.
The toto() of ConceptA is not a behaviour of ConceptB: it is reached through container only, and container.toto()
runs it whatever ConceptB declares. Each container. climbs one level of containment, whatever the inheritance of the
concepts on the way.
Properties follow the same rules with the same receivers. With a property level declared at each of the four places
("root", "A", "IB", "B"), in a behaviour of ConceptB, this.level is "B", container.level is "A" and
container.container.level is "root". A property is late bound like a behaviour: ConceptB redeclares the level of
IConceptB (§5.3.1), and this.level, or level, written in IConceptB and read on a ConceptB, is "B".
Unlike a behaviour, a property is also reached by its bare name, which follows the scopes of §9.6.3 outward: the properties
of the concept and its ancestors first, then those of the enclosing concepts, then those of the model. The value read is that of
the instance that contains the current one, not of any instance of the enclosing concept: with a property inA of ConceptA and
two instances a1 and a2 holding "a1" and "a2", the bare inA is "a1" in a ConceptB of a1 and "a2" in a
ConceptB of a2. A property declared both in a concept and in one of its containers is reported by the validation as
shadowing the other (a warning); the bare name then designates the nearest one, the concept's own or inherited.
The model and its script are FML/TestLexicalContext.fml and AutomatedTests/TestLexicalContext.fmlscript of the test
resource center, which assert every value given here.
super.name, where name is a property, evaluates to null with a warning and no error, even when
the concept does not redeclare the property (CORE-D-99). Read an inherited property with this.name. What super.name gives
when the concept redeclares the property is not specified by this document.
9.7 Creating instances: new
new_instance = ( composite_ident "." )? "new" reference_type "(" argument_list? ")" with_clause?
| ( composite_ident "." )? "new" uidentifier "::" lidentifier "(" argument_list? ")" with_clause?
with_clause = "with" fml_parameters
new creates an instance of a concept, of a virtual model, or of a Java class, according to what the
type resolves to:
public Task addTask(String label) {
Task task = new Task(label);
tasks.add(task);
return task;
}
public List<Task> fresh() {
List<Task> l = new ArrayList<Task>();
return l;
}
- A concept — the arguments are those of a creation scheme (§7.3.1). The second form,
new Shelf::named(args), names the creation scheme. The new instance is created in the nearest object that can hold it, found by climbing the containment tree fromthis, or from the object that the prefixcomposite_ident.designates inc.new X(args)(chapter 14). - A virtual model — a new virtual model instance, which needs a
with (name = "…"). - A Java class — the Java constructor is called; the
withclause is not used.
Where the instance goes is the subject of chapter 14:
new X()andc.new X()climb the containment tree to the nearest object that can hold anX. Anewthat no object can hold is an invalid binding: it is reported when the unit is validated and, as any invalid binding (§9.8), it is an execution error at run time.
The with clause supplies the parameters of the instantiation of a virtual model: name (mandatory; the name of
the instance), and, where relevant, virtualModelInstanceTitle, uri, rc (the resource center),
path and folder.
list = new TaskList() with (name = "groceries");
The arguments must match a creation scheme in number (§7.2). A concept that declares no creation scheme is created with no argument.
9.8 Null
null belongs to every non-primitive type and is also the value of an unassigned primitive-typed property
(§4.2). Two different things are called "null" when an expression is evaluated, and they must not be confused:
- a path whose elements do not resolve (a misspelled name, a missing import, a bare call) is an invalid binding: it is reported when the unit is loaded and validated, and evaluating it is an execution error (a resolution error) that stops the behaviour;
- a path that resolves but goes through a
nullvalue (p.namewherepisnull) raises a null reference: an execution error that stops the behaviour, wherever the expression is, in a condition too (§8.4).
A comparison to null is written == null or != null; since && and || short-circuit (§9.3), it guards the rest of
the condition: p != null && p.name == "Ann".
Before 3.0 (CORE-F-11), an invalid binding evaluated to null without any message, and a
null reference in the condition of an if made the condition false. An initial value that goes through a null value
still gives null (§6.2).
9.9 Type tests and casts
e instanceof T tests whether the value of e is an instance of T; T may be a concept (instances of
sub-concepts satisfy it) or a Java type. (T) e is a cast: for a primitive target it converts the number
((int) 3.7); for a reference target it asserts the type for the binding analysis, which is how the members of a
Java type are made available on an expression of a more general type. A cast may be followed by [] in the
grammar; arrays are otherwise not a type of FML (§4.4).
9.10 The binding entry point
An expression alone is an input of the grammar (§1.2). It is how the data bindings embedded in user-interface components and inspectors are parsed. The same expression grammar applies, evaluated in the binding model of the embedding component; the first element of a path is then a variable of that model.
9.11 Evaluation errors
| Situation | Result |
|---|---|
| a path element that does not resolve (invalid binding) | execution error (resolution error): the behaviour stops |
a path through a null value, anywhere (conditions included) | execution error (null reference): the behaviour stops |
| a failure of Java code called from FML | execution error (host error): the behaviour stops |
a type error (1 + "a", "4.5" * 1.0) | execution error: the behaviour stops |
an invalid condition in if / while / for | execution error: the behaviour stops |
Validation (§13.8) reports unresolved paths; it is the only place where they surface before execution.