visitClassDeclaration method

  1. @override
Object? visitClassDeclaration(
  1. SClassDeclaration node
)
override

Implementation

@override
Object? visitClassDeclaration(SClassDeclaration node) {
  final className = node.namePart.typeName.name;
  if (Logger.isDebug) {
    Logger.debug(
      "[Visitor.visitClassDeclaration] START for '$className' in env: ${environment.hashCode}",
    );
  }

  // Retrieve the placeholder class object created in Pass 1
  Object? placeholder = environment.get(className);
  if (placeholder == null || placeholder is! InterpretedClass) {
    // This should not happen if Pass 1 worked correctly
    throw StateD4rtException(
      "Placeholder for class '$className' not found or invalid during Pass 2.",
    );
  }
  final klass = placeholder;
  // SCD72: record the visitor so `InterpretedInstance.toString()` can reach a
  // script's own `toString` override after the interpreter has unwound — which
  // is exactly when a host reads it (measured: `D4.activeVisitor` is null
  // inside an `onUncaughtError` hook). Once per class, not per instance.
  klass.declaringVisitor = this;
  // SCE130: pass 1 resolved this class's type-parameter bounds before any
  // import or type alias existed, and left behind whatever it could not
  // resolve. Repair it now, before any member is populated.
  // GitHub #9: a bound naming a class not declared yet while modules load
  // (exported by a barrel that has not reached it) is repaired once the
  // outermost load returns.
  final boundsEnv = environment;
  void repairBounds() => klass.resolveDeferredTypeParameterBounds(
    node.namePart.typeParameters,
    boundsEnv,
  );
  final boundNames = <String>[
    ...?node.namePart.typeParameters?.typeParameters
        .map(
          (param) => switch (param.bound) {
            SNamedType(:final name?) => name.name,
            _ => null,
          },
        )
        .nonNulls,
  ];
  if (!(boundNames.any((name) => !environment.isDefined(name)) &&
      moduleContext.deferUntilModulesLoaded(repairBounds))) {
    repairBounds();
  }
  if (Logger.isDebug) {
    Logger.debug(
      "[Visitor.visitClassDeclaration] Retrieved placeholder for '$className' (hash: ${klass.hashCode})",
    );
  }

  // GitHub #9 — the supertypes are resolved, and the inherited members
  // checked, in [resolveRelationships] / [checkInheritedMembers]. When a name
  // in the extends / implements / with clause is not declared yet while a
  // module load is in progress (an import cycle, or a barrel that has not
  // reached the export declaring it), both are handed to the module loader,
  // which runs them once the outermost load returns; the members below are
  // populated either way. A class whose supertypes are all declared is
  // resolved here, as before.
  final relationshipEnv = environment;
  void resolveRelationships() {
    // Resolve and populate relationships ON THE EXISTING klass object
    // Superclass lookup
    // InterpretedClass? superclass; // Keep this commented or remove
    if (node.extendsClause != null) {
      final superclassName = node.extendsClause!.superclass!.name!.name;
      if (Logger.isDebug) {
        Logger.debug(
          "[Visitor.visitClassDeclaration]   Trying to get superclass '$superclassName' from env: ${environment.hashCode}",
        );
      }
      Object? potentialSuperclass;
      try {
        potentialSuperclass = environment.get(
          _relationshipLookupName(node.extendsClause!.superclass!),
        );
      } on RuntimeD4rtException {
        throw RuntimeD4rtException(
          "Superclass '$superclassName' not found for class '$className'. Ensure it's defined.",
        );
      }

      if (potentialSuperclass is InterpretedClass) {
        // Standard Dart Superclass
        final superclass = potentialSuperclass;

        // Add checks for final and interface modifiers
        // Note: sealed and interface classes CAN be extended within the same library/file,
        // and in D4rt all interpreted code is considered the same library
        //
        // For 'final' classes:
        // - A 'final' class cannot be extended outside its library
        // - An 'abstract final' class CAN be extended within the same library (needs implementation)
        // - Since all D4rt code is considered the same library, we only block non-abstract final classes
        if (superclass.isFinal && !superclass.isAbstract) {
          throw RuntimeD4rtException(
            "Class '$className' cannot extend final class '$superclassName'.",
          );
        }
        // Interface classes can be extended within the same library, so we allow it in D4rt
        // sealed classes are also allowed to be extended - they restrict external libraries only

        // Set the superclass and clear bridged superclass
        klass.superclass = superclass;
        klass.bridgedSuperclass = null;
        if (Logger.isDebug) {
          Logger.debug(
            "[Visitor.visitClassDeclaration] Set standard superclass '$superclassName' for '$className'",
          );
        }
      } else if (potentialSuperclass is BridgedClass) {
        final bridgedSuperclass = potentialSuperclass;
        // No modifier checks needed for bridged classes (yet?)

        // Set the bridged superclass and clear standard superclass
        klass.bridgedSuperclass = bridgedSuperclass;
        klass.superclass = null;

        // Capture the reified type arguments from the extends clause so
        // proxy factories can pick the right typed variant (e.g.
        // `extends CustomClipper<RRect>` → pick the RRect proxy, not the
        // default Path one). See [InterpretedClass.bridgedSuperTypeArgNames].
        final superTypeArgs =
            node.extendsClause!.superclass!.typeArguments?.arguments;
        if (superTypeArgs != null && superTypeArgs.isNotEmpty) {
          klass.bridgedSuperTypeArgNames = superTypeArgs
              .map((arg) => arg is SNamedType ? (arg.name?.name ?? '') : '')
              .toList();
        }

        if (Logger.isDebug) {
          Logger.debug(
            "[Visitor.visitClassDeclaration] Set BRIDGED superclass '$superclassName' for '$className' (typeArgs=${klass.bridgedSuperTypeArgNames})",
          );
        }
      } else {
        throw RuntimeD4rtException(
          "Superclass '$superclassName' for class '$className' resolved to ${potentialSuperclass?.runtimeType}, which is not a class or bridged class.",
        );
      }
    }

    // Interface lookup
    if (node.implementsClause != null) {
      if (Logger.isDebug) {
        Logger.debug(
          "[Visitor.visitClassDeclaration] Processing 'implements' clause for '$className' in env: ${environment.hashCode}",
        );
      }
      for (final interfaceType in node.implementsClause!.interfaces) {
        final interfaceName = interfaceType.name!.name;
        if (Logger.isDebug) {
          Logger.debug(
            "[Visitor.visitClassDeclaration]   Trying to get interface '$interfaceName' from env: ${environment.hashCode}",
          );
        }
        try {
          final potentialInterface = environment.get(
            _relationshipLookupName(interfaceType),
          );
          if (potentialInterface is InterpretedClass) {
            // Add checks for base modifier only
            // Note: sealed classes CAN be implemented within the same library/file
            if (potentialInterface.isBase) {
              throw RuntimeD4rtException(
                "Class '$className' cannot implement base class '$interfaceName' outside of its library.",
              );
            }
            // sealed classes are allowed to be implemented - they restrict external libraries only

            // Add to the interfaces list of the existing klass object
            klass.interfaces.add(potentialInterface);
            if (Logger.isDebug) {
              Logger.debug(
                "[Visitor.visitClassDeclaration] Added interface '$interfaceName' for '$className'",
              );
            }
          } else if (potentialInterface is BridgedClass) {
            // Support for bridged interfaces like Comparable, Exception
            klass.bridgedInterfaces.add(potentialInterface);
            if (Logger.isDebug) {
              Logger.debug(
                "[Visitor.visitClassDeclaration] Added bridged interface '$interfaceName' for '$className'",
              );
            }
          } else {
            throw RuntimeD4rtException(
              "Class '$className' cannot implement non-class '$interfaceName' (${potentialInterface?.runtimeType}).",
            );
          }
        } on RuntimeD4rtException {
          throw RuntimeD4rtException(
            "Interface '$interfaceName' not found for class '$className'. Ensure it's defined.",
          );
        }
      }
    }

    // Mixin application lookup
    if (node.withClause != null) {
      if (Logger.isDebug) {
        Logger.debug(
          "[Visitor.visitClassDeclaration] Processing 'with' clause for '$className' in env: ${environment.hashCode}",
        );
      }
      for (final mixinType in node.withClause!.mixinTypes) {
        final mixinName = mixinType.name!.name;
        if (Logger.isDebug) {
          Logger.debug(
            "[Visitor.visitClassDeclaration]   Trying to get mixin '$mixinName' from env: ${environment.hashCode}",
          );
        }

        Object? mixin;
        try {
          mixin = environment.get(_relationshipLookupName(mixinType));
        } on RuntimeD4rtException {
          throw RuntimeD4rtException(
            "Mixin '$mixinName' not found during lookup for class '$className'. Ensure it's defined (as a mixin or class mixin).",
          );
        }

        if (mixin is InterpretedClass) {
          if (!mixin.isMixin) {
            throw RuntimeD4rtException(
              "Class '$mixinName' cannot be used as a mixin because it's not declared with 'mixin' or 'class mixin'.",
            );
          }

          // Add checks for base modifier only
          // Note: sealed classes CAN be mixed in within the same library/file
          if (mixin.isBase) {
            throw RuntimeD4rtException(
              "Class '$className' cannot mix in base class '$mixinName' outside of its library.",
            );
          }
          // sealed classes are allowed to be mixed in - they restrict external libraries only

          // Add to the mixins list of the existing klass object
          klass.mixins.add(mixin);
          if (Logger.isDebug) {
            Logger.debug(
              "[Visitor.visitClassDeclaration] Applied interpreted mixin '$mixinName' to '$className'",
            );
          }
        } else if (mixin is BridgedClass) {
          // Support for bridged classes as mixins
          if (!mixin.canBeUsedAsMixin) {
            throw RuntimeD4rtException(
              "Bridged class '$mixinName' cannot be used as a mixin. Set canBeUsedAsMixin=true when registering the bridge.",
            );
          }

          // Add to the bridged mixins list
          klass.bridgedMixins.add(mixin);
          if (Logger.isDebug) {
            Logger.debug(
              "[Visitor.visitClassDeclaration] Applied bridged mixin '$mixinName' to '$className'",
            );
          }
        } else {
          throw RuntimeD4rtException(
            "Identifier '$mixinName' resolved to ${mixin?.runtimeType}, which is not a class/mixin, for class '$className'.",
          );
        }
      }
    }
  }

  final supertypeNames = <String>[
    if (node.extendsClause != null)
      _relationshipLookupName(node.extendsClause!.superclass!),
    for (final type
        in node.implementsClause?.interfaces ?? const <SNamedType>[])
      _relationshipLookupName(type),
    for (final type in node.withClause?.mixinTypes ?? const <SNamedType>[])
      _relationshipLookupName(type),
  ];
  void checkInheritedMembers() {
    // ghissues46: a class with a noSuchMethod other than Object's (its own,
    // an interpreted superclass's or mixin's, or a bridged superclass's or
    // mixin's) gets a forwarder for every member its interfaces and
    // abstract superclasses leave unimplemented, so nothing is missing. A
    // class relying on Object's noSuchMethod is still checked.
    if (klass.isAbstract || klass.hasNonTrivialNoSuchMethod) return;

    // Check for unimplemented abstract members
    if (!klass.isAbstract) {
      final inheritedAbstract = klass.getAbstractInheritedMembers();
      // G-DOV-6/7 FIX: Use getAllConcreteMembers() to walk the full superclass chain
      // (not just this class + mixins), so grandparent concrete implementations are found.
      final concreteMembers = klass.getAllConcreteMembers();
      final fieldNames = klass
          .getInstanceFieldNames(); // Fields also satisfy abstract getters
      for (final abstractName in inheritedAbstract.keys) {
        // Check if the abstract member is satisfied by a concrete method/getter/setter OR a field
        if (!concreteMembers.containsKey(abstractName) &&
            !fieldNames.contains(abstractName)) {
          final abstractMember = inheritedAbstract[abstractName]!;
          String memberType = "method";
          if (abstractMember.isGetter) memberType = "getter";
          if (abstractMember.isSetter) memberType = "setter";
          throw RuntimeD4rtException(
            "Missing concrete implementation for inherited abstract $memberType '$abstractName' in class '${klass.name}'.",
          );
        }
      }
    }

    // Check for unimplemented interface members
    if (!klass.isAbstract) {
      final requiredInterfaceMembers = klass.getAllInterfaceMembers();
      final availableConcreteMembers = klass.getAllConcreteMembers();
      for (final requiredName in requiredInterfaceMembers.keys) {
        if (!availableConcreteMembers.containsKey(requiredName)) {
          final memberType = requiredInterfaceMembers[requiredName]!;
          throw RuntimeD4rtException(
            "Missing concrete implementation for interface $memberType '$requiredName' in class '${klass.name}'.",
          );
        }
      }
    }
  }

  final relationshipsDeferred =
      supertypeNames.any((name) => !environment.isDefined(name)) &&
      moduleContext.deferUntilModulesLoaded(() {
        final savedEnv = environment;
        try {
          environment = relationshipEnv;
          resolveRelationships();
          checkInheritedMembers();
        } finally {
          environment = savedEnv;
        }
      });
  if (!relationshipsDeferred) resolveRelationships();

  // Populate members ON THE EXISTING klass object
  final staticInitEnv = environment; // Statics use the class definition env
  final originalVisitorEnv = environment; // Backup visitor env

  if (Logger.isDebug) {
    Logger.debug(
      "[Visitor.visitClassDeclaration] Processing members for '$className' (hash: ${klass.hashCode})",
    );
  }

  for (final member in node.body.members) {
    if (member is SMethodDeclaration) {
      final methodName = member.name!.name;
      // Pass the ALREADY RETRIEVED klass object
      // GitHub #9: lenient bounds while modules load; see
      // [_deferUnresolvedBounds].
      final lenientBounds = moduleContext.isLoadingModules;
      final function = InterpretedFunction.method(
        member,
        staticInitEnv,
        klass,
        lenientBounds: lenientBounds,
      );
      if (lenientBounds) {
        _deferUnresolvedBounds(
          function,
          member.typeParameters,
          staticInitEnv,
        );
      }

      if (member.isStatic) {
        if (member.isGetter) {
          klass.staticGetters[methodName] = function;
        } else if (member.isSetter) {
          klass.staticSetters[methodName] = function;
        } else {
          klass.staticMethods[methodName] = function;
        }
      } else if (!member.isAbstract) {
        if (member.isGetter) {
          klass.getters[methodName] = function;
        } else if (member.isSetter) {
          klass.setters[methodName] = function;
        } else if (member.isOperator) {
          // Add operator methods to the operators map
          klass.operators[methodName] = function;
        } else {
          klass.methods[methodName] = function;
        }
      } else {
        // Abstract
        if (!klass.isAbstract) {
          throw RuntimeD4rtException(
            "Abstract methods can only be declared in abstract classes. Method '${klass.name}.$methodName'.",
          );
        }
        if (member.body is! SEmptyFunctionBody) {
          throw RuntimeD4rtException(
            "Abstract methods cannot have a body. Method '${klass.name}.$methodName'.",
          );
        }
        if (member.isGetter) {
          klass.getters[methodName] = function;
        } else if (member.isSetter) {
          klass.setters[methodName] = function;
        } else if (member.isOperator) {
          // Add abstract operator methods to the operators map
          klass.operators[methodName] = function;
        } else {
          klass.methods[methodName] = function;
        }
      }
    } else if (member is SConstructorDeclaration) {
      final function = InterpretedFunction.constructor(
        member,
        staticInitEnv,
        klass,
      );
      final constructorName = member.name?.name ?? '';
      klass.constructors[constructorName] = function;
    } else if (member is SFieldDeclaration) {
      // Defer static field processing - collect them for later
      if (!member.isStatic) {
        klass.fieldDeclarations.add(member);
      }
    } else {
      throw StateD4rtException('Unknown member type: ${member.runtimeType}');
    }
  }

  // Static fields are initialized LAZILY, on first read, as in Dart
  // (GitHub #10): every field with an initializer becomes a [LateVariable]
  // whose initializer runs in [staticFieldEvalEnv]. So declaration order does
  // not matter (`static const values = [base]; static const base = 'x';`),
  // a class nobody reads runs none of its initializers, and a field that
  // reads itself during its initialization is reported as a cycle. Every
  // holder is installed before any initializer can run, so a sibling read,
  // bare or qualified, finds its holder and initializes it on demand.
  final staticFieldDecls = <SVariableDeclaration>[];
  final staticFieldMeta =
      <
        String,
        (
          bool isLate,
          bool isFinal,
          SAstNode? initializer,
          bool declaredDouble,
        )
      >{};
  for (final member in node.body.members) {
    if (member is SFieldDeclaration && member.isStatic) {
      final isLate = member.fields!.isLate;
      final isFinal = member.fields!.isFinal || member.fields!.isConst;
      // ghissues32: an `int` bound to a `double` static field widens.
      final declaredDouble = ResolvedBinding.declaresDouble(
        member.fields!.type,
      );
      for (final variable in member.fields!.variables) {
        final fieldName = variable.name!.name;
        staticFieldDecls.add(variable);
        staticFieldMeta[fieldName] = (
          isLate,
          isFinal,
          variable.initializer,
          declaredDouble,
        );
        klass.staticFields[fieldName] = null;
      }
    }
  }

  // The environment the initializers run in: the class scope, plus every
  // static field's holder for bare sibling reads.
  final staticFieldEvalEnv = Environment(enclosing: staticInitEnv);

  void evaluateStaticFields() {
    for (final variable in staticFieldDecls) {
      final fieldName = variable.name!.name;
      final (isLate, isFinal, initializer, declaredDouble) =
          staticFieldMeta[fieldName]!;
      // A `double` field without an initializer still gets a holder, so a
      // later assignment widens (ghissues32).
      if (initializer == null && !isLate && !declaredDouble) {
        // `static int? n;` - null until assigned, nothing to run.
        klass.staticFields[fieldName] = null;
        staticFieldEvalEnv.define(fieldName, null);
        continue;
      }
      final holder = LateVariable(
        '${klass.name}.$fieldName',
        initializer == null
            ? (isLate ? null : () => null)
            : () {
                final savedEnv = environment;
                try {
                  environment = staticFieldEvalEnv;
                  return initializer.accept<Object?>(this);
                } finally {
                  environment = savedEnv;
                }
              },
        // A `late` field without `final` stays assignable; a non-late field
        // is assignable unless it is final or const.
        isFinal: isFinal,
        declaredDouble: declaredDouble,
      );
      klass.staticFields[fieldName] = holder;
      staticFieldEvalEnv.define(fieldName, holder);
    }
  }

  if (deferStaticFieldInits) {
    if (Logger.isDebug) {
      Logger.debug(
        "[ClassDecl] Deferring static-field initialization for class '${klass.name}' until all classes are declared.",
      );
    }
    _pendingStaticInitializers.add(evaluateStaticFields);
    // Leave environment where the caller expects it (originalVisitorEnv).
    environment = originalVisitorEnv;
  } else {
    try {
      evaluateStaticFields();
    } finally {
      environment = originalVisitorEnv;
    }
  }

  if (Logger.isDebug) {
    Logger.debug(
      "[Visitor.visitClassDeclaration] Finished processing members for '$className'",
    );
  }

  // Final Checks (run on the populated klass object)
  if (!relationshipsDeferred) checkInheritedMembers();
  // Perf T6: all function tables are fully populated; compact them into
  // their read-only form. staticFields is excluded (deferred init).
  klass.freezeMemberTables();

  if (Logger.isDebug) {
    Logger.debug("[Visitor.visitClassDeclaration] END for '$className'");
  }
  // No need to define/assign klass in the environment here, it was done in Pass 1.
  return null; // Class declaration statement doesn't return a value
}