Skip to content

Commit

Permalink
Fix convert to cascade
Browse files Browse the repository at this point in the history
Closes #56788

GitOrigin-RevId: 7e35273
Change-Id: I49af5c39267d6b91cfca40b4feb42e1d921a4eeb
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/386860
Reviewed-by: Brian Wilkerson <[email protected]>
Commit-Queue: Brian Wilkerson <[email protected]>
Reviewed-by: Samuel Rawlins <[email protected]>
  • Loading branch information
FMorschel authored and Commit Queue committed Sep 27, 2024
1 parent 2015686 commit 30a57b2
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,20 @@ class ConvertToCascade extends ResolvedCorrectionProducer {
if (block is! Block) return;

var previous = _getPrevious(block, node);
if (previous is! ExpressionStatement) return;
var previousOperator = _getTargetAndOperator(previous.expression)?.operator;
Token? previousOperator;
Token? semicolon;
if (previous is ExpressionStatement) {
semicolon = previous.semicolon;
previousOperator = _getTargetAndOperator(previous.expression)?.operator;
} else if (previous is VariableDeclarationStatement) {
// Single variable declaration.
if (previous.variables.variables.length != 1) {
return;
}
semicolon = previous.endToken;
} else {
return;
}

var expression = node.expression;
var target = _getTargetAndOperator(expression)?.target;
Expand All @@ -43,7 +55,9 @@ class ConvertToCascade extends ResolvedCorrectionProducer {
if (previousOperator != null) {
builder.addSimpleInsertion(previousOperator.offset, '.');
}
builder.addDeletion(range.token(previous.semicolon!));
if (semicolon != null) {
builder.addDeletion(range.token(semicolon));
}
builder.addSimpleReplacement(range.node(target), targetReplacement);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,27 @@ void f(A a) {
''');
}

Future<void> test_declaration_method() async {
await resolveTestCode('''
class A {
void m() {}
}
void f() {
final a = A();
a.m();
}
''');
await assertHasFix('''
class A {
void m() {}
}
void f() {
final a = A()
..m();
}
''');
}

Future<void> test_method_method() async {
await resolveTestCode('''
class A {
Expand Down Expand Up @@ -96,6 +117,32 @@ void f(A a) {
''');
}

Future<void> test_multipleDeclaration_first_method() async {
await resolveTestCode('''
class A {
void m() {}
}
void f() {
final a = A(), a2 = A();
a.m();
}
''');
await assertNoFix();
}

Future<void> test_multipleDeclaration_last_method() async {
await resolveTestCode('''
class A {
void m() {}
}
void f() {
final a = A(), a2 = A();
a2.m();
}
''');
await assertNoFix();
}

Future<void> test_property_cascade() async {
await resolveTestCode('''
class A {
Expand Down

0 comments on commit 30a57b2

Please sign in to comment.