Skip to content

[code_builder] Chained cascade after nullable type cast emits ?.. syntax error #2693

Closed

Description

@kevmoo

Chaining .cascade(...) or .cascadeIndex(...) after an assignment whose right-hand side ends with a ? token (such as an unparenthesized nullable cast as T?, or asA once #1140 lands) emits as T?..nextField, which the Dart scanner lexes as the ?.. null-aware cascade operator on T.

  • Root cause: pkgs/code_builder/lib/src/specs/expression.dart#L315-L321 and expression.dart#L509-L526 emit .. with addSpace: false directly after expression.left without separating a trailing ? on the preceding cascade's RHS from the leading .. of the next cascade section.
  • Impact: Code generators emitting cascaded setter assignments (such as package:json_serializable) produce unparseable Dart output that crashes DartFormatter unless every cascaded RHS is manually padded with a trailing space (Code('${expr} ')).

Proposed Fix

  • In ExpressionEmitter.visitBinaryExpression (or by introducing a dedicated leading-space flag on cascade / cascadeIndex when chained onto an assignment/binary expression), emit a separating space (or newline) before .. / ?.. when expression.operator is '..' or '?..' and expression.left is a cascade assignment or ends with ?.
Minimal reproduction & DartFormatter error
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';

void main() {
  final expr = refer('Foo').call([])
      .cascade('a').assign(const CodeExpression(Code("json['a'] as int?")))
      .cascade('b').assign(literalNum(1));

  final raw = expr.accept(DartEmitter(useNullSafetySyntax: true)).toString();
  print(raw); // Foo()..a = json['a'] as int?..b = 1

  // Throws FormatterException: Can't Have type arguments on the receiver of a
  // null-aware cascade / Expected ';' after this.
  DartFormatter(languageVersion: DartFormatter.latestLanguageVersion)
      .formatStatement('$raw;');
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    package:code_buildertype-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions