Class ToJsonGenerator

java.lang.Object
org.ek9lang.compiler.phase7.synthesis.AbstractSyntheticGenerator
org.ek9lang.compiler.phase7.synthesis.ToJsonGenerator

final class ToJsonGenerator extends AbstractSyntheticGenerator
Generates synthetic IR for the _json ($$) operator.

The generated code follows this pattern:

JSON _json():
  // Guard: if this aggregate declares NO FIELDS at all, return UNSET JSON.
  // NOTE: this does NOT ask this._isSet() - '?' is AND over every field, so gating on it would
  // make a partial object serialise to nothing. An unset FIELD renders as JSON null instead.
  if this declares no fields -> return unset JSON

  // has_data: (label spelling is historical) the aggregate declares at least one field
  jsonTemp = JSON()
  result = jsonTemp.object()

  // For each field:
  fieldValue = LOAD this.field
  fieldJson = fieldValue._json()         // Recursive JSON conversion
  nameString = "fieldName" (literal)
  pair = JSON(nameString, fieldJson)     // Create name/value pair
  result._merge(pair)                    // Merge into result

  return result

  return_unset:
    return new JSON()  // Unset JSON

Key semantic requirements:

  • Returns UNSET JSON only for a FIELD-LESS aggregate - a record with fields always serialises, even when every field is unset (JsonAllFieldsUnsetTest pins {"name":null,...})
  • Stays SET for a PARTIAL object, unlike '$', which collapses to unset via copy-left String join. The asymmetry is deliberate: JSON has a null to render an unset field with
  • Format: {"field1": value1, "field2": value2}
  • Each field value is converted via $$ (_json) recursively
  • Unset field values become JSON null (handled by JSON constructor)
  • Lists produce JSON arrays, Dicts produce nested objects

⚠️ This operator does NOT consult '?'. See generateNoOwnFieldsGuard for why, and HashCodeGenerator for the contrasting decision taken by '#?'.

  • Constructor Details

  • Method Details

    • generate

      List<IRInstr> generate(MethodSymbol operatorSymbol, AggregateSymbol aggregateSymbol)
      Generate the _json operator IR for the given aggregate.
      Parameters:
      operatorSymbol - The _json operator symbol
      aggregateSymbol - The aggregate containing the operator
      Returns:
      List of IR instructions implementing the operator