Class AbstractSyntheticGenerator

java.lang.Object
org.ek9lang.compiler.phase7.synthesis.AbstractSyntheticGenerator
Direct Known Subclasses:
CompareGenerator, CopyGenerator, DelegationGenerator, DerivedComparisonGenerator, EnumCompareGenerator, EnumConstructorGenerator, EnumEqualsGenerator, EnumFirstLastGenerator, EnumHashCodeGenerator, EnumIncrementDecrementGenerator, EnumIsSetGenerator, EnumIteratorGenerator, EnumJsonGenerator, EnumStringGenerator, EnumStringParamGenerator, EqualsGenerator, FieldSetStatusGenerator, FunctionIsSetGenerator, HashCodeGenerator, IsSetGenerator, NotEqualsGenerator, ToJsonGenerator, ToStringGenerator

public abstract class AbstractSyntheticGenerator extends Object
Base class for synthetic operator generators.

Provides common patterns and utilities used by all synthetic generators:

  • IsSet guard generation for this and parameters
  • Unset return block generation
  • Field iteration utilities
  • Memory management (RETAIN/SCOPE_REGISTER) patterns

All generated IR follows the EK9 tri-state semantics where operations return unset if any operand is unset.

  • Field Details

    • stackContext

      protected final IRGenerationContext stackContext
    • synthesisedCallMetaData

      protected final SynthesisedCallMetaData synthesisedCallMetaData
      THE shared source of call metadata for every synthesised call site - use this rather than constructing one per generator (fifteen of them had, before this was hoisted), and never hand-write a CallMetaDataDetails tuple. See its javadoc for the two honest sources.
  • Constructor Details

    • AbstractSyntheticGenerator

      protected AbstractSyntheticGenerator(IRGenerationContext stackContext)
      Create a new synthetic generator with the given context.
      Parameters:
      stackContext - The IR generation context
  • Method Details

    • getReturnBlockHelper

      protected ReturnBlockHelper getReturnBlockHelper()
      Get the shared ReturnBlockHelper instance.

      Lazily initializes a single ReturnBlockHelper per generator instance, avoiding the need to create a new instance in each generate() method.

      Returns:
      The shared ReturnBlockHelper instance
    • methodCall

      protected SyntheticMethodCallBuilder methodCall()
      Create a builder for a method call.
      Returns:
      A new SyntheticMethodCallBuilder configured for method calls
    • constructorCall

      protected SyntheticMethodCallBuilder constructorCall()
      Create a builder for a constructor call.
      Returns:
      A new SyntheticMethodCallBuilder configured for constructor calls
    • getTypeName

      protected String getTypeName(ISymbol symbol)
      Get the fully qualified name for a type.
      Parameters:
      symbol - The symbol to get the type name for
      Returns:
      The fully qualified type name
    • getType

      protected ISymbol getType(ISymbol symbol)
      The same type, as a SYMBOL rather than a name - so a call ON this value can derive its dispatch flag instead of inheriting the builder's shape-only default.

      Pass this wherever getTypeName(ISymbol) was feeding a .on(receiver, name): the two then answer from one place, and a field whose type is CLOSED (a record, an enum, a non-open class, or a closed built-in like Boolean or JSON) stops rendering its operator calls as dispatchable.

    • getBooleanTypeName

      protected String getBooleanTypeName()
      Get the Boolean type name from the EK9 type system.
    • getBooleanType

      protected ISymbol getBooleanType()
      The Boolean type SYMBOL - for reading call metadata off it, rather than only naming it.
    • getIntegerType

      protected ISymbol getIntegerType()
      The Integer type SYMBOL - see getBooleanType().
    • getIntegerTypeName

      protected String getIntegerTypeName()
      Get the Integer type name from the EK9 type system.
    • getStringTypeName

      protected String getStringTypeName()
      Get the String type name from the EK9 type system.
    • getStringType

      protected ISymbol getStringType()
      The String type SYMBOL - see getBooleanType().
    • getBitsTypeName

      protected String getBitsTypeName()
      Get the Bits type name from the EK9 type system.
    • getBitsType

      protected ISymbol getBitsType()
      The Bits type SYMBOL - see getBooleanType().
    • getAnyType

      protected ISymbol getAnyType()
      The Any type SYMBOL - the root of every EK9 type, a Java interface at the backend. Used as the fall-back receiver when a synthesised default operator runs over a field whose type has no REAL operator of its own (see fieldTypeHasRealOperator(ISymbol, String, boolean)).
    • getAnyTypeName

      protected String getAnyTypeName()
      The Any type name - see getAnyType().
    • fieldTypeHasRealOperator

      protected boolean fieldTypeHasRealOperator(ISymbol field, String glyph, boolean binary)
      Does the field's TYPE have a REAL operatorGlyph of its own (declared or inherited from a real super), as opposed to only the degenerate Any default that every type inherits?

      A synthesised default operator (<=>/==/$/#?) over a field may direct-call the field type's own operator ONLY when this is true. When false - the case for a monomorphised generic field whose T is a non-capable type (e.g. List of String has no real <=>) - the generator must instead call Any's operator, otherwise it emits a call to a symbol that no object defines (a native eager-link failure; the JVM only tolerates it by lazy dispatch onto the Any interface default). Uses the shared HasRealOperator walk.

      Parameters:
      field - the field symbol
      glyph - the operator glyph ("<=>", "==", "$", "#?")
      binary - true for a self-typed single-argument operator (<=>, ==); false for a no-argument operator ($, #?)
    • getVoidTypeName

      protected String getVoidTypeName()
      Get the Void type name from the EK9 type system.
    • generateTempName

      protected String generateTempName()
      Generate a temporary variable name.
    • generateLabelName

      protected String generateLabelName(String prefix)
      Generate a label name with the given prefix.
    • createDebugInfo

      protected DebugInfo createDebugInfo(ISymbol symbol)
      Create debug info from a symbol's source token.
    • createSynthesisScope

      protected SynthesisScope createSynthesisScope(ISymbol symbol, String scopeLabel)
      Create an SynthesisScope for the given operator symbol.

      This bundles debugInfo and scopeId together for cleaner method signatures. Use this at the start of a generate() method:

        final var ctx = createSynthesisScope(operatorSymbol, "_eq");
        // Use ctx.debugInfo() and ctx.scopeId() or pass ctx to methods
      
      Parameters:
      symbol - The method symbol to get debug info from
      scopeLabel - The label for the scope (e.g., "_eq", "_cmp", "_hashcode")
      Returns:
      SynthesisScope bundling debugInfo and scopeId
    • initializeScope

      protected AbstractSyntheticGenerator.ScopeSetup initializeScope(MethodSymbol operatorSymbol, String scopeLabel, String returnVarName, String returnTypeName)
      Initialize scope with return variable reference.

      This consolidates the common boilerplate at the start of every generate() method:

        final var ctx = createSynthesisScope(operatorSymbol, "_eq");
        final var instructions = new ArrayList<IRInstr>();
        instructions.add(ScopeInstr.enter(ctx.scopeId(), ctx.debugInfo()));
        instructions.add(MemoryInstr.reference(RETURN_VAR, getBooleanTypeName(), ctx.debugInfo()));
      

      Becomes:

        final var setup = initializeScope(operatorSymbol, "_eq", RETURN_VAR, getBooleanTypeName());
        final var ctx = setup.ctx();
        final var instructions = setup.instructions();
      
      Parameters:
      operatorSymbol - The operator method symbol for debug info
      scopeLabel - The scope label (e.g., "_eq", "_cmp")
      returnVarName - The return variable name (typically "rtn")
      returnTypeName - The return type name
      Returns:
      ScopeSetup containing context and initialized instruction list
    • initializeScopeNoReturn

      protected AbstractSyntheticGenerator.ScopeSetup initializeScopeNoReturn(MethodSymbol operatorSymbol, String scopeLabel)
      Initialize scope for void-returning methods (no return variable).

      Use this for operators like ++ and -- that don't return a value.

      Parameters:
      operatorSymbol - The operator method symbol for debug info
      scopeLabel - The scope label (e.g., "_inc", "_dec")
      Returns:
      ScopeSetup containing context and initialized instruction list
    • generateBinaryOperatorGuards

      protected List<IRInstr> generateBinaryOperatorGuards(String aggregateTypeName, ISymbol aggregateType, String paramName, String unsetLabel, SynthesisScope ctx)
      Generate isSet guards for binary operators (this and param).

      Most binary operators (==, <>, <=>) need to check that both this and the parameter are set before comparing. This helper consolidates the common two-guard pattern:

        instructions.addAll(generateThisIsSetGuard(aggregateTypeName, returnUnsetLabel, ctx));
        instructions.addAll(generateIsSetGuard(paramName, aggregateTypeName, returnUnsetLabel, ctx));
      
      Parameters:
      aggregateTypeName - The fully qualified type name of both this and param
      paramName - The parameter variable name (typically "param")
      unsetLabel - Label to branch to if either is unset
      ctx - Synthesis scope context
      Returns:
      List of IR instructions for both guards
    • generateThisIsSetGuard

      protected List<IRInstr> generateThisIsSetGuard(String aggregateTypeName, ISymbol aggregateType, DebugInfo debugInfo, String unsetLabel, String scopeId)
      Generate isSet guard check for 'this' with branch to unset return.

      Pattern:

        _temp = CALL this._isSet() -> Boolean
        RETAIN _temp
        SCOPE_REGISTER _temp, scope_id
        _temp_val = UNBOX _temp -> boolean
        BRANCH_IF_FALSE _temp_val -> unset_label
      
      Parameters:
      aggregateTypeName - The fully qualified type name of the aggregate
      debugInfo - Debug information for the instructions
      unsetLabel - Label to branch to if unset
      scopeId - Current scope ID for memory management
      Returns:
      List of IR instructions for the guard
    • generateIsSetGuard

      protected List<IRInstr> generateIsSetGuard(String variableName, String typeName, ISymbol type, DebugInfo debugInfo, String unsetLabel, String scopeId)
      Generate isSet guard check for a variable with branch to unset return.

      The check generates:

        1. _temp = CALL variable._isSet() -> Boolean
        2. RETAIN/SCOPE_REGISTER _temp
        3. _tempBool = CALL _temp._true() -> boolean (primitive)
        4. RETAIN/SCOPE_REGISTER _tempBool
        5. BRANCH_FALSE _tempBool, unsetLabel
      
      Parameters:
      variableName - The variable to check
      typeName - The fully qualified type name of the variable
      type - That type as a SYMBOL, so the _isSet metadata is read rather than defaulted
      debugInfo - Debug information for the instructions
      unsetLabel - Label to branch to if unset
      scopeId - Current scope ID for memory management
      Returns:
      List of IR instructions for the guard
    • generateAnyFieldSetGuard

      protected List<IRInstr> generateAnyFieldSetGuard(AggregateSymbol aggregateSymbol, String aggregateTypeName, DebugInfo debugInfo, String returnUnsetLabel, String scopeId)
      Generate guard that returns UNSET if no fields are set (ANY field set semantics).

      Uses _fieldSetStatus()._empty() directly, avoiding dependency on ? operator. Also checks super._isSet() if super has ? operator defined.

      Pattern:

        // If super has ? operator, check it first
        superIsSet = super._isSet()
        superBool = superIsSet._true()
        BRANCH_TRUE superBool, continue_label  // Super is set, skip own field check
      
        // Check own fields
        status = this._fieldSetStatus() -> Bits
        isEmpty = status._empty() -> Boolean
        isEmptyBool = isEmpty._true()
        BRANCH_TRUE isEmptyBool, returnUnsetLabel  // No fields set, return UNSET
      
        continue_label:
      
      Parameters:
      aggregateSymbol - The aggregate being checked
      aggregateTypeName - Fully qualified type name
      debugInfo - Debug information
      returnUnsetLabel - Label to branch to if no fields are set
      scopeId - Current scope ID
      Returns:
      List of IR instructions implementing the guard
    • getSyntheticFields

      protected List<ISymbol> getSyntheticFields(AggregateSymbol aggregateSymbol)
      Get all fields from an aggregate that should be included in synthetic operations.

      This returns only the direct properties of the aggregate, not inherited ones. Inherited fields are handled by calling super's synthetic operators.

      For dynamic classes/functions with captured variables, those captured fields are stored in a separate CaptureScope. This method includes them so that synthetic operators like _isSet and _fieldSetStatus correctly reflect captured field state.

      Parameters:
      aggregateSymbol - The aggregate to get fields from
      Returns:
      List of field symbols
    • superHasOperator

      protected boolean superHasOperator(AggregateSymbol aggregateSymbol, String operatorName)
      Check if the super aggregate has a specific operator defined.
      Parameters:
      aggregateSymbol - The aggregate whose super we're checking
      operatorName - The operator name (e.g., "==", "<=>")
      Returns:
      true if super has the operator, false otherwise
    • isAnyType

      protected boolean isAnyType(IAggregateSymbol type)
      Check if the given type is the Any type.
    • isTraitType

      protected boolean isTraitType(ISymbol symbol)
      Check if the given symbol's type is a trait.

      Traits in EK9 compile to Java interfaces, so method calls on trait-typed variables must use invokeinterface instead of invokevirtual.

      Parameters:
      symbol - The symbol to check (typically a field or variable)
      Returns:
      true if the symbol's type is a trait, false otherwise
    • aggregateHasOperator

      protected boolean aggregateHasOperator(AggregateSymbol aggregateSymbol, String operatorName)
      Check if the given aggregate has a specific operator defined (in its own scope).
      Parameters:
      aggregateSymbol - The aggregate to check
      operatorName - The operator name (e.g., "?", "$", "#?")
      Returns:
      true if the aggregate has the operator, false otherwise
    • getSuperTypeName

      protected String getSuperTypeName(AggregateSymbol aggregateSymbol)
      Get the fully qualified name of the super aggregate.
      Parameters:
      aggregateSymbol - The aggregate to get super from
      Returns:
      The super type name, or empty string if no super (other than Any)
    • generateFieldLoad

      protected List<IRInstr> generateFieldLoad(String targetVar, String objectVar, String fieldName, String ownerTypeName, String fieldTypeName, DebugInfo debugInfo, String scopeId)
      Generate field load instruction with memory management using explicit LOAD_FIELD.

      Pattern:

        _temp = LOAD_FIELD objectVar, fieldName, ownerTypeName, fieldTypeName
        RETAIN _temp
        SCOPE_REGISTER _temp, scope_id
      
      Parameters:
      targetVar - The variable to store the loaded value
      objectVar - The object to load from (typically "this" or "param")
      fieldName - The field name to load
      ownerTypeName - The fully qualified type name of the object that owns the field
      fieldTypeName - The fully qualified type name of the field
      debugInfo - Debug information
      scopeId - Current scope ID
      Returns:
      List of IR instructions
    • generateStringLiteralLoad

      protected List<IRInstr> generateStringLiteralLoad(String resultVar, String literalValue, DebugInfo debugInfo, String scopeId)
      Generate a string literal load with memory management.

      Pattern:

        _temp = LOAD_LITERAL "value", org.ek9.lang::String
        RETAIN _temp
        SCOPE_REGISTER _temp, scope_id
      
      Parameters:
      resultVar - Variable to store the loaded literal
      literalValue - The string literal value
      debugInfo - Debug information
      scopeId - Current scope ID
      Returns:
      List of IR instructions
    • generateFieldSetStatusCheck

      protected List<IRInstr> generateFieldSetStatusCheck(String otherParamName, AggregateSymbol aggregateSymbol, DebugInfo debugInfo, String scopeId, String returnUnsetLabel)
      Generate field set status comparison check.

      This optimization compares the _fieldSetStatus() bitmasks of both objects. If the bitmasks differ, it means different fields are set/unset between the objects, so the comparison result should be unset (tri-state semantics).

      Pattern:

        _thisStatus = CALL this._fieldSetStatus() -> Bits
        _otherStatus = CALL other._fieldSetStatus() -> Bits
        _statusEq = CALL _thisStatus._eq(_otherStatus) -> Boolean
        _statusEqSet = CALL _statusEq._isSet() -> Boolean
        BRANCH_IF_FALSE _statusEqSet -> return_unset  // shouldn't happen but safe
        _statusEqVal = CALL _statusEq._true() -> boolean
        BRANCH_IF_FALSE _statusEqVal -> return_unset  // different field set patterns
      
      Parameters:
      otherParamName - The name of the other parameter to compare with (typically "param")
      aggregateSymbol - The aggregate as a SYMBOL - supplies both the emitted type name and the dispatch flag, so a closed aggregate's _fieldSetStatus() calls are direct
      debugInfo - Debug information
      scopeId - Current scope ID
      returnUnsetLabel - Label to branch to if bitmasks differ
      Returns:
      List of IR instructions implementing the check
    • generateUnsetReturnBlockWithLabel

      protected List<IRInstr> generateUnsetReturnBlockWithLabel(String labelName, String returnTypeName, String returnVarName, DebugInfo debugInfo, String scopeId)
      Generate unset return block at a specific label.

      Unlike the other overload of generateUnsetReturnBlockWithLabel, this version uses the provided label name instead of generating a new one. Use this when you need to branch to the unset return from multiple locations.

      Parameters:
      labelName - The label name for this block
      returnTypeName - The type of value to return
      returnVarName - The name of the return variable
      debugInfo - Debug information
      scopeId - Current scope ID
      Returns:
      List of IR instructions for the unset return block
    • generateResultReturnBlock

      protected List<IRInstr> generateResultReturnBlock(String labelName, String returnVarName, DebugInfo debugInfo, String scopeId)
      Generate a result return block that returns whatever is in the return variable.

      This is a shared return point when the return variable has already been set by the caller. Only performs scope cleanup and return.

      Pattern:

        label_name:
        SCOPE_EXIT scope_id
        RETURN returnVarName
      
      Parameters:
      labelName - The label name for this block
      returnVarName - The return variable name (already set by caller)
      debugInfo - Debug information
      scopeId - Current scope ID
      Returns:
      List of IR instructions for the return block
    • generateResultReturnBlock

      protected List<IRInstr> generateResultReturnBlock(String labelName, String returnVarName, SynthesisScope ctx)
      Generate result return block using SynthesisScope.

      Convenience overload that extracts debugInfo and scopeId from the context.

      Parameters:
      labelName - The label for this return block
      returnVarName - The return variable name (already set by caller)
      ctx - Synthesis scope context
      Returns:
      List of IR instructions for the return block
    • generateIsSetGuard

      protected List<IRInstr> generateIsSetGuard(String variableName, String typeName, ISymbol type, String unsetLabel, SynthesisScope ctx)
      Generate isSet guard check for a variable using SynthesisScope.
      Parameters:
      variableName - The variable to check
      typeName - The fully qualified type name of the variable
      type - That type as a SYMBOL, so the _isSet metadata is read rather than defaulted
      unsetLabel - Label to branch to if unset
      ctx - IR generation context
      Returns:
      List of IR instructions for the guard
    • generateThisIsSetGuard

      protected List<IRInstr> generateThisIsSetGuard(String aggregateTypeName, ISymbol aggregateType, String unsetLabel, SynthesisScope ctx)
      Generate isSet guard for 'this' using SynthesisScope.
      Parameters:
      aggregateTypeName - The fully qualified type name of the aggregate
      unsetLabel - Label to branch to if unset
      ctx - IR generation context
      Returns:
      List of IR instructions for the guard
    • generateFieldLoad

      protected List<IRInstr> generateFieldLoad(String targetVar, String objectVar, String fieldName, String ownerTypeName, String fieldTypeName, SynthesisScope ctx)
      Generate field load using SynthesisScope with explicit type information.
      Parameters:
      targetVar - The variable to store the loaded value
      objectVar - The object to load from (typically "this" or "param")
      fieldName - The field name to load
      ownerTypeName - The fully qualified type name of the object that owns the field
      fieldTypeName - The fully qualified type name of the field
      ctx - IR generation context
      Returns:
      List of IR instructions
    • generateUnsetReturnBlockWithLabel

      protected List<IRInstr> generateUnsetReturnBlockWithLabel(String labelName, String returnTypeName, String returnVarName, SynthesisScope ctx)
      Generate unset return block using SynthesisScope.
      Parameters:
      labelName - The label name for this block
      returnTypeName - The type of value to return
      returnVarName - The name of the return variable
      ctx - IR generation context
      Returns:
      List of IR instructions for the unset return block
    • generateBooleanBranch

      protected List<IRInstr> generateBooleanBranch(String booleanVar, String label, boolean branchIfTrue, SynthesisScope ctx)
      Extract primitive boolean from Boolean object and branch.

      This consolidates the common pattern of calling _true() on a Boolean object to get a primitive boolean, then branching based on the result.

      Pattern:

        _temp = CALL booleanVar._true() -> boolean
        BRANCH_IF_TRUE/FALSE _temp, label
      
      Parameters:
      booleanVar - The Boolean variable to extract value from
      label - The label to branch to
      branchIfTrue - If true, branch when Boolean is true; if false, branch when false
      ctx - Synthesis scope context
      Returns:
      List of IR instructions