Type system internals
This page describes how the type system of the toolkit is built inside, and how the EFX-2 translator checks types. It is for contributors who need to understand or change the implementation of the type system. If you are implementing a generator, start with Working with EFX types instead.
This page uses the names of EfxDataType, such as StringScalar and BooleanSequence, to describe the types
inside the toolkit. They are not the same as the Expression classes, such as StringExpression and
BooleanSequenceExpression, that the methods of your ScriptGenerator receive. The EfxDataType interfaces name
the types. The Expression classes stand for the translated values, with their types, that pass through the
translator.
|
The grid of EFX types
The type system of EFX is a grid with two dimensions, called a lattice in the code. One dimension is the basic type, called the primitive in the code. The other is the number of values, called cardinality: a single value (scalar) or a sequence of zero or more values.
Basic type |
Cardinality |
|
|---|---|---|
Scalar |
Sequence |
|
String |
|
|
MultilingualString |
|
|
Boolean |
|
|
Number |
|
|
Date |
|
|
Time |
|
|
Duration |
|
|
Node |
|
|
MultilingualString is a subtype of String, so a multilingual text is accepted wherever a text is. The result of a
dynamic function has its own subtype of Boolean, DynamicScalar (and DynamicSequence), so that the translator
can keep the calls of dynamic functions apart from other indicators.
Marker interfaces
The code builds the grid with marker interfaces, that is, interfaces with no methods, which serve as labels for the
types. They are nested in the interface EfxDataType:
interface Boolean extends Primitive {}
interface BooleanScalar extends Boolean, Cardinality.Scalar, ConcreteScalar {}
interface BooleanSequence extends Boolean, Cardinality.Sequence, ConcreteSequence {}
In Java, an interface can extend several interfaces, so the two dimensions map directly onto Java types. A
BooleanScalar is at the same time a Boolean (basic type) and a Scalar (cardinality). So the code can ask
questions about types with the type system of Java itself:
-
Boolean.class.isAssignableFrom(BooleanScalar.class)returnstrue -
Cardinality.Scalar.class.isAssignableFrom(BooleanScalar.class)returnstrue -
BooleanScalar.class.isAssignableFrom(BooleanSequence.class)returnsfalse
Operations on the grid
The class EfxTypeLattice provides operations to move around the grid:
// Get the primitive type from any variant
EfxTypeLattice.toPrimitive(StringScalar.class) // → String.class
// Convert between cardinalities
EfxTypeLattice.toScalar(String.class) // → StringScalar.class
EfxTypeLattice.toSequence(String.class) // → StringSequence.class
// Check cardinality
EfxTypeLattice.isScalar(StringScalar.class) // → true
EfxTypeLattice.isSequence(StringScalar.class) // → false
Expression hierarchy
Two ways of recording the type
The toolkit records the type of an expression in two ways, side by side:
- Class hierarchy
-
The Java class hierarchy (
StringExpression extends ScalarExpression) lets Java choose the right method for each class, and lets the code test classes withinstanceof. - Annotation
-
The annotation
@EfxDataTypeAssociationdeclares the EFX data type of the class, so that the type checks can read it.
@EfxDataTypeAssociation(dataType = EfxDataType.StringScalar.class)
public class StringExpression extends ScalarExpression.Impl<EfxDataType.StringScalar> {
// ...
}
There are two ways because the class hierarchy records where the value comes from (computed, path or literal), while the annotation records the data type in the grid of EFX types. The toolkit needs both: the class hierarchy to choose the right behaviour for each class, and the annotation for the rules of type checking.
TypedExpression
The expressions that stand for values or paths implement TypedExpression, which gives their data type. The
expressions that are only parts of the structure of an expression, such as IteratorExpression,
IteratorListExpression and DeclarationExpression, do not:
public interface TypedExpression extends Expression {
Class<? extends EfxDataType> getDataType();
boolean is(Class<? extends EfxDataType> dataType);
}
Converting a path between a single value and a sequence
A PathExpression can convert itself between a single value and a sequence. A single value can always become a
sequence of one value:
// A ScalarPath can be widened to a SequencePath
ScalarPath scalar = new StringPath("/some/path");
SequencePath sequence = scalar.asSequence();
// A SequencePath can be narrowed to ScalarPath (use with caution)
SequencePath seq = new StringSequencePath("/some/path");
ScalarPath narrow = seq.asScalar();
The conversion creates a new object with the same script, but another type. TypedExpression.from(expression, type)
converts any expression in the same way, for example a StringPath into the StringExpression of its value.
How the EFX-2 translator checks types
The grammar of EFX-2 describes only the syntax. It has a single rule, expression, for every expression, whatever its
type (see EFX grammar). So the parser accepts BT-00-Text + 1, and the translator rejects
it. The translator finds the type of each part of an expression, and checks it, while it translates.
The visitor and its sub-expressions
The class EfxExpressionVisitor translates the expressions of EFX-2. It visits the parse tree: each visit
translates the parts inside a part of the expression first, and then the part itself. A visit returns a
Subexpression: the translated expression, with its type, and its Origin, that is, what the sub-expression is
written as, such as a field, a node, a variable, a literal or the result of an operator.
The part around a sub-expression decides how it reads it: as a value, as most operators and functions do; as a path,
as is present does; or as the context of the reference after ::. The origin answers each of these readings. A
field, for example, gives its path when it is read as a path, and the value that composeFieldValueReference gives
when it is read as a value. When the reading does not fit, the origin also gives the error that explains why, for
example that a field can have several values from the context.
Constructs, signatures and overloads
Every part of the language that takes arguments is a Construct, checked in the same way:
-
the operators and built-in functions, which the catalogue
BuiltInsholds, in the enumerations of the packageeu.europa.ted.efx.model.builtins; -
the parts that the grammar writes inside an expression, such as parentheses, the conditional, a list, an iteration, a predicate, an index and a context override, in
ExpressionConstruct; -
the functions and templates that a file declares;
-
the clauses of statements and declarations, such as the condition after
WHENor the value of a variable, inClause.
A construct that translates its calls, a Composable, has one Overload for each way in which it can be written. An
overload pairs a Signature, that is, the types of its parameters and of its result, with a Composer, which calls
the method of the ScriptGenerator. For example, the function substring has two overloads:
SUBSTRING("substring",
overload(signature(parameter("value", TEXT), parameter("start", NUMBER)).returning(TEXT),
(script, value, start) -> script.composeSubstringExtraction(value, start)),
overload(signature(parameter("value", TEXT), parameter("start", NUMBER), parameter("length", NUMBER))
.returning(TEXT),
(script, value, start, length) ->
script.composeSubstringExtraction(value, start, length))),
So the catalogue also shows which method of the ScriptGenerator each part of the language calls. Some built-ins
call a method that you might not expect: empty(<text>), for example, is a comparison with the empty text, and each
negative condition, such as not in, is the positive condition followed by composeLogicalNot.
The parameter types are constants of ParameterType:
-
concrete types, such as
TEXT,NUMBERorDATE_SEQUENCE, for a value of one exact type; -
path types, such as
PATHorNODES, for a reference; -
the type variables
TandT_SEQUENCE, for a single value or a sequence of any basic type. A signature that mentions them is generic, as the one ofinis:(needle: T, haystack: T*) → indicator.
Matching a call
For each call, the construct matches the arguments against its signatures:
-
A signature takes the arguments if it takes their number. A generic signature is first bound to the basic type of the argument at the first position of
T. -
Each argument must then convert to its parameter: unchanged, from a subtype (a multilingual text to a text), or from a single value to a sequence of one value. A sequence never converts to a single value.
-
When several overloads take the arguments, the most specific one wins. For example, an overload that takes
Tis more specific than one that takesT*, for a single value.
The chosen overload, with the arguments converted to its parameters, is a Resolution. Its composer then calls the
method of the ScriptGenerator. When no overload takes the arguments, the construct gives a Mismatch, which says
which argument each signature rejects, and why. The translator turns it into a TypeMismatchException, with the
position of the argument in the file, for example:
line 1:21 Type mismatch. Operator '==' cannot take 'text*' and 'text'. Its left operand must be 'text'. Field 'BT-13-Text' may return multiple values from context 'ND-Root': use a sequence expression or change the context.
Types of references
The translator does not compute the type of a reference itself: the symbol resolver gives it. For a field, the
symbol resolver gives the path as an instance of the class that matches the type of the field in the SDK and its
repeatability from the context. XPathSymbolResolver, the base class of SdkSymbolResolver, does it as follows:
if (isFieldRepeatableFromContext(sdkField, context)) {
return SequencePath.instantiate(relativeScript, FieldTypes.fromString(sdkField.getType()));
} else {
return ScalarPath.instantiate(relativeScript, FieldTypes.fromString(sdkField.getType()));
}
The types of variables and parameters come from their declarations, and the types of functions from their signatures.
The type checker of the call stack
The parts of a template file or a rules file that are not expressions, such as template lines, declarations and
rules, are translated by an ANTLR listener (see
Call stack architecture). The listener keeps translated parts on the
CallStack, and takes them off with a type. When it takes a value off the stack, the CallStack asks a
TypeChecker whether the value can be converted to the type requested:
public interface TypeChecker {
boolean canConvert(Class<? extends TypedExpression> from,
Class<? extends TypedExpression> to);
}
The toolkit provides two implementations, TypeChecker.V1 and TypeChecker.V2:
TypeCheckerV1-
A less strict check, for the translators of SDK 1. It lets a
PathExpressionconvert to the abstract typesScalarExpressionandSequenceExpression. TypeCheckerV2-
A strict check, for the translators of SDK 2. It requires concrete types: it accepts a class that the target class can already hold, a subtype of the basic type, and a single value that becomes a sequence. It never lets a sequence become a single value.
// Valid: scalar promotes to sequence
canConvert(StringExpression.class, StringSequenceExpression.class) // → true
// Invalid in V2: sequence cannot narrow to scalar
canConvert(StringSequenceExpression.class, StringExpression.class) // → false
Maps between field types and classes
The toolkit keeps maps between the types of fields in the SDK and the expression classes:
- The enumeration
FieldTypes -
Maps the names of SDK field types, for example "text" and "indicator", to constants.
ScalarExpression.fromFieldType,SequenceExpression.fromFieldType-
Map
FieldTypesto the computed classes, for a single value and for a sequence. ScalarPath.fromFieldType,SequencePath.fromFieldType-
Map
FieldTypesto the path classes, for a single value and for a sequence. ScalarExpression.fromEfxDataType,SequenceExpression.fromEfxDataType-
Map the basic types of
EfxDataTypeto the computed classes.
See also: