Implementing ScriptGenerator

Overview

The interface ScriptGenerator is the main link between the toolkit and your target language. It defines more than a hundred methods, one for each part of the EFX language. During the translation, the toolkit calls these methods with expressions whose types are already known. In return, it expects a piece of code in the target language, in the matching expression class.

There are many methods, but most of them follow the same pattern: they combine the getScript() texts of the input expressions in the syntax of your target language, and put the result in an expression object. A typical method has one to three lines of code. The methods fall into these groups:

  • literals;

  • logical operations;

  • text operations;

  • numeric operations, including the parts of dates and times;

  • date, time and duration operations;

  • paths and field references;

  • sequence operations;

  • conditions on uniqueness and membership, with one method for each data type;

  • formatting;

  • variables, parameters and declarations.

The examples below show typical methods of each group. The other methods of a group follow the same patterns. For the complete list, see the Javadoc of the interface ScriptGenerator, and the reference implementation XPathScriptGenerator.

The examples write JavaScript. This JavaScript calls helper functions, such as getFieldValue, and uses a notice object that stands for the notice. The toolkit does not provide these. Your application provides them when it runs (see Runtime libraries).

The examples follow three rules, which you will need in any target language:

  • Where the meaning of an EFX operation differs from that of the nearest JavaScript operator, the examples call a helper function. For example, two JavaScript Date objects for the same moment are not equal with ===, so the examples compare values with the helper compare.

  • Where the examples write an operator, they put parentheses around the operands that need them, and give the result the precedence of the operation (see Precedence of operations).

  • The names that the examples write never clash. EFX names become JavaScript names that start with $, the names that the examples generate for their own use start with __, and the helper functions start with neither (see Variables and declarations).

Getting started

Your class implements ScriptGenerator directly. There is no abstract base class to extend:

public class JavaScriptScriptGenerator implements ScriptGenerator {

    private final TranslatorOptions translatorOptions;

    public JavaScriptScriptGenerator(TranslatorOptions translatorOptions) {
        this.translatorOptions = translatorOptions;
    }

    // ... implement all methods
}

TranslatorOptions holds the settings of the translation. Keep it in a field, because several methods need it. Its methods are:

  • getPrimaryLanguage2LetterCode() and getPrimaryLanguage3LetterCode(): the primary language for multilingual content;

  • getAllLanguage2LetterCodes() and getAllLanguage3LetterCodes(): all the configured languages;

  • getDecimalFormat(): the format of numbers;

  • getUserDefinedFunctionNamespace(): the namespace of user-defined EFX functions;

  • isProfilerEnabled() and getProfilerOutputPath(): the optional measurement of the time that the translation takes;

  • getIncludedFileResolver(): what reads the files that the #include directives of rules files name.

So that the ComponentFactory can find your implementation, add the annotation @SdkComponent to it, with a qualifier of your own:

@SdkComponent(versions = {"2"}, componentType = SdkComponentType.SCRIPT_GENERATOR, qualifier = "js")
public class JavaScriptScriptGenerator implements ScriptGenerator {
    // ...
}

The qualifier is needed because the toolkit already registers XPathScriptGenerator for SDK 2 without one. Two script generators with the same qualifier stop the toolkit with an error. If your factory creates your class directly, the annotation is not needed. For how to register and put together components, see Assembling and running a translator.

Default methods

Four methods have default implementations, and a translator for EFX-2 does not need to override them:

composeFieldReferenceWithAxis

Deprecated, for EFX-1 only. The default implementation returns the field reference unchanged.

composeExternalReference

Deprecated, for EFX-1 only: references to other notices were removed in EFX-2. The default implementation returns null.

composeFieldInExternalReference

Deprecated, for EFX-1 only. The default implementation returns null.

composeDynamicFunction

Optional. Needed only if your translator supports dynamic functions, which call an external service during validation (see Dynamic function declaration). The default implementation throws UnsupportedOperationException.

How the toolkit calls your methods

Before you look at the groups of methods, look at how the toolkit calls them. To translate an EFX expression such as BT-00-Number > 100, the toolkit calls these methods:

  1. getNumericLiteralEquivalent("100"), which converts the literal;

  2. composeFieldValueReference(NumericPath), which gives the value of the field reference in your target language;

  3. composeComparisonOperation(left, ">", right), which combines both into a comparison. The left operand is the value of the field, converted to a NumericExpression, and the right one the NumericLiteral.

The toolkit translates the operands of an operation before the operation itself, but do not rely on any other order: here, for example, it converts the literal before it reads the field. Each method receives the results of the earlier methods as complete expressions. You never need to translate the parts of an expression yourself, or to decide the order of evaluation: the toolkit does this.

To find out which method a part of the language calls, look at the catalogue of built-ins, in the package eu.europa.ted.efx.model.builtins, and at ExpressionConstruct. Each operator and function there lists its forms, and the method that translates each of them (see Constructs, signatures and overloads). Some calls are not obvious: empty(<text>) calls composeComparisonOperation with an empty text, and each negative condition, such as not in, calls the method of the positive condition followed by composeLogicalNot.

Precedence of operations

When your method combines its operands into an operation, it must also put parentheses around an operand where the grouping of the EFX expression needs them, and give the result the precedence of the operation. Otherwise, the negation of the EFX condition $a and $b becomes !$a && $b, which JavaScript reads as (!$a) && $b. For how the XPath implementation does this, see Precedence.

The examples on this page use the same helper method as the XPath implementation:

private static String operand(Expression operand, Precedence required) {
    return operand.getPrecedence().bindsAtLeast(required)
        ? operand.getScript()
        : "(" + operand.getScript() + ")";
}

The precedence rules of JavaScript are not those of XPath, but the values of Precedence are enough for the examples. A result that is a call, a literal or a name needs no precedence of its own: an expression created without one is PRIMARY.

Method categories

Path and field references

These methods find data in the notice. Most other operations use the values that these methods return.

composeFieldValueReference is one of the hardest methods to implement correctly. The XPath reference implementation treats each data type differently: text fields use normalize-space(text()), date fields use xs:date(text()), and so on. Your implementation probably needs to treat each type in its own way too. To check the type, use fieldReference.is(EfxDataType.Date.class).
@Override
public PathExpression composeFieldValueReference(PathExpression fieldReference) {
    // This method often needs type-dependent logic.
    // The XPath implementation branches on the field's data type.
    // A simplified JavaScript approach, with a helper function.
    // Keep the class of the path: it carries the type and the number of values.
    return Expression.instantiate(
        "getFieldValue(notice, " + fieldReference.getScript() + ")", fieldReference.getClass());
}

@Override
public PathExpression composeFieldRawValueReference(PathExpression fieldReference) {
    // Returns the raw text content without type-specific processing.
    // Use when the EFX code explicitly asks for the unprocessed value.
    // A raw value is always a text: one, or a sequence of them.
    String script = "getRawValue(notice, " + fieldReference.getScript() + ")";
    return fieldReference instanceof SequenceExpression
        ? new StringSequencePath(script)
        : new StringPath(script);
}

composeFieldReferenceWithPredicate and composeNodeReferenceWithPredicate keep only the fields or nodes for which a condition is true. The toolkit has already translated the predicate relative to these fields or nodes:

@Override
public PathExpression composeFieldReferenceWithPredicate(
        PathExpression fieldReference, BooleanExpression predicate) {
    // XPath: "path[predicate]" (native filtering syntax)
    // For JavaScript, the predicate script already references the current item.
    // How you integrate it depends on your data access model.
    return Expression.instantiate(
        "filterField(" + fieldReference.getScript() + ", " + predicate.getScript() + ")",
        fieldReference.getClass());
}

contextualizePath turns an absolute path into a path relative to the current context. The XPath implementation leaves this to a separate class, XPathContextualizer, because the operations on paths are complex. Your implementation depends on your data model. With XPath on XML, it needs similar operations. With JSON data, it can need other operations on paths.

@Override
public PathExpression contextualizePath(PathExpression absolutePath, PathExpression contextPath) {
    return Expression.instantiate(
        "relativize(" + absolutePath.getScript() + ", " + contextPath.getScript() + ")",
        absolutePath.getClass());
}

@Override
public PathExpression joinPaths(PathExpression first, PathExpression second) {
    return Expression.instantiate(first.getScript() + "/" + second.getScript(), second.getClass());
}

@Override
public BooleanExpression composeExistsCondition(PathExpression reference) {
    return new BooleanExpression("exists(" + reference.getScript() + ")");
}

@Override
public <T extends PathExpression> T composeFieldAttributeReference(
        PathExpression fieldReference, String attribute, Class<T> type) {
    // Accesses an XML attribute on a field element (e.g., @listName, @schemeName)
    return Expression.instantiate(
        "getAttr(" + fieldReference.getScript() + ", \"" + attribute + "\")", type);
}

Literal creation

These methods turn EFX literals into the syntax of your target language. For example:

// EFX: 'hello world'
@Override
public StringExpression getStringLiteralEquivalent(String efxLiteral) {
    // The efxLiteral is the literal as written in EFX, with its quotes: 'hello world'.
    // Inside it, \' and \" stand for quotes. Any other backslash belongs to the text,
    // for example in the pattern '\d+'. Read a backslash and the character after it
    // as one pair, so that the second backslash of \\ never starts a new pair.
    String content = efxLiteral.substring(1, efxLiteral.length() - 1);
    StringBuilder text = new StringBuilder();
    for (int i = 0; i < content.length(); i++) {
        char c = content.charAt(i);
        if (c == '\\' && i + 1 < content.length()) {
            char next = content.charAt(++i);
            if (next != '\'' && next != '"') {
                text.append(c);
            }
            text.append(next);
        } else {
            text.append(c);
        }
    }
    return getStringLiteralFromUnquotedString(text.toString());
}

@Override
public StringExpression getStringLiteralFromUnquotedString(String value) {
    // Writes the text as a JavaScript literal, which must escape
    // backslashes, double quotes and control characters.
    StringBuilder literal = new StringBuilder("\"");
    for (char c : value.toCharArray()) {
        if (c == '\\' || c == '"') {
            literal.append('\\').append(c);
        } else if (c < 0x20) {
            literal.append(String.format("\\u%04x", (int) c));
        } else {
            literal.append(c);
        }
    }
    return new StringLiteral(literal.append('"').toString());
}

// EFX: 42
@Override
public NumericExpression getNumericLiteralEquivalent(String efxLiteral) {
    // Numeric literals are often the same across languages
    return new NumericLiteral(efxLiteral);
}

// EFX: TRUE
@Override
public BooleanExpression getBooleanEquivalent(boolean value) {
    return new BooleanLiteral(value ? "true" : "false");
}

Return the literal classes, such as StringLiteral and NumericLiteral: they are subclasses of the computed classes, so they can go wherever a value of their type can.

There are also literal methods for Date, Time and Duration. They receive the literal without quotes, in its ISO 8601 form, such as 2024-01-01Z, and write the form of dates, times and durations of your target language.

The toolkit uses the separate method getStringLiteralFromUnquotedString when it needs a text literal from a value of its own, not written in EFX syntax. It differs from getStringLiteralEquivalent, which receives texts in EFX syntax. In the example above, the second method writes the literal for both.

Boolean and logical operations

@Override
public BooleanExpression composeLogicalAnd(BooleanExpression left, BooleanExpression right) {
    // XPath:      "left and right"
    // JavaScript: "left && right"
    return Expression.instantiate(
        operand(left, Precedence.AND) + " && " + operand(right, Precedence.COMPARISON),
        Precedence.AND, BooleanExpression.class);
}

@Override
public BooleanExpression composeLogicalNot(BooleanExpression condition) {
    return Expression.instantiate("!" + operand(condition, Precedence.UNARY),
        Precedence.UNARY, BooleanExpression.class);
}

In composeLogicalAnd, the left operand can itself be an &&, so it needs at least AND. The right operand needs COMPARISON, so that $a && ($b && $c) keeps its parentheses. In composeLogicalNot, a negated && keeps its parentheses: !($a && $b).

Comparisons

A single method handles all comparison operators. The parameter operator is the EFX operator (==, !=, <, >, <=, >=). EFX compares values as XPath does:

  • dates and times are compared with their time zones: 2024-01-01Z and 2024-01-01+01:00 are not equal;

  • a duration of one year is longer than one of eleven months;

  • a comparison with a missing value is false, whatever the operator: if a field has no value, both BT-00-Text == 'a' and BT-00-Text != 'a' are false.

JavaScript compares objects such as Date by their identity, and has no type for durations. A missing value would make one of === and !== true. So the example passes the EFX operator and both operands to the helper compare, which follows these rules and returns the result:

@Override
public BooleanExpression composeComparisonOperation(
        ScalarExpression left, String operator, ScalarExpression right) {
    // compare("==", a, b) gives true or false. The EFX operator goes to the helper as a text.
    return new BooleanExpression("compare(" + getStringLiteralFromUnquotedString(operator).getScript()
        + ", " + left.getScript() + ", " + right.getScript() + ")");
}
The XPathScriptGenerator writes the operators in the XPath, and uses a static Map<String, String> to translate the EFX operators to XPath operators. You can use the same approach when you write the operators of your target language in your method.

String operations

The text methods include concatenation, taking parts of texts, changes between upper and lower case, removing white space, padding, and pattern matching:

@Override
public StringExpression composeStringConcatenation(List<StringExpression> list) {
    return new StringExpression("["
        + list.stream().map(Expression::getScript).collect(Collectors.joining(", ")) + "].join('')");
}

@Override
public StringExpression composeSubstringExtraction(
        StringExpression text, NumericExpression start, NumericExpression length) {
    return new StringExpression(
        "substring(" + text.getScript() + ", " + start.getScript() + ", " + length.getScript() + ")");
}

@Override
public BooleanExpression composePatternMatchCondition(StringExpression expression, String pattern) {
    // The pattern is a literal as written in EFX, with its quotes: '[0-9]+'.
    return new BooleanExpression("matches(normalizeSpace(" + expression.getScript() + "), "
        + getStringLiteralEquivalent(pattern).getScript() + ")");
}

The JavaScript method substr does not do what EFX does. EFX counts the characters from 1, and rounds the start and the length, as XPath does: substring('abcd', 0, 3) gives ab. The helper substring of the runtime library must follow these rules.

composePatternMatchCondition receives the pattern as written in EFX, with its quotes. The example turns it into a JavaScript text with the method for literals, and the helper matches creates the regular expression from that text, for example with new RegExp. Like the XPath implementation, it removes the extra white space of the value before it compares it with the pattern. The regular expressions of EFX are those of XPath, so the helper must also convert the parts in which XPath and JavaScript differ.

Two methods handle multilingual content. getPreferredLanguage returns the code of the language that best suits the reader, and getTextInPreferredLanguage takes the text of a multilingual field in that language. Both receive a PathExpression that points to the multilingual field.

Numeric operations

Methods for arithmetic, for totals and other values computed from sequences, and for conversions, including those that take the parts of dates and times:

@Override
public NumericExpression composeNumericOperation(
        NumericExpression left, String operator, NumericExpression right) {
    // The operators of EFX (+, -, *, /, %) are also those of JavaScript.
    if ("+".equals(operator) || "-".equals(operator)) {
        return Expression.instantiate(
            operand(left, Precedence.ADDITIVE) + " " + operator + " "
                + operand(right, Precedence.MULTIPLICATIVE),
            Precedence.ADDITIVE, NumericExpression.class);
    }
    return Expression.instantiate(
        operand(left, Precedence.MULTIPLICATIVE) + " " + operator + " "
            + operand(right, Precedence.UNARY),
        Precedence.MULTIPLICATIVE, NumericExpression.class);
}

@Override
public NumericExpression composeCountOperation(SequenceExpression list) {
    return new NumericExpression(operand(list, Precedence.PRIMARY) + ".length");
}

@Override
public NumericExpression composeSumOperation(NumericSequenceExpression list) {
    return new NumericExpression(
        operand(list, Precedence.PRIMARY) + ".reduce((__a, __b) => __a + __b, 0)");
}

The right operand of a subtraction needs a higher precedence than the left one, so that 10 - (5 - 2) keeps its parentheses. A property such as .length needs an operand of precedence PRIMARY: otherwise, .length would apply only to the last part of the operand.

There are also five composeToStringConversion methods, one for each type that can be converted, and methods that take the parts of dates and times (composeYearFunction, composeMonthFunction and so on).

Date, time and duration operations

These methods compute with dates, times and durations, and take their parts. They depend the most on the target language:

@Override
public DateExpression composeAddition(DateExpression date, DurationExpression duration) {
    return new DateExpression(
        "addDuration(" + date.getScript() + ", " + duration.getScript() + ")");
}

@Override
public NumericExpression composeYearFunction(DateExpression date) {
    // A JavaScript Date is a moment in time, without the time zone of the EFX date,
    // so the helper reads the year from the form that keeps the time zone.
    return new NumericExpression("year(" + date.getScript() + ")");
}

@Override
public StringExpression composeFormatDateMedium(DateExpression date) {
    String language = translatorOptions.getPrimaryLanguage2LetterCode();
    return new StringExpression("formatDateMedium(" + date.getScript() + ", "
        + getStringLiteralFromUnquotedString(language).getScript() + ")");
}

composeFormatDateMedium reads the language code from translatorOptions, to format the date for that language. The medium format has two digits for the day, the abbreviated name of the month in that language, and four digits for the year, as in 15 Feb 2026. The JavaScript method toLocaleDateString does not give this format without options, so the example calls a helper.

Containment and uniqueness checks

The interface has two different methods named composeContainsCondition. Their parameters tell them apart:

// String containment: does the string contain a substring?
@Override
public BooleanExpression composeContainsCondition(
        StringExpression haystack, StringExpression needle) {
    return new BooleanExpression(
        operand(haystack, Precedence.PRIMARY) + ".includes(" + needle.getScript() + ")");
}

// Sequence containment: is the value present in the collection?
@Override
public BooleanExpression composeContainsCondition(
        ScalarExpression needle, SequenceExpression haystack) {
    // Array.includes would compare dates by identity: the helper compares values.
    return new BooleanExpression(
        "containsValue(" + haystack.getScript() + ", " + needle.getScript() + ")");
}

composeUniqueValueCondition has six forms, one for each basic type that has values: text, number, indicator, date, time and duration. The forms exist so that Java can check the types. The code can be the same for all types, if it calls a helper that compares the values according to their type, as compare does in Comparisons. Put the code in a private method:

// All six typed overloads delegate to one helper:
private BooleanExpression composeUniqueValue(Expression needle, Expression haystack) {
    return Expression.instantiate(
        "countValue(" + haystack.getScript() + ", " + needle.getScript() + ") === 1",
        Precedence.COMPARISON, BooleanExpression.class);
}

@Override
public BooleanExpression composeUniqueValueCondition(
        StringExpression needle, StringSequenceExpression haystack) {
    return composeUniqueValue(needle, haystack);
}
// ... same for Numeric, Boolean, Date, Time, Duration
There is also an older form from EFX-1, composeUniqueValueCondition(PathExpression, PathExpression). It has no default implementation, so you must implement it, even for an EFX-2 translator. It can call the same helper method.

Sequence operations

Methods that build and change sequences, and that ask questions about them:

@Override
public <T extends SequenceExpression> T composeList(
        List<? extends ScalarExpression> list, Class<T> type) {
    String items = list.stream()
        .map(Expression::getScript)
        .collect(Collectors.joining(", "));
    return Expression.instantiate("[" + items + "]", type);
}

@Override
public <T extends SequenceExpression> T composeDistinctValuesFunction(T list, Class<T> type) {
    // A JavaScript Set would keep two Date objects for the same day: the helper compares values.
    return Expression.instantiate("distinctValues(" + list.getScript() + ")", type);
}

@Override
public <T extends ScalarExpression> T composeIndexer(
        SequenceExpression list, NumericExpression index, Class<T> type) {
    // EFX counts the items from 1, JavaScript from 0.
    return Expression.instantiate(
        operand(list, Precedence.PRIMARY) + "[" + operand(index, Precedence.ADDITIVE) + " - 1]", type);
}

Variables and declarations

Variables and parameters follow the same pattern. Parameters are the parameters of functions and templates.

The names of EFX can contain hyphens, such as $max-value, and JavaScript names cannot. So the example turns each EFX name into a JavaScript name: it adds $ at the start, and replaces each hyphen with $. EFX names never contain $, so two EFX names never give the same JavaScript name. The names that the examples generate for their own use, such as result, start with , which EFX reserves, so they cannot clash with an EFX name either. Variables are declared with let:

private static String jsName(String efxName) {
    // max-value -> $max$value
    return "$" + efxName.replace('-', '$');
}

@Override
public <T extends TypedExpression> T composeVariableDeclaration(String variableName, Class<T> type) {
    return Expression.instantiate("let " + jsName(variableName), type);
}

@Override
public <T extends TypedExpression> T composeVariableReference(String variableName, Class<T> type) {
    return Expression.instantiate(jsName(variableName), type);
}

// Parameter methods follow the same pattern as variable methods
The rules translator finds the variables that a rule uses by looking in the script of the rule for $ followed by the name of the variable, as the XPath implementation writes it (see The expression and markup model). With the names of this example, it finds the names without hyphens, but not $max$value. A validator generator that relies on this search must use names that it can find.

Conditional expressions, iteration and parentheses

composeParenthesizedExpression puts an expression in parentheses. The XPath implementation uses reflection, which lets Java create an object of a class known only while the program runs, to build a new expression of the same type. You can use Expression.instantiate instead:

@Override
public <T extends Expression> T composeParenthesizedExpression(T expression, Class<T> type) {
    return Expression.instantiate("(" + expression.getScript() + ")", type);
}

The example puts the whole conditional expression in parentheses, as the XPath implementation does. The result then has the precedence PRIMARY, and goes anywhere without more parentheses:

@Override
public <T extends TypedExpression> T composeConditionalExpression(
        BooleanExpression condition, T whenTrue, T whenFalse, Class<T> type) {
    return Expression.instantiate(
        "(" + condition.getScript() + " ? " + whenTrue.getScript() + " : " + whenFalse.getScript() + ")",
        type);
}

The method composeForExpression builds a sequence by applying an expression to each item of another sequence. It has two forms. In one, the expression after return gives a single value in each round. In the other, it gives a sequence in each round, and the result joins these sequences. An EFX iteration always calls the second form: a single value after return reaches your method as a sequence of one value. The template translator calls the first form, for example to format each number of a sequence, so implement both.

Both forms receive an IteratorListExpression, which composeIteratorList builds from the results of composeIteratorExpression. An iteration can have several iterators, such as for number:$x in [1, 2], number:$y in [3, 4] return $x * $y. In JavaScript, each iterator becomes a for loop, and the loops are nested:

@Override
public IteratorExpression composeIteratorExpression(
        Expression variableDeclaration, SequenceExpression sourceList) {
    // for (let $x of [1, 2])
    return new IteratorExpression(
        "for (" + variableDeclaration.getScript() + " of " + sourceList.getScript() + ")");
}

@Override
public IteratorListExpression composeIteratorList(List<IteratorExpression> iterators) {
    // for (let $x of [1, 2]) for (let $y of [3, 4])
    return new IteratorListExpression(
        iterators.stream().map(Expression::getScript).collect(Collectors.joining(" ")));
}

@Override
public <T extends SequenceExpression> T composeForExpression(
        IteratorListExpression iterators, ScalarExpression expression, Class<T> type) {
    // One value in each round
    return Expression.instantiate(
        "(() => { const __result = []; " + iterators.getScript()
            + " __result.push(" + expression.getScript() + "); return __result; })()",
        type);
}

@Override
public <T extends SequenceExpression> T composeForExpression(
        IteratorListExpression iterators, SequenceExpression expression, Class<T> type) {
    // A sequence in each round: the result joins them
    return Expression.instantiate(
        "(() => { const __result = []; " + iterators.getScript()
            + " __result.push(..." + expression.getScript() + "); return __result; })()",
        type);
}

Quantified expressions

EFX has the expressions every …​ satisfies and some …​ satisfies. They map to composeAllSatisfy and composeAnySatisfies. Both receive an IteratorListExpression and a condition:

@Override
public BooleanExpression composeAllSatisfy(
        IteratorListExpression iterators, BooleanExpression condition) {
    // EFX: every number:$x in [1, 2] satisfies $x > 0
    return new BooleanExpression(
        "(() => { " + iterators.getScript()
            + " if (!(" + condition.getScript() + ")) return false; return true; })()");
}

@Override
public BooleanExpression composeAnySatisfies(
        IteratorListExpression iterators, BooleanExpression condition) {
    // EFX: some number:$x in [1, 2] satisfies $x > 1
    return new BooleanExpression(
        "(() => { " + iterators.getScript()
            + " if (" + condition.getScript() + ") return true; return false; })()");
}

User-defined functions and dictionaries

