Call stack architecture

Overview

This page explains how the EFX-2 translators keep track of what they translate. It describes the class Translation, which holds the state of one translation, and the two stacks in it: the CallStack, for the scope of names, and the ContextStack, for the context. A stack is a list in which the last item added is the first one taken off. The page is for contributors who need to understand or change the translators.

Two ways of going through the parse tree

The parser gives the structure of a file as a tree, the parse tree. The EFX-2 translators go through this tree in two ways:

The listener, for statements

The class TranslatorListener, and its subclasses for single expressions, templates and rules, are ANTLR listeners: ANTLR calls their methods as it enters and leaves each node of the parse tree. They translate the parts of a file that are not expressions, such as template lines, declarations, sections, stages and rules. They walk the tree with an ExpressionSkippingWalker, which does not go into expressions and contexts.

The visitor, for expressions

For each expression and each context, the listener asks an EfxExpressionVisitor. The visitor translates the parts inside an expression first, and returns each translated part to the part around it (see How the EFX-2 translator checks types). So the parts of an expression never go through a stack. Only the result of the whole expression can: the listener puts it on the CallStack, for the statement that contains the expression. For example, the listener puts the value of an expression block of a template line there, for the template line to take it off.

Translation: the state of one translation

A Translation holds what one translation needs:

  • the SymbolResolver and the ScriptGenerator;

  • a CallStack, with the type checker of SDK 2;

  • a ContextStack, which uses the symbol resolver to compute the paths of contexts.

Each translation starts with a new Translation, and a new visitor, so that the declarations and contexts of one translation are not visible in the next one. The value of a parameter of a single expression is also translated in a Translation of its own.

CallStack: scope and the parts of statements

The CallStack is a stack of stack frames. Each frame is a scope: it holds the names declared in it, and the parts of statements that the listener has translated but not yet used. The frame at the bottom of the stack is the global scope.

A stack of parts for the listener

The listener uses each frame as a stack of translated parts. When ANTLR leaves a node, the listener takes the parts of the node’s children off the stack, combines them, and puts the result on the stack. For example, a fragment of text in a template line goes on the stack when ANTLR leaves it, and the template that contains it takes it off:

@Override
public void exitTextBlock(TextBlockContext ctx) {
  this.translation.stack().push(new TextContentTemplateFragment(ctx.getText()));
}

Taking a part off the stack with a type

The method pop(Class<T> expectedType) takes the part at the top of the current frame, and checks its type. A part of the expected class, or of a subclass, comes off as it is. A translated expression of another class comes off converted, if the TypeChecker allows the conversion. Otherwise, the CallStack throws a TypeMismatchException:

synchronized <T extends ParsedEntity> T pop(Class<T> expectedType) {
  Class<? extends ParsedEntity> actualType = this.peek().getClass();
  if (expectedType.isAssignableFrom(actualType)) {
    return expectedType.cast(this.pop());
  }

  if (TypedExpression.class.isAssignableFrom(actualType) && TypedExpression.class.isAssignableFrom(expectedType)) {
    var actual = actualType.asSubclass(TypedExpression.class);
    var expected = expectedType.asSubclass(TypedExpression.class);
    if (typeChecker.canConvert(actual, expected)) {
      return expectedType.cast(TypedExpression.from((TypedExpression) this.pop(), expected));
    }
    throw TypeMismatchException.cannotConvert(CallStack.this.peekParserContext(), expected, actual);
  }

  throw TypeMismatchException.cannotConvert(CallStack.this.peekParserContext(), expectedType, actualType);
}

Scopes and names

The CallStack keeps registers of names at two levels:

Global scope

globalIdentifierRegistry holds the global variables, dictionaries, functions and templates. They are visible in the whole file under translation.

Local scopes

Each frame has its own identifierRegistry for the names declared in that scope. These include the variables of template lines and rule-sets, the parameters of functions and templates, and the iterator variables.

To find a name, the CallStack searches all the frames and the global register. A name is found in at most one place, because the CallStack refuses a declaration in two cases:

  • when the name is already declared, in any visible scope. So a name never hides another one, as the language requires (see Scope of variables);

  • when the name starts with __, the prefix that the translator keeps for the names that it generates.

The end of a scope and its result

A part of the language that has its own scope, such as an iteration, opens a frame with pushStackFrame and closes it with popStackFrame. Closing a frame drops all its names. If parts are left on the frame, the CallStack passes them to the frame below:

public void popStackFrame() {
  StackFrame droppedFrame = this.frames.pop();
  // If the dropped frame is not empty, then it contains return values that should
  // be passed to the next frame on the stack.
  if (!droppedFrame.isEmpty()) {
    if (this.frames.empty()) {
      throw new ParseCancellationException(STACK_UNDERFLOW);
    }
    this.frames.peek().addAll(droppedFrame);
  }
}

The position for errors

The CallStack also keeps the parse tree nodes that the translation is in, with pushParserContext and popParserContext. An error raised without a position of its own, for example by the symbol resolver, then gives the position of the node in which it happened.

ContextStack: the context

The ContextStack keeps track of something else: the place in the notice from which the expressions are read. Each Context on the stack holds:

Symbol

The identifier of the field or node, for example BT-00-Text or ND-Lot.

Absolute path

The full path from the root of the notice to this place.

Relative path

The path from the previous context to this place.

The translator needs both paths to write correct code. It uses absolute paths to compute how contexts relate to each other, and relative paths to write the code that moves from one place to another. The ContextStack asks the symbol resolver for both:

public FieldContext pushFieldContext(final String fieldId) {
  PathExpression absolutePath = symbols.getAbsolutePathOfField(fieldId);
  if (this.isEmpty()) {
    FieldContext context = new FieldContext(fieldId, absolutePath);
    this.push(context);
    return context;
  }
  PathExpression relativePath = symbols.getRelativePathOfField(fieldId, this.symbol());
  FieldContext context = new FieldContext(fieldId, absolutePath, relativePath);
  this.push(context);
  return context;
}

The subclasses FieldContext and NodeContext keep field contexts and node contexts apart.

Context variables

A context variable names one occurrence of a field or node, so that an expression can refer to it after the context has changed (see Context variable). The CallStack registers the variable like any other variable. The ContextStack keeps, for each context variable, the context that it holds:

private final Map<Variable, Context> contextsOfVariables = new IdentityHashMap<>();

Reads of the context

The ContextStack also counts, for each context, whether expressions read from it. An index uses this count, for example, to find out whether its position reads the current context, which the target language could read differently for each occurrence.

The variable model

The class Variable keeps three separate expressions:

public final Expression declarationExpression;
public final TypedExpression initializationExpression;
public final TypedExpression referenceExpression;
Declaration expression

The code in the target language that declares the variable, for example $x in the XPath iteration for $x in (1,2,3) return ….

Initialisation expression

The value that the variable receives.

Reference expression

The code in the target language that reads the variable, for example $x in XPath.

The translator needs these three expressions, because it translates code into other code. One EFX variable can need different code in the target language, depending on how the code uses it. For example, the initialisation expression of an iterator variable gives a sequence, but its reference expression stands for the current item:

// Iterator variable: the initialisation is a sequence, the reference a single value
assert EfxTypeLattice.toPrimitive(referenceExpression.getDataType())
    .isAssignableFrom(EfxTypeLattice.toPrimitive(initializationExpression.getDataType()));

Identifier hierarchy

The class hierarchy of Identifier stands for everything that has a name in EFX:

classDiagram
    Identifier <|-- Variable
    Variable <|-- DynamicVariable
    Identifier <|-- ParsedParameter
    Identifier <|-- Dictionary
    Identifier <|-- Invocable
    Invocable <|-- Function
    Function <|-- DynamicFunction
    Invocable <|-- Template
    Identifier : +name
    Identifier : +dataType

All identifiers have a name and a data type. The subclass decides where the CallStack stores the identifier, globally or locally, and how the translator uses a reference to it. A function or a template is also a Construct, whose parameters the translator checks the arguments of each call against.

Design rationale

Separation of CallStack and ContextStack

The scope of names and the context change separately. In this template, the variable $label stays visible in the nested line, whose context is another node:

WITH ND-RepeatableNode, text:$label = BT-00-Text-In-Repeatable-Node DISPLAY ${$label};
    WITH ND-RepeatableInRepeatableNode DISPLAY ${$label}: ${BT-23-Text};

Because scope and context are kept apart, the two can change separately.

Why a visitor for expressions

In a visitor, each part of an expression returns its translation to the part around it. The part around it can then check each argument against its signatures, and report an error at the argument that does not fit. With a stack of values, it would only see the values that are on the stack, without knowing what each of them was written as.

Why chained symbol tables

Chained symbol tables are the usual way for compilers to manage the scope of names. With a single table, the translator would have to keep track of the scopes itself. With frames, when a scope ends, the CallStack drops its frame and all its local declarations at once.

Usage patterns

Declaring variables

The translator declares a variable by adding it to the register of names of the current frame:

callStack.declareIdentifier(new Variable(name, initExpr, refExpr));

The CallStack checks that the name is not already declared in a visible scope, and that it does not start with the reserved prefix.

Referring to variables

The visitor finds a variable with getVariable, and uses its reference expression. The listener uses pushIdentifierReference, which puts the reference expression of a parameter or variable on the stack.

Scoped constructs

The parts of the language that open a new scope follow the same pattern: open a frame, translate, close the frame. The visitor translates an iteration in this way:

this.translation.stack().pushStackFrame();
final IteratorListExpression iterators = this.iteratorsOf(ctx.iteratorList());
final Subexpression<?> iteration = this.subexpression(
    this.resolved(ExpressionConstruct.iteration(iterators),
        List.of(this.visit(ctx.expression())), position -> ctx.expression())
        .compose(this.translation.script()));
this.translation.stack().popStackFrame();

Relationship to other components

The CallStack and the ContextStack work with other components of the translator:

SymbolResolver

The ContextStack uses the SymbolResolver to compute the absolute and relative paths of each new context.

ScriptGenerator

The composers of the constructs call the ScriptGenerator, which writes the code in the target language.

TypeChecker

The CallStack uses the TypeChecker to convert values when the listener takes them off the stack with a type.

graph TD
    Parser -->|parse tree| Listener
    Listener -->|expressions and contexts| Visitor
    Listener --> CallStack
    Listener --> ContextStack
    Visitor --> CallStack
    Visitor --> ContextStack
    ContextStack --> SymbolResolver
    Visitor --> ScriptGenerator
    CallStack --> TypeChecker

See also: