Class 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
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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static final recordRecord bundling scope context with initialized instruction list. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final IRGenerationContextprotected final SynthesisedCallMetaDataTHE 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 aCallMetaDataDetailstuple. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedAbstractSyntheticGenerator(IRGenerationContext stackContext) Create a new synthetic generator with the given context. -
Method Summary
Modifier and TypeMethodDescriptionprotected booleanaggregateHasOperator(AggregateSymbol aggregateSymbol, String operatorName) Check if the given aggregate has a specific operator defined (in its own scope).protected SyntheticMethodCallBuilderCreate a builder for a constructor call.protected DebugInfocreateDebugInfo(ISymbol symbol) Create debug info from a symbol's source token.protected SynthesisScopecreateSynthesisScope(ISymbol symbol, String scopeLabel) Create an SynthesisScope for the given operator symbol.protected booleanfieldTypeHasRealOperator(ISymbol field, String glyph, boolean binary) Does the field's TYPE have a REALoperatorGlyphof its own (declared or inherited from a real super), as opposed to only the degenerateAnydefault that every type inherits?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).generateBinaryOperatorGuards(String aggregateTypeName, ISymbol aggregateType, String paramName, String unsetLabel, SynthesisScope ctx) Generate isSet guards for binary operators (this and param).generateBooleanBranch(String booleanVar, String label, boolean branchIfTrue, SynthesisScope ctx) Extract primitive boolean from Boolean object and branch.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.generateFieldLoad(String targetVar, String objectVar, String fieldName, String ownerTypeName, String fieldTypeName, SynthesisScope ctx) Generate field load using SynthesisScope with explicit type information.generateFieldSetStatusCheck(String otherParamName, AggregateSymbol aggregateSymbol, DebugInfo debugInfo, String scopeId, String returnUnsetLabel) Generate field set status comparison check.generateIsSetGuard(String variableName, String typeName, ISymbol type, String unsetLabel, SynthesisScope ctx) Generate isSet guard check for a variable using SynthesisScope.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.protected StringgenerateLabelName(String prefix) Generate a label name with the given prefix.generateResultReturnBlock(String labelName, String returnVarName, DebugInfo debugInfo, String scopeId) Generate a result return block that returns whatever is in the return variable.generateResultReturnBlock(String labelName, String returnVarName, SynthesisScope ctx) Generate result return block using SynthesisScope.generateStringLiteralLoad(String resultVar, String literalValue, DebugInfo debugInfo, String scopeId) Generate a string literal load with memory management.protected StringGenerate a temporary variable name.generateThisIsSetGuard(String aggregateTypeName, ISymbol aggregateType, String unsetLabel, SynthesisScope ctx) Generate isSet guard for 'this' using SynthesisScope.generateThisIsSetGuard(String aggregateTypeName, ISymbol aggregateType, DebugInfo debugInfo, String unsetLabel, String scopeId) Generate isSet guard check for 'this' with branch to unset return.generateUnsetReturnBlockWithLabel(String labelName, String returnTypeName, String returnVarName, DebugInfo debugInfo, String scopeId) Generate unset return block at a specific label.generateUnsetReturnBlockWithLabel(String labelName, String returnTypeName, String returnVarName, SynthesisScope ctx) Generate unset return block using SynthesisScope.protected ISymbolThe Any type SYMBOL - the root of every EK9 type, a Java interface at the backend.protected StringThe Any type name - seegetAnyType().protected ISymbolThe Bits type SYMBOL - seegetBooleanType().protected StringGet the Bits type name from the EK9 type system.protected ISymbolThe Boolean type SYMBOL - for reading call metadata off it, rather than only naming it.protected StringGet the Boolean type name from the EK9 type system.protected ISymbolThe Integer type SYMBOL - seegetBooleanType().protected StringGet the Integer type name from the EK9 type system.protected ReturnBlockHelperGet the shared ReturnBlockHelper instance.protected ISymbolThe String type SYMBOL - seegetBooleanType().protected StringGet the String type name from the EK9 type system.protected StringgetSuperTypeName(AggregateSymbol aggregateSymbol) Get the fully qualified name of the super aggregate.getSyntheticFields(AggregateSymbol aggregateSymbol) Get all fields from an aggregate that should be included in synthetic operations.protected ISymbolThe 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.protected StringgetTypeName(ISymbol symbol) Get the fully qualified name for a type.protected StringGet the Void type name from the EK9 type system.protected AbstractSyntheticGenerator.ScopeSetupinitializeScope(MethodSymbol operatorSymbol, String scopeLabel, String returnVarName, String returnTypeName) Initialize scope with return variable reference.protected AbstractSyntheticGenerator.ScopeSetupinitializeScopeNoReturn(MethodSymbol operatorSymbol, String scopeLabel) Initialize scope for void-returning methods (no return variable).protected booleanisAnyType(IAggregateSymbol type) Check if the given type is the Any type.protected booleanisTraitType(ISymbol symbol) Check if the given symbol's type is a trait.protected SyntheticMethodCallBuilderCreate a builder for a method call.protected booleansuperHasOperator(AggregateSymbol aggregateSymbol, String operatorName) Check if the super aggregate has a specific operator defined.
-
Field Details
-
stackContext
-
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 aCallMetaDataDetailstuple. See its javadoc for the two honest sources.
-
-
Constructor Details
-
AbstractSyntheticGenerator
Create a new synthetic generator with the given context.- Parameters:
stackContext- The IR generation context
-
-
Method Details
-
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
Create a builder for a method call.- Returns:
- A new SyntheticMethodCallBuilder configured for method calls
-
constructorCall
Create a builder for a constructor call.- Returns:
- A new SyntheticMethodCallBuilder configured for constructor calls
-
getTypeName
-
getType
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
Get the Boolean type name from the EK9 type system. -
getBooleanType
The Boolean type SYMBOL - for reading call metadata off it, rather than only naming it. -
getIntegerType
The Integer type SYMBOL - seegetBooleanType(). -
getIntegerTypeName
Get the Integer type name from the EK9 type system. -
getStringTypeName
Get the String type name from the EK9 type system. -
getStringType
The String type SYMBOL - seegetBooleanType(). -
getBitsTypeName
Get the Bits type name from the EK9 type system. -
getBitsType
The Bits type SYMBOL - seegetBooleanType(). -
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 synthesiseddefault operatorruns over a field whose type has no REAL operator of its own (seefieldTypeHasRealOperator(ISymbol, String, boolean)). -
getAnyTypeName
The Any type name - seegetAnyType(). -
fieldTypeHasRealOperator
Does the field's TYPE have a REALoperatorGlyphof its own (declared or inherited from a real super), as opposed to only the degenerateAnydefault 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 Stringhas no real<=>) - the generator must instead callAny'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 theAnyinterface default). Uses the sharedHasRealOperatorwalk.- Parameters:
field- the field symbolglyph- the operator glyph ("<=>","==","$","#?")binary- true for a self-typed single-argument operator (<=>,==); false for a no-argument operator ($,#?)
-
getVoidTypeName
Get the Void type name from the EK9 type system. -
generateTempName
Generate a temporary variable name. -
generateLabelName
-
createDebugInfo
-
createSynthesisScope
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 fromscopeLabel- 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 infoscopeLabel- 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 infoscopeLabel- 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 paramparamName- The parameter variable name (typically "param")unsetLabel- Label to branch to if either is unsetctx- 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 aggregatedebugInfo- Debug information for the instructionsunsetLabel- Label to branch to if unsetscopeId- 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 checktypeName- The fully qualified type name of the variabletype- That type as a SYMBOL, so the _isSet metadata is read rather than defaulteddebugInfo- Debug information for the instructionsunsetLabel- Label to branch to if unsetscopeId- 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 checkedaggregateTypeName- Fully qualified type namedebugInfo- Debug informationreturnUnsetLabel- Label to branch to if no fields are setscopeId- Current scope ID- Returns:
- List of IR instructions implementing the guard
-
getSyntheticFields
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
Check if the super aggregate has a specific operator defined.- Parameters:
aggregateSymbol- The aggregate whose super we're checkingoperatorName- The operator name (e.g., "==", "<=>")- Returns:
- true if super has the operator, false otherwise
-
isAnyType
Check if the given type is the Any type. -
isTraitType
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
Check if the given aggregate has a specific operator defined (in its own scope).- Parameters:
aggregateSymbol- The aggregate to checkoperatorName- The operator name (e.g., "?", "$", "#?")- Returns:
- true if the aggregate has the operator, false otherwise
-
getSuperTypeName
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 valueobjectVar- The object to load from (typically "this" or "param")fieldName- The field name to loadownerTypeName- The fully qualified type name of the object that owns the fieldfieldTypeName- The fully qualified type name of the fielddebugInfo- Debug informationscopeId- 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 literalliteralValue- The string literal valuedebugInfo- Debug informationscopeId- 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 directdebugInfo- Debug informationscopeId- Current scope IDreturnUnsetLabel- 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 blockreturnTypeName- The type of value to returnreturnVarName- The name of the return variabledebugInfo- Debug informationscopeId- 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 blockreturnVarName- The return variable name (already set by caller)debugInfo- Debug informationscopeId- 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 blockreturnVarName- 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 checktypeName- The fully qualified type name of the variabletype- That type as a SYMBOL, so the _isSet metadata is read rather than defaultedunsetLabel- Label to branch to if unsetctx- 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 aggregateunsetLabel- Label to branch to if unsetctx- 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 valueobjectVar- The object to load from (typically "this" or "param")fieldName- The field name to loadownerTypeName- The fully qualified type name of the object that owns the fieldfieldTypeName- The fully qualified type name of the fieldctx- 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 blockreturnTypeName- The type of value to returnreturnVarName- The name of the return variablectx- 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 fromlabel- The label to branch tobranchIfTrue- If true, branch when Boolean is true; if false, branch when falsectx- Synthesis scope context- Returns:
- List of IR instructions
-