visitWhileStatement method

  1. @override
Object? visitWhileStatement(
  1. SWhileStatement node
)
override

Visit a SWhileStatement.

Implementation

@override
Object? visitWhileStatement(SWhileStatement node) {
  while (true) {
    // Handle condition being BridgedInstance<bool>
    final conditionValue = node.condition!.accept<Object?>(this);
    bool conditionResult;
    final bridgedInstance = toBridgedInstance(conditionValue);
    if (conditionValue is bool) {
      conditionResult = conditionValue;
    } else if (bridgedInstance.$2 &&
        bridgedInstance.$1?.nativeObject is bool) {
      conditionResult = bridgedInstance.$1!.nativeObject as bool;
    } else {
      throw RuntimeD4rtException(
        "The condition of a 'while' loop must be a boolean, but was ${conditionValue?.runtimeType}.",
      );
    }

    if (!conditionResult) {
      break;
    }

    try {
      // Condition is true, execute the body
      node.body!.accept<Object?>(this);
    } on BreakException catch (e) {
      Logger.debug(
        "[While] Caught BreakException (label: ${e.label}) with current labels: $_currentStatementLabels",
      );
      if (e.label == null || _currentStatementLabels.contains(e.label)) {
        // Unlabeled break OR labeled break targeting this loop.
        Logger.debug("[While] Breaking loop.");
        break; // Exit the while loop
      } else {
        // Labeled break targeting an outer construct.
        Logger.debug("[While] Rethrowing outer break...");
        rethrow;
      }
    } on ContinueException catch (e) {
      Logger.debug(
        "[While] Caught ContinueException (label: ${e.label}) with current labels: $_currentStatementLabels",
      );
      if (e.label == null || _currentStatementLabels.contains(e.label)) {
        // Unlabeled continue OR labeled continue targeting this loop.
        Logger.debug("[While] Continuing loop.");
        continue; // Skip to the next iteration
      } else {
        // Labeled continue targeting an outer loop.
        Logger.debug("[While] Rethrowing outer continue...");
        rethrow;
      }
    }
    // Other exceptions will propagate up
  }
  return null;
}