composeFunctionInvocation handles calls to user-defined EFX functions. The name of the function becomes a JavaScript name in the same way as the name of a variable:

@Override
public <T extends TypedExpression> T composeFunctionInvocation(
        String functionName, List<? extends TypedExpression> parameters, Class<T> type) {
    String args = parameters.stream()
        .map(Expression::getScript)
        .collect(Collectors.joining(", "));
    return Expression.instantiate(jsName(functionName) + "(" + args + ")", type);
}

composeDictionaryLookup handles references to dictionaries: tables with a name, which map keys to values, for example a country code to the name of the country:

@Override
public <T extends TypedExpression> T composeDictionaryLookup(
        String dictionaryName, StringExpression keyExpression, Class<T> type) {
    return Expression.instantiate("lookupDictionary("
        + getStringLiteralFromUnquotedString(dictionaryName).getScript() + ", "
        + keyExpression.getScript() + ")", type);
}

Runtime libraries

Your ScriptGenerator writes pieces of code, not a complete program. Complex operations often need helper functions in your target language. The examples on this page call these helpers:

  • reading the notice: getFieldValue, getRawValue, getAttr, filterField, relativize and exists;

  • comparing values according to their type: compare, containsValue, countValue and distinctValues;

  • texts: substring, matches and normalizeSpace, which follow the rules of XPath;

  • dates and durations: addDuration, year and formatDateMedium;

  • dictionaries: lookupDictionary.

You must provide these helper functions. The ScriptGenerator writes calls to them, and their implementations must exist where the code runs. Your application decides how to package and distribute this library of helpers.

Common implementation errors

Two forms of composeContainsCondition

One checks whether a text contains another text. The other checks whether a sequence contains a value. The two methods have the same name but different meanings. Implement both.

A different treatment for each type in composeFieldValueReference

Text, date, number and duration fields can all need a different way to read their values. In the XPath implementation, this method has more than 25 lines that treat each data type differently.

Positions that start at 1

In EFX, positions always start at 1, as in XPath. Adjust them in composeSubstringExtraction, composeIndexer, composeSubsequenceFunction and composeIndexOfFunction if your language starts at 0.

Operators that compare objects, not values

The equality operator of your language can compare two dates, times or durations by their identity, not by their value. Compare them according to their type, in comparisons, in conditions on membership and uniqueness, and when you remove duplicates.

Operands without parentheses

An operand that is itself an operation can need parentheses. Use the precedence of the expressions (see Precedence of operations).

Methods with several forms

Several methods have several forms, for example six typed forms of composeUniqueValueCondition and five of composeToStringConversion. Their implementations are usually the same: put the code in a private helper method, and call it from each form.

A second script generator without a qualifier

The toolkit registers XPathScriptGenerator for SDK 2 without a qualifier. A script generator of your own, annotated without a qualifier, makes two of them, and the toolkit stops with the error "More than one components of type [SCRIPT_GENERATOR] have been found for SDK version [2]". The annotation @SdkComponent is inherited, so this also happens with a subclass of XPathScriptGenerator, even without an annotation of its own. Give a subclass an annotation with a qualifier of its own. A class that implements ScriptGenerator directly can instead have no annotation, if your factory creates it directly.

Implementation guidance

Implementing the methods step by step

Begin with the literal methods and the basic operations (composeLogicalAnd, composeNumericOperation). With them, you can run a first translation early. Add the more complex methods, such as the formatting of dates, the sequence operations and contextualizePath, once the basic translation works.

Use the XPath implementation as a reference

The class XPathScriptGenerator implements all the methods. When you are not sure what a method should do, look at its XPath implementation. The Javadoc of each method of the interface ScriptGenerator describes what the method must do, and the XPath code shows one way to do it.

Put shared code in private helper methods

The XPathScriptGenerator uses private helper methods to share code between the forms of a method. For example, a single composeTypedUniqueValueCondition handles the six typed forms of composeUniqueValueCondition. This avoids repeated code, and leaves less code to maintain.

Take care with escape sequences in texts

The method getStringLiteralEquivalent receives the EFX text literal, in which a backslash starts an escape sequence. You may need to convert it to the way your target language writes special characters in texts. The XPathScriptGenerator does this with a helper method, efxToXPathLiteral.


See also: