visitFStringExpr method

  1. @override
Object? visitFStringExpr(
  1. FStringExpr expr
)

Visitor method for evaluating an FStringExpr (f"..."). Evaluates each part expression and returns the combined string.

Implementation

@override
Object? visitFStringExpr(FStringExpr expr) {
  StringBuffer result = StringBuffer();
  for (FStringPart part in expr.parts) {
    if (part is FStringLiteralPart) {
      result.write(part.value); // Append literal string directly
    } else if (part is FStringExpressionPart) {
      // Evaluate the expression part
      Object? value = evaluate(part.expression);
      // Apply formatting if specifier exists, otherwise stringify
      if (part.formatSpec != null && part.formatSpec!.isNotEmpty) {
        try {
          result.write(_formatValue(value, part.formatSpec!));
        } catch (e) {
          // Catch formatting errors
          throw RuntimeError(
            expr.token,
            "Error formatting value in f-string: $e",
          );
        }
      } else {
        // No format specifier, just convert value to string
        result.write(stringify(value));
      }
    }
  }
  return result.toString();
}