Migrate several lib/src/services/correction/dart/
R=brianwilkerson@google.com
Change-Id: Ie38a28ee77c2faeb50f9c46e54a64cef933e3916
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/194880
Commit-Queue: Konstantin Shcheglov <scheglov@google.com>
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_required_argument.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_required_argument.dart
index d95722a..6da748e 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_required_argument.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_required_argument.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/src/services/completion/dart/utilities.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
@@ -12,10 +10,11 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:collection/collection.dart';
class AddMissingRequiredArgument extends CorrectionProducer {
/// The name of the parameter that was missing.
- String _missingParameterName;
+ String _missingParameterName = '';
@override
List<Object> get fixArguments => [_missingParameterName];
@@ -25,9 +24,9 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- InstanceCreationExpression creation;
- Element targetElement;
- ArgumentList argumentList;
+ InstanceCreationExpression? creation;
+ Element? targetElement;
+ ArgumentList? argumentList;
if (node is SimpleIdentifier || node is ConstructorName) {
var invocation = node.parent;
@@ -35,8 +34,7 @@
targetElement = invocation.methodName.staticElement;
argumentList = invocation.argumentList;
} else {
- creation =
- invocation.thisOrAncestorOfType<InstanceCreationExpression>();
+ creation = invocation?.thisOrAncestorOfType();
if (creation != null) {
targetElement = creation.constructorName.staticElement;
argumentList = creation.argumentList;
@@ -44,7 +42,12 @@
}
}
- if (targetElement is ExecutableElement) {
+ var diagnostic = this.diagnostic;
+ if (diagnostic == null) {
+ return;
+ }
+
+ if (targetElement is ExecutableElement && argumentList != null) {
// Format: "Missing required argument 'foo'."
var messageParts = diagnostic.problemMessage.message.split("'");
if (messageParts.length < 2) {
@@ -52,9 +55,9 @@
}
_missingParameterName = messageParts[1];
- var missingParameter = targetElement.parameters.firstWhere(
- (p) => p.name == _missingParameterName,
- orElse: () => null);
+ var missingParameter = targetElement.parameters.firstWhereOrNull(
+ (p) => p.name == _missingParameterName,
+ );
if (missingParameter == null) {
return;
}
@@ -68,7 +71,7 @@
} else {
var lastArgument = arguments.last;
offset = lastArgument.end;
- hasTrailingComma = lastArgument.endToken.next.type == TokenType.COMMA;
+ hasTrailingComma = lastArgument.endToken.next!.type == TokenType.COMMA;
if (lastArgument is NamedExpression &&
flutter.isWidgetExpression(creation)) {
@@ -80,9 +83,10 @@
}
}
}
+
var defaultValue = getDefaultStringParameterValue(missingParameter,
withNullability: libraryElement.isNonNullableByDefault &&
- missingParameter.library.isNonNullableByDefault);
+ (missingParameter.library?.isNonNullableByDefault ?? false));
await builder.addDartFileEdit(file, (builder) {
builder.addInsertion(offset, (builder) {
@@ -93,14 +97,17 @@
builder.write('$_missingParameterName: ');
// Use defaultValue.cursorPosition if it's not null.
- if (defaultValue?.cursorPosition != null) {
- builder.write(
- defaultValue.text.substring(0, defaultValue.cursorPosition));
- builder.selectHere();
- builder.write(
- defaultValue.text.substring(defaultValue.cursorPosition));
+ if (defaultValue != null) {
+ var cursorPosition = defaultValue.cursorPosition;
+ if (cursorPosition != null) {
+ builder.write(defaultValue.text.substring(0, cursorPosition));
+ builder.selectHere();
+ builder.write(defaultValue.text.substring(cursorPosition));
+ } else {
+ builder.addSimpleLinkedEdit('VALUE', defaultValue.text);
+ }
} else {
- builder.addSimpleLinkedEdit('VALUE', defaultValue?.text);
+ builder.addSimpleLinkedEdit('VALUE', 'null');
}
if (flutter.isWidgetExpression(creation)) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_on_type.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_on_type.dart
index ead067d..a47567a 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_on_type.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_on_type.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -23,30 +21,30 @@
var exceptionParameter = node;
if (exceptionParameter is SimpleIdentifier) {
var catchClause = exceptionParameter.parent;
- if (catchClause is CatchClause &&
- catchClause.exceptionType == null &&
- catchClause.exceptionParameter == exceptionParameter) {
- var exceptionTypeName = exceptionParameter.name;
- fixArguments.add(exceptionTypeName);
- await builder.addDartFileEdit(file, (builder) {
- if (catchClause.stackTraceParameter != null) {
- builder.addSimpleReplacement(
- range.startStart(
- catchClause.catchKeyword,
- catchClause.stackTraceParameter,
- ),
- 'on $exceptionTypeName catch (_, ',
- );
- } else {
- builder.addSimpleReplacement(
- range.startEnd(
- catchClause.catchKeyword,
- catchClause.rightParenthesis,
- ),
- 'on $exceptionTypeName',
- );
- }
- });
+ if (catchClause is CatchClause) {
+ var catchKeyword = catchClause.catchKeyword;
+ var rightParenthesis = catchClause.rightParenthesis;
+ if (catchKeyword != null &&
+ catchClause.exceptionType == null &&
+ catchClause.exceptionParameter == exceptionParameter &&
+ rightParenthesis != null) {
+ var exceptionTypeName = exceptionParameter.name;
+ fixArguments.add(exceptionTypeName);
+ await builder.addDartFileEdit(file, (builder) {
+ var stackTraceParameter = catchClause.stackTraceParameter;
+ if (stackTraceParameter != null) {
+ builder.addSimpleReplacement(
+ range.startStart(catchKeyword, stackTraceParameter),
+ 'on $exceptionTypeName catch (_, ',
+ );
+ } else {
+ builder.addSimpleReplacement(
+ range.startEnd(catchKeyword, rightParenthesis),
+ 'on $exceptionTypeName',
+ );
+ }
+ });
+ }
}
}
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart
index 62a920e..f8788d4 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_for_final_fields.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/analysis/features.dart';
@@ -28,8 +26,12 @@
if (classDeclaration == null) {
return;
}
+
var className = classDeclaration.name.name;
- var superType = classDeclaration.declaredElement.supertype;
+ var superType = classDeclaration.declaredElement?.supertype;
+ if (superType == null) {
+ return;
+ }
// prepare names of uninitialized final fields
var fieldNames = <String>[];
@@ -45,11 +47,17 @@
}
// prepare location for a new constructor
var targetLocation = utils.prepareNewConstructorLocation(classDeclaration);
+ if (targetLocation == null) {
+ return;
+ }
if (flutter.isExactlyStatelessWidgetType(superType) ||
flutter.isExactlyStatefulWidgetType(superType)) {
// Specialize for Flutter widgets.
var keyClass = await sessionHelper.getClass(flutter.widgetsUri, 'Key');
+ if (keyClass == null) {
+ return;
+ }
await builder.addDartFileEdit(file, (builder) {
builder.addInsertion(targetLocation.offset, (builder) {
builder.write(targetLocation.prefix);
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_super.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_super.dart
index 212261b..e4acc52 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_super.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_constructor_super.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -16,16 +14,26 @@
@override
Iterable<CorrectionProducer> get producers sync* {
var targetClassNode = node.thisOrAncestorOfType<ClassDeclaration>();
- var targetClassElement = targetClassNode.declaredElement;
+ if (targetClassNode == null) {
+ return;
+ }
+
+ var targetClassElement = targetClassNode.declaredElement!;
var superType = targetClassElement.supertype;
+ if (superType == null) {
+ return;
+ }
+
// add proposals for all super constructors
for (var constructor in superType.constructors) {
// Only propose public constructors.
if (!Identifier.isPrivateName(constructor.name)) {
var targetLocation =
utils.prepareNewConstructorLocation(targetClassNode);
- yield _CreateConstructor(
- constructor, targetLocation, targetClassElement.name);
+ if (targetLocation != null) {
+ yield _CreateConstructor(
+ constructor, targetLocation, targetClassElement.name);
+ }
}
}
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
index fa00de2..ec42942 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_field.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -14,7 +12,7 @@
class CreateField extends CorrectionProducer {
/// The name of the field to be created.
- String _fieldName;
+ String _fieldName = '';
@override
List<Object> get fixArguments => [_fieldName];
@@ -38,9 +36,15 @@
if (targetClassNode == null) {
return;
}
+
var nameNode = parameter.identifier;
_fieldName = nameNode.name;
+
var targetLocation = utils.prepareNewFieldLocation(targetClassNode);
+ if (targetLocation == null) {
+ return;
+ }
+
//
// Add proposal.
//
@@ -56,13 +60,13 @@
}
Future<void> _proposeFromIdentifier(ChangeBuilder builder) async {
- if (node is! SimpleIdentifier) {
+ var nameNode = node;
+ if (nameNode is! SimpleIdentifier) {
return;
}
- SimpleIdentifier nameNode = node;
_fieldName = nameNode.name;
// prepare target Expression
- Expression target;
+ Expression? target;
{
var nameParent = nameNode.parent;
if (nameParent is PrefixedIdentifier) {
@@ -73,7 +77,7 @@
}
// prepare target ClassElement
var staticModifier = false;
- ClassElement targetClassElement;
+ ClassElement? targetClassElement;
if (target != null) {
targetClassElement = getTargetClassElement(target);
// maybe static
@@ -102,13 +106,20 @@
if (targetDeclarationResult == null) {
return;
}
- if (targetDeclarationResult.node is! ClassOrMixinDeclaration) {
+ var targetNode = targetDeclarationResult.node;
+ if (targetNode is! ClassOrMixinDeclaration) {
return;
}
- ClassOrMixinDeclaration targetNode = targetDeclarationResult.node;
// prepare location
- var targetLocation = CorrectionUtils(targetDeclarationResult.resolvedUnit)
- .prepareNewFieldLocation(targetNode);
+ var targetUnit = targetDeclarationResult.resolvedUnit;
+ if (targetUnit == null) {
+ return;
+ }
+ var targetLocation =
+ CorrectionUtils(targetUnit).prepareNewFieldLocation(targetNode);
+ if (targetLocation == null) {
+ return;
+ }
// build field source
var targetSource = targetClassElement.source;
var targetFile = targetSource.fullName;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_file.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_file.dart
index 6dd55bf..455c0c8 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_file.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_file.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -12,7 +10,7 @@
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
class CreateFile extends CorrectionProducer {
- String _fileName;
+ String _fileName = '';
@override
List<Object> get fixArguments => [_fileName];
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_function.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_function.dart
index 2351d57..1a8aaf4 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_function.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_function.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -12,7 +10,7 @@
import 'package:analyzer_plugin/utilities/range_factory.dart';
class CreateFunction extends CorrectionProducer {
- String _functionName;
+ String _functionName = '';
@override
List<Object> get fixArguments => [_functionName];
@@ -37,8 +35,10 @@
// prepare environment
int insertOffset;
String sourcePrefix;
- AstNode enclosingMember =
- node.thisOrAncestorOfType<CompilationUnitMember>();
+ var enclosingMember = node.thisOrAncestorOfType<CompilationUnitMember>();
+ if (enclosingMember == null) {
+ return;
+ }
insertOffset = enclosingMember.end;
sourcePrefix = '$eol$eol';
utils.targetClassElement = null;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
index 3ca2941..3c9c661 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_getter.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -14,7 +12,7 @@
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
class CreateGetter extends CorrectionProducer {
- String _getterName;
+ String _getterName = '';
@override
List<Object> get fixArguments => [_getterName];
@@ -24,16 +22,16 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- if (node is! SimpleIdentifier) {
+ var nameNode = node;
+ if (nameNode is! SimpleIdentifier) {
return;
}
- SimpleIdentifier nameNode = node;
_getterName = nameNode.name;
if (!nameNode.inGetterContext()) {
return;
}
// prepare target
- Expression target;
+ Expression? target;
{
var nameParent = nameNode.parent;
if (nameParent is PrefixedIdentifier) {
@@ -44,7 +42,7 @@
}
// prepare target element
var staticModifier = false;
- Element targetElement;
+ Element? targetElement;
if (target is ExtensionOverride) {
targetElement = target.staticElement;
} else if (target is Identifier &&
@@ -72,7 +70,11 @@
}
staticModifier = inStaticContext;
}
- if (targetElement.librarySource.isInSystemLibrary) {
+ if (targetElement == null) {
+ return;
+ }
+ var targetSource = targetElement.source;
+ if (targetSource == null || targetSource.isInSystemLibrary) {
return;
}
// prepare target declaration
@@ -81,16 +83,26 @@
if (targetDeclarationResult == null) {
return;
}
- if (targetDeclarationResult.node is! ClassOrMixinDeclaration &&
- targetDeclarationResult.node is! ExtensionDeclaration) {
+ var targetNode = targetDeclarationResult.node;
+ if (targetNode is CompilationUnitMember) {
+ if (targetDeclarationResult.node is! ClassOrMixinDeclaration &&
+ targetDeclarationResult.node is! ExtensionDeclaration) {
+ return;
+ }
+ } else {
return;
}
- CompilationUnitMember targetNode = targetDeclarationResult.node;
// prepare location
- var targetLocation = CorrectionUtils(targetDeclarationResult.resolvedUnit)
- .prepareNewGetterLocation(targetNode);
+ var resolvedUnit = targetDeclarationResult.resolvedUnit;
+ if (resolvedUnit == null) {
+ return;
+ }
+ var targetLocation =
+ CorrectionUtils(resolvedUnit).prepareNewGetterLocation(targetNode);
+ if (targetLocation == null) {
+ return;
+ }
// build method source
- var targetSource = targetElement.source;
var targetFile = targetSource.fullName;
await builder.addDartFileEdit(targetFile, (builder) {
builder.addInsertion(targetLocation.offset, (builder) {
@@ -100,7 +112,7 @@
builder.writeGetterDeclaration(_getterName,
isStatic: staticModifier,
nameGroupName: 'NAME',
- returnType: fieldType,
+ returnType: fieldType ?? typeProvider.dynamicType,
returnTypeGroupName: 'TYPE');
builder.write(targetLocation.suffix);
});
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_local_variable.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_local_variable.dart
index 42ba1d7..22b464e 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_local_variable.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_local_variable.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
@@ -14,7 +12,7 @@
import 'package:analyzer_plugin/utilities/range_factory.dart';
class CreateLocalVariable extends CorrectionProducer {
- String _variableName;
+ String _variableName = '';
@override
List<Object> get fixArguments => [_variableName];
@@ -24,14 +22,14 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- if (node is! SimpleIdentifier) {
+ var nameNode = node;
+ if (nameNode is! SimpleIdentifier) {
return;
}
- SimpleIdentifier nameNode = node;
_variableName = nameNode.name;
// if variable is assigned, convert assignment into declaration
- if (node.parent is AssignmentExpression) {
- AssignmentExpression assignment = node.parent;
+ var assignment = node.parent;
+ if (assignment is AssignmentExpression) {
if (assignment.leftHandSide == node &&
assignment.operator.type == TokenType.EQ &&
assignment.parent is ExpressionStatement) {
@@ -48,7 +46,7 @@
}
var prefix = utils.getNodePrefix(target);
// compute type
- var type = inferUndefinedExpressionType(node);
+ var type = inferUndefinedExpressionType(nameNode);
if (!(type == null || type is InterfaceType || type is FunctionType)) {
return;
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
index 66397fc..a697fff 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_method.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -18,7 +16,7 @@
/// The kind of method to be created.
final _MethodKind _kind;
- String _memberName;
+ String _memberName = '';
CreateMethod(this._kind);
@@ -47,11 +45,11 @@
}
final classDecl = memberDecl.thisOrAncestorOfType<ClassDeclaration>();
if (classDecl != null) {
- final classElement = classDecl.declaredElement;
+ final classElement = classDecl.declaredElement!;
var missingEquals = memberDecl is FieldDeclaration ||
(memberDecl as MethodDeclaration).name.name == 'hashCode';
- ExecutableElement element;
+ ExecutableElement? element;
if (missingEquals) {
_memberName = '==';
element = classElement.lookUpInheritedMethod(
@@ -61,14 +59,21 @@
element = classElement.lookUpInheritedConcreteGetter(
_memberName, classElement.library);
}
+ if (element == null) {
+ return;
+ }
final location =
utils.prepareNewClassMemberLocation(classDecl, (_) => true);
+ if (location == null) {
+ return;
+ }
+ final element_final = element;
await builder.addDartFileEdit(file, (fileBuilder) {
fileBuilder.addInsertion(location.offset, (builder) {
builder.write(location.prefix);
- builder.writeOverride(element, invokeSuper: true);
+ builder.writeOverride(element_final, invokeSuper: true);
builder.write(location.suffix);
});
});
@@ -84,24 +89,28 @@
_memberName = (node as SimpleIdentifier).name;
var invocation = node.parent as MethodInvocation;
// prepare environment
- Element targetElement;
+ Element? targetElement;
var staticModifier = false;
- CompilationUnitMember targetNode;
+ CompilationUnitMember? targetNode;
var target = invocation.realTarget;
var utils = this.utils;
if (target is ExtensionOverride) {
targetElement = target.staticElement;
- targetNode = await getExtensionDeclaration(targetElement);
- if (targetNode == null) {
- return;
+ if (targetElement is ExtensionElement) {
+ targetNode = await getExtensionDeclaration(targetElement);
+ if (targetNode == null) {
+ return;
+ }
}
} else if (target is Identifier &&
target.staticElement is ExtensionElement) {
targetElement = target.staticElement;
- targetNode = await getExtensionDeclaration(targetElement);
- if (targetNode == null) {
- return;
+ if (targetElement is ExtensionElement) {
+ targetNode = await getExtensionDeclaration(targetElement);
+ if (targetNode == null) {
+ return;
+ }
}
staticModifier = true;
} else if (target == null) {
@@ -112,8 +121,11 @@
// doesn't make sense to create a method.
return;
}
- targetNode = enclosingMember.parent;
- staticModifier = inStaticContext;
+ var enclosingMemberParent = enclosingMember.parent;
+ if (enclosingMemberParent is CompilationUnitMember) {
+ targetNode = enclosingMemberParent;
+ staticModifier = inStaticContext;
+ }
} else {
var targetClassElement = getTargetClassElement(target);
if (targetClassElement == null) {
@@ -130,7 +142,7 @@
}
// maybe static
if (target is Identifier) {
- staticModifier = target.staticElement.kind == ElementKind.CLASS;
+ staticModifier = target.staticElement?.kind == ElementKind.CLASS;
}
// use different utils
var targetPath = targetClassElement.source.fullName;
@@ -138,8 +150,18 @@
await resolvedResult.session.getResolvedUnit(targetPath);
utils = CorrectionUtils(targetResolveResult);
}
+ if (targetElement == null || targetNode == null) {
+ return;
+ }
var targetLocation = utils.prepareNewMethodLocation(targetNode);
- var targetFile = targetElement.source.fullName;
+ if (targetLocation == null) {
+ return;
+ }
+ var targetSource = targetElement.source;
+ if (targetSource == null) {
+ return;
+ }
+ var targetFile = targetSource.fullName;
// build method source
await builder.addDartFileEdit(targetFile, (builder) {
builder.addInsertion(targetLocation.offset, (builder) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart
index c831928..3695dfa 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_method_or_function.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -17,9 +15,9 @@
import 'package:analyzer_plugin/utilities/range_factory.dart';
class CreateMethodOrFunction extends CorrectionProducer {
- FixKind _fixKind;
+ FixKind _fixKind = DartFixKind.CREATE_METHOD;
- String _functionName;
+ String _functionName = '';
@override
List<Object> get fixArguments => [_functionName];
@@ -29,10 +27,10 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- if (node is SimpleIdentifier) {
- var nameNode = node as SimpleIdentifier;
+ var nameNode = node;
+ if (nameNode is SimpleIdentifier) {
// prepare argument expression (to get parameter)
- ClassElement targetElement;
+ ClassElement? targetElement;
Expression argument;
{
var target = getQualifiedPropertyTarget(node);
@@ -70,12 +68,11 @@
if (parameterType is! FunctionType) {
return;
}
- var functionType = parameterType as FunctionType;
// add proposal
if (targetElement != null) {
- await _createMethod(builder, targetElement, functionType);
+ await _createMethod(builder, targetElement, parameterType);
} else {
- await _createFunction(builder, functionType);
+ await _createFunction(builder, parameterType);
}
}
}
@@ -135,7 +132,7 @@
var sourcePrefix = '$eol';
var sourceSuffix = eol;
await _createExecutable(builder, functionType, name, file, insertOffset,
- false, prefix, sourcePrefix, sourceSuffix, unit.declaredElement);
+ false, prefix, sourcePrefix, sourceSuffix, unit.declaredElement!);
_fixKind = DartFixKind.CREATE_FUNCTION;
_functionName = name;
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_missing_overrides.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_missing_overrides.dart
index a1e5881..e6e0c70 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_missing_overrides.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_missing_overrides.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/utilities/strings.dart';
@@ -15,7 +13,7 @@
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
class CreateMissingOverrides extends CorrectionProducer {
- int _numElements;
+ int _numElements = 0;
@override
List<Object> get fixArguments => [_numElements];
@@ -48,6 +46,9 @@
var location =
utils.prepareNewClassMemberLocation(targetClass, (_) => true);
+ if (location == null) {
+ return;
+ }
var prefix = utils.getIndent(1);
await builder.addDartFileEdit(file, (builder) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart
index 6f783b2..14c4598 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_mixin.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -14,7 +12,7 @@
import 'package:analyzer_plugin/utilities/range_factory.dart';
class CreateMixin extends CorrectionProducer {
- String _mixinName;
+ String _mixinName = '';
@override
List<Object> get fixArguments => [_mixinName];
@@ -24,13 +22,15 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- Element prefixElement;
+ Element? prefixElement;
SimpleIdentifier nameNode;
+ var node = this.node;
if (node is SimpleIdentifier) {
var parent = node.parent;
+ var grandParent = parent?.parent;
if (parent is TypeName &&
- parent.parent is ConstructorName &&
- parent.parent.parent is InstanceCreationExpression) {
+ grandParent is ConstructorName &&
+ grandParent.parent is InstanceCreationExpression) {
return;
} else {
nameNode = node;
@@ -40,13 +40,12 @@
if (node.parent is InstanceCreationExpression) {
return;
}
- PrefixedIdentifier prefixedIdentifier = node;
- prefixElement = prefixedIdentifier.prefix.staticElement;
+ prefixElement = node.prefix.staticElement;
if (prefixElement == null) {
return;
}
- nameNode = prefixedIdentifier.identifier;
- _mixinName = prefixedIdentifier.identifier.name;
+ nameNode = node.identifier;
+ _mixinName = node.identifier.name;
} else {
return;
}
@@ -58,9 +57,9 @@
var prefix = '';
var suffix = '';
var offset = -1;
- String filePath;
+ String? filePath;
if (prefixElement == null) {
- targetUnit = unit.declaredElement;
+ targetUnit = unit.declaredElement!;
var enclosingMember = node.thisOrAncestorMatching((node) =>
node is CompilationUnitMember && node.parent is CompilationUnit);
if (enclosingMember == null) {
@@ -77,8 +76,10 @@
targetUnit = library.definingCompilationUnit;
var targetSource = targetUnit.source;
try {
- offset = targetSource.contents.data.length;
- filePath = targetSource.fullName;
+ if (targetSource != null) {
+ offset = targetSource.contents.data.length;
+ filePath = targetSource.fullName;
+ }
prefix = '$eol';
suffix = '$eol';
} on FileSystemException {
@@ -90,7 +91,7 @@
}
}
}
- if (offset < 0) {
+ if (filePath == null || offset < 0) {
return;
}
await builder.addDartFileEdit(filePath, (builder) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_no_such_method.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_no_such_method.dart
index 92af6ca..aa62503 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_no_such_method.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_no_such_method.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart b/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
index c6c7fc5..8958731 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/create_setter.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/util.dart';
@@ -14,7 +12,7 @@
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
class CreateSetter extends CorrectionProducer {
- String _setterName;
+ String _setterName = '';
@override
List<Object> get fixArguments => [_setterName];
@@ -24,15 +22,15 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- if (node is! SimpleIdentifier) {
+ var nameNode = node;
+ if (nameNode is! SimpleIdentifier) {
return;
}
- SimpleIdentifier nameNode = node;
if (!nameNode.inSetterContext()) {
return;
}
// prepare target
- Expression target;
+ Expression? target;
{
var nameParent = nameNode.parent;
if (nameParent is PrefixedIdentifier) {
@@ -43,7 +41,7 @@
}
// prepare target element
var staticModifier = false;
- Element targetElement;
+ Element? targetElement;
if (target is ExtensionOverride) {
targetElement = target.staticElement;
} else if (target is Identifier &&
@@ -71,7 +69,11 @@
}
staticModifier = inStaticContext;
}
- if (targetElement.librarySource.isInSystemLibrary) {
+ if (targetElement == null) {
+ return;
+ }
+ var targetSource = targetElement.source;
+ if (targetSource == null || targetSource.isInSystemLibrary) {
return;
}
// prepare target declaration
@@ -80,16 +82,26 @@
if (targetDeclarationResult == null) {
return;
}
- if (targetDeclarationResult.node is! ClassOrMixinDeclaration &&
- targetDeclarationResult.node is! ExtensionDeclaration) {
+ var targetNode = targetDeclarationResult.node;
+ if (targetNode is CompilationUnitMember) {
+ if (targetDeclarationResult.node is! ClassOrMixinDeclaration &&
+ targetDeclarationResult.node is! ExtensionDeclaration) {
+ return;
+ }
+ } else {
return;
}
- CompilationUnitMember targetNode = targetDeclarationResult.node;
// prepare location
- var targetLocation = CorrectionUtils(targetDeclarationResult.resolvedUnit)
+ var targetUnit = targetDeclarationResult.resolvedUnit;
+ if (targetUnit == null) {
+ return;
+ }
+ var targetLocation = CorrectionUtils(targetUnit)
.prepareNewGetterLocation(targetNode); // Rename to "AccessorLocation"
+ if (targetLocation == null) {
+ return;
+ }
// build method source
- var targetSource = targetElement.source;
var targetFile = targetSource.fullName;
_setterName = nameNode.name;
await builder.addDartFileEdit(targetFile, (builder) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart b/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart
index d5aa8b9..9bbf4d8 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/encapsulate_field.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -43,7 +41,7 @@
}
var field = fields.first;
var nameNode = field.name;
- FieldElement fieldElement = nameNode.staticElement;
+ var fieldElement = field.declaredElement as FieldElement;
// should have a public name
var name = nameNode.name;
if (Identifier.isPrivateName(name)) {
@@ -67,10 +65,11 @@
for (var member in classDeclaration.members) {
if (member is ConstructorDeclaration) {
for (var parameter in member.parameters.parameters) {
+ var identifier = parameter.identifier;
var parameterElement = parameter.declaredElement;
- if (parameterElement is FieldFormalParameterElement &&
+ if (identifier != null &&
+ parameterElement is FieldFormalParameterElement &&
parameterElement.field == fieldElement) {
- var identifier = parameter.identifier;
builder.addSimpleReplacement(range.node(identifier), '_$name');
}
}
@@ -79,14 +78,16 @@
// Write getter and setter.
builder.addInsertion(fieldDeclaration.end, (builder) {
- String docCode;
- if (fieldDeclaration.documentationComment != null) {
- docCode = utils.getNodeText(fieldDeclaration.documentationComment);
+ String? docCode;
+ var documentationComment = fieldDeclaration.documentationComment;
+ if (documentationComment != null) {
+ docCode = utils.getNodeText(documentationComment);
}
var typeCode = '';
- if (variableList.type != null) {
- typeCode = utils.getNodeText(variableList.type) + ' ';
+ var typeAnnotation = variableList.type;
+ if (typeAnnotation != null) {
+ typeCode = utils.getNodeText(typeAnnotation) + ' ';
}
// Write getter.
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/exchange_operands.dart b/pkg/analysis_server/lib/src/services/correction/dart/exchange_operands.dart
index bb6b9de..9d1f05d 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/exchange_operands.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/exchange_operands.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -44,7 +42,7 @@
// maybe replace the operator
var operator = binaryExpression.operator;
// prepare a new operator
- String newOperator;
+ String? newOperator;
var operatorType = operator.type;
if (operatorType == TokenType.LT) {
newOperator = '>';
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/extend_class_for_mixin.dart b/pkg/analysis_server/lib/src/services/correction/dart/extend_class_for_mixin.dart
index e9eab92..10dbaad 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/extend_class_for_mixin.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/extend_class_for_mixin.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -11,7 +9,7 @@
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
class ExtendClassForMixin extends CorrectionProducer {
- String _typeName;
+ String _typeName = '';
@override
List<Object> get fixArguments => [_typeName];
@@ -21,6 +19,11 @@
@override
Future<void> compute(ChangeBuilder builder) async {
+ var diagnostic = this.diagnostic;
+ if (diagnostic == null) {
+ return;
+ }
+
var declaration = node.thisOrAncestorOfType<ClassDeclaration>();
if (declaration != null && declaration.extendsClause == null) {
// TODO(brianwilkerson) Find a way to pass in the name of the class
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_children.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_children.dart
index 01cc86a..1c0f0ca 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_children.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_children.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -21,7 +19,7 @@
NamedExpression namedExp;
{
var node = this.node;
- var parent = node?.parent;
+ var parent = node.parent;
var parent2 = parent?.parent;
if (node is SimpleIdentifier &&
parent is Label &&
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart
index 48cf327..a386080 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_convert_to_stateful_widget.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
@@ -37,14 +35,14 @@
}
// Find the build() method.
- MethodDeclaration buildMethod;
+ MethodDeclaration? buildMethod;
for (var member in widgetClass.members) {
- if (member is MethodDeclaration &&
- member.name.name == 'build' &&
- member.parameters != null &&
- member.parameters.parameters.length == 1) {
- buildMethod = member;
- break;
+ if (member is MethodDeclaration && member.name.name == 'build') {
+ var parameters = member.parameters;
+ if (parameters != null && parameters.parameters.length == 1) {
+ buildMethod = member;
+ break;
+ }
}
}
if (buildMethod == null) {
@@ -52,8 +50,9 @@
}
// Must be a StatelessWidget subclasses.
- var widgetClassElement = widgetClass.declaredElement;
- if (!flutter.isExactlyStatelessWidgetType(widgetClassElement.supertype)) {
+ var widgetClassElement = widgetClass.declaredElement!;
+ var superType = widgetClassElement.supertype;
+ if (superType == null || !flutter.isExactlyStatelessWidgetType(superType)) {
return;
}
@@ -75,20 +74,26 @@
for (var member in widgetClass.members) {
if (member is FieldDeclaration && !member.isStatic) {
for (var fieldNode in member.fields.variables) {
- FieldElement fieldElement = fieldNode.declaredElement;
+ var fieldElement = fieldNode.declaredElement as FieldElement;
if (!fieldsAssignedInConstructors.contains(fieldElement)) {
nodesToMove.add(member);
elementsToMove.add(fieldElement);
- elementsToMove.add(fieldElement.getter);
- if (fieldElement.setter != null) {
- elementsToMove.add(fieldElement.setter);
+
+ var getter = fieldElement.getter;
+ if (getter != null) {
+ elementsToMove.add(getter);
+ }
+
+ var setter = fieldElement.setter;
+ if (setter != null) {
+ elementsToMove.add(setter);
}
}
}
}
if (member is MethodDeclaration && !member.isStatic) {
nodesToMove.add(member);
- elementsToMove.add(member.declaredElement);
+ elementsToMove.add(member.declaredElement!);
}
}
@@ -128,8 +133,9 @@
var hasBuildMethod = false;
var typeParams = '';
- if (widgetClass.typeParameters != null) {
- typeParams = utils.getNodeText(widgetClass.typeParameters);
+ var typeParameters = widgetClass.typeParameters;
+ if (typeParameters != null) {
+ typeParams = utils.getNodeText(typeParameters);
}
/// Replace code between [replaceOffset] and [replaceEnd] with
@@ -206,10 +212,10 @@
// Write just param names (and not bounds, metadata and docs).
builder.write('<${widgetClass.name}');
- if (widgetClass.typeParameters != null) {
+ if (typeParameters != null) {
builder.write('<');
var first = true;
- for (var param in widgetClass.typeParameters.typeParameters) {
+ for (var param in typeParameters.typeParameters) {
if (!first) {
builder.write(', ');
first = false;
@@ -250,7 +256,10 @@
if (node.parent is FieldFormalParameter) {
var element = node.staticElement;
if (element is FieldFormalParameterElement) {
- fieldsAssignedInConstructors.add(element.field);
+ var field = element.field;
+ if (field != null) {
+ fieldsAssignedInConstructors.add(field);
+ }
}
}
if (node.parent is ConstructorFieldInitializer) {
@@ -290,7 +299,7 @@
}
var element = node.staticElement;
if (element is ExecutableElement &&
- element?.enclosingElement == widgetClassElement &&
+ element.enclosingElement == widgetClassElement &&
!elementsToMove.contains(element)) {
var offset = node.offset - linesRange.offset;
var qualifier =
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_down.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_down.dart
index 740afed..1e2fa0f 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_down.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_down.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_up.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_up.dart
index ec29164..8513af7 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_up.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_move_up.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart
index 0158fbc..9818245 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_remove_widget.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -25,7 +23,7 @@
// Prepare the list of our children.
var childrenArgument = flutter.findChildrenArgument(widgetCreation);
if (childrenArgument != null) {
- var childrenExpression = childrenArgument?.expression;
+ var childrenExpression = childrenArgument.expression;
if (childrenExpression is ListLiteral &&
childrenExpression.elements.isNotEmpty) {
await _removeChildren(
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_child.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_child.dart
index c1c46e5..c254da0 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_child.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_child.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -17,7 +15,8 @@
InstanceCreationExpression parent,
InstanceCreationExpression child) async {
// The child must have its own child.
- if (flutter.findChildArgument(child) == null) {
+ var stableChild = flutter.findChildArgument(child);
+ if (stableChild == null) {
return;
}
@@ -38,11 +37,8 @@
// Write all the arguments of the parent.
// Don't write the "child".
- Expression stableChild;
for (var argument in childArgs.arguments) {
- if (flutter.isChildArgument(argument)) {
- stableChild = argument;
- } else {
+ if (argument != stableChild) {
var text = utils.getNodeText(argument);
text = replaceSourceIndent(text, childIndent, parentIndent);
builder.write(parentIndent);
@@ -100,16 +96,16 @@
@override
Future<void> compute(ChangeBuilder builder) async {
var parent = flutter.identifyNewExpression(node);
- if (!flutter.isWidgetCreation(parent)) {
+ if (parent == null || !flutter.isWidgetCreation(parent)) {
return;
}
var childArgument = flutter.findChildArgument(parent);
- if (childArgument?.expression is! InstanceCreationExpression ||
- !flutter.isWidgetCreation(childArgument.expression)) {
+ var child = childArgument?.expression;
+ if (child is! InstanceCreationExpression ||
+ !flutter.isWidgetCreation(child)) {
return;
}
- InstanceCreationExpression child = childArgument.expression;
await swapParentAndChild(builder, parent, child);
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_parent.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_parent.dart
index a8b9f8b..701c73e 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_parent.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_swap_with_parent.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/flutter_swap_with_child.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -17,7 +15,7 @@
@override
Future<void> compute(ChangeBuilder builder) async {
var child = flutter.identifyNewExpression(node);
- if (!flutter.isWidgetCreation(child)) {
+ if (child == null || !flutter.isWidgetCreation(child)) {
return;
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_generic.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_generic.dart
index 4938af4..5fcd235 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_generic.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_generic.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_stream_builder.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_stream_builder.dart
index 50f11bb..ce2f849 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_stream_builder.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap_stream_builder.dart
@@ -2,10 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
+import 'package:analyzer/src/dart/ast/extensions.dart';
import 'package:analyzer_plugin/utilities/assist/assist.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/range_factory.dart';
@@ -20,7 +19,7 @@
if (widgetExpr == null) {
return;
}
- if (flutter.isExactWidgetTypeStreamBuilder(widgetExpr.staticType)) {
+ if (flutter.isExactWidgetTypeStreamBuilder(widgetExpr.typeOrThrow)) {
return;
}
var widgetSrc = utils.getNodeText(widgetExpr);
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/import_add_show.dart b/pkg/analysis_server/lib/src/services/correction/dart/import_add_show.dart
index 19ee675..4b923a3 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/import_add_show.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/import_add_show.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'dart:collection';
import 'package:analysis_server/src/services/correction/assist.dart';
@@ -39,7 +37,7 @@
var namespace = getImportNamespace(importElement);
// prepare names of referenced elements (from this import)
var visitor = _ReferenceFinder(namespace);
- resolvedResult.unit.accept(visitor);
+ unit.accept(visitor);
var referencedNames = visitor.referencedNames;
// ignore if unused
if (referencedNames.isEmpty) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
index 872fd34..2274c6e 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/import_library.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'dart:collection';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
@@ -56,10 +54,9 @@
} else if (_importKind == _ImportKind.forTopLevelVariable) {
var node = this.node;
if (node is Annotation) {
- Annotation annotation = node;
- var name = annotation.name;
- if (name != null && name.staticElement == null) {
- if (annotation.arguments != null) {
+ var name = node.name;
+ if (name.staticElement == null) {
+ if (node.arguments != null) {
return;
}
node = name;
@@ -75,10 +72,9 @@
} else if (_importKind == _ImportKind.forType) {
var node = this.node;
if (node is Annotation) {
- Annotation annotation = node;
- var name = annotation.name;
- if (name != null && name.staticElement == null) {
- if (annotation.arguments == null) {
+ var name = node.name;
+ if (name.staticElement == null) {
+ if (node.arguments == null) {
return;
}
node = name;
@@ -116,11 +112,8 @@
/// Return the relative uri from the passed [library] to the given [path].
/// If the [path] is not in the LibraryElement, `null` is returned.
- String _getRelativeURIFromLibrary(LibraryElement library, String path) {
- var librarySource = library?.librarySource;
- if (librarySource == null) {
- return null;
- }
+ String? _getRelativeURIFromLibrary(LibraryElement library, String path) {
+ var librarySource = library.librarySource;
var pathCtx = resourceProvider.pathContext;
var libraryDirectory = pathCtx.dirname(librarySource.fullName);
var sourceDirectory = pathCtx.dirname(path);
@@ -133,7 +126,7 @@
}
Iterable<CorrectionProducer> _importLibrary(FixKind fixKind, Uri library,
- [String relativeURI]) sync* {
+ [String? relativeURI]) sync* {
yield _ImportAbsoluteLibrary(fixKind, library);
if (relativeURI != null && relativeURI.isNotEmpty) {
yield _ImportRelativeLibrary(fixKind, relativeURI);
@@ -154,12 +147,15 @@
for (var imp in libraryElement.imports) {
// prepare element
var libraryElement = imp.importedLibrary;
+ if (libraryElement == null) {
+ continue;
+ }
var element = getExportedElement(libraryElement, name);
if (element == null) {
continue;
}
if (element is PropertyAccessorElement) {
- element = (element as PropertyAccessorElement).variable;
+ element = element.variable;
}
if (!elementKinds.contains(element.kind)) {
continue;
@@ -167,7 +163,7 @@
// may be apply prefix
var prefix = imp.prefix;
if (prefix != null) {
- yield _ImportLibraryPrefix(imp);
+ yield _ImportLibraryPrefix(libraryElement, prefix);
continue;
}
// may be update "show" directive
@@ -265,7 +261,7 @@
final Uri _library;
- String _uriText;
+ String _uriText = '';
_ImportAbsoluteLibrary(this._fixKind, this._library);
@@ -294,13 +290,14 @@
/// A correction processor that can make one of the possible change computed by
/// the [ImportLibrary] producer.
class _ImportLibraryPrefix extends CorrectionProducer {
- final ImportElement _importElement;
+ final LibraryElement _importedLibrary;
+ final PrefixElement _importPrefix;
- String _libraryName;
+ String _libraryName = '';
- String _prefixName;
+ String _prefixName = '';
- _ImportLibraryPrefix(this._importElement);
+ _ImportLibraryPrefix(this._importedLibrary, this._importPrefix);
@override
List<Object> get fixArguments => [_libraryName, _prefixName];
@@ -310,10 +307,8 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- var libraryElement = _importElement.importedLibrary;
- var prefix = _importElement.prefix;
- _libraryName = libraryElement.displayName;
- _prefixName = prefix.displayName;
+ _libraryName = _importedLibrary.displayName;
+ _prefixName = _importPrefix.displayName;
await builder.addDartFileEdit(file, (builder) {
builder.addSimpleReplacement(range.startLength(node, 0), '$_prefixName.');
});
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/inline_invocation.dart b/pkg/analysis_server/lib/src/services/correction/dart/inline_invocation.dart
index eb35756..c2e0711 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/inline_invocation.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/inline_invocation.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
@@ -32,35 +30,42 @@
@override
Future<void> compute(ChangeBuilder builder) async {
var node = this.node;
- if (node is! SimpleIdentifier || node.parent is! MethodInvocation) {
+ if (node is! SimpleIdentifier || node.name != 'add') {
return;
}
- SimpleIdentifier name = node;
- MethodInvocation invocation = node.parent;
- if (name != invocation.methodName ||
- name.name != 'add' ||
+
+ var invocation = node.parent;
+ if (invocation is! MethodInvocation) {
+ return;
+ }
+
+ if (node != invocation.methodName ||
!invocation.isCascaded ||
invocation.argumentList.arguments.length != 1) {
return;
}
- var cascade = invocation.thisOrAncestorOfType<CascadeExpression>();
+
+ var cascade = invocation.parent;
+ if (cascade is! CascadeExpression) {
+ return;
+ }
+
var sections = cascade.cascadeSections;
var target = cascade.target;
if (target is! ListLiteral || sections[0] != invocation) {
// TODO(brianwilkerson) Consider extending this to handle set literals.
return;
}
- ListLiteral list = target;
var argument = invocation.argumentList.arguments[0];
var elementText = utils.getNodeText(argument);
await builder.addDartFileEdit(file, (builder) {
- if (list.elements.isNotEmpty) {
+ if (target.elements.isNotEmpty) {
// ['a']..add(e);
- builder.addSimpleInsertion(list.elements.last.end, ', $elementText');
+ builder.addSimpleInsertion(target.elements.last.end, ', $elementText');
} else {
// []..add(e);
- builder.addSimpleInsertion(list.leftBracket.end, elementText);
+ builder.addSimpleInsertion(target.leftBracket.end, elementText);
}
builder.addDeletion(range.node(invocation));
});
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/inline_typedef.dart b/pkg/analysis_server/lib/src/services/correction/dart/inline_typedef.dart
index 6790500..6272326 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/inline_typedef.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/inline_typedef.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
@@ -14,7 +12,7 @@
import 'package:analyzer_plugin/utilities/range_factory.dart';
class InlineTypedef extends CorrectionProducer {
- String _name;
+ String _name = '';
@override
List<Object> get fixArguments => [_name];
@@ -27,13 +25,17 @@
@override
Future<void> compute(ChangeBuilder builder) async {
+ var parent = node.parent;
+ if (parent == null) {
+ return;
+ }
+
//
// Extract the information needed to build the edit.
//
- TypeAnnotation returnType;
- TypeParameterList typeParameters;
+ TypeAnnotation? returnType;
+ TypeParameterList? typeParameters;
List<FormalParameter> parameters;
- var parent = node.parent;
if (parent is FunctionTypeAlias) {
returnType = parent.returnType;
_name = parent.name.name;
@@ -44,6 +46,9 @@
return;
}
var functionType = parent.functionType;
+ if (functionType == null) {
+ return;
+ }
returnType = functionType.returnType;
_name = parent.name.name;
typeParameters = functionType.typeParameters;
@@ -53,8 +58,9 @@
}
// TODO(brianwilkerson) Handle parts.
var finder = _ReferenceFinder(_name);
- resolvedResult.unit.accept(finder);
- if (finder.count != 1) {
+ unit.accept(finder);
+ var reference = finder.reference;
+ if (reference == null || finder.count != 1) {
return;
}
//
@@ -62,7 +68,7 @@
//
await builder.addDartFileEdit(file, (builder) {
builder.addDeletion(utils.getLinesRange(range.node(parent)));
- builder.addReplacement(range.node(finder.reference), (builder) {
+ builder.addReplacement(range.node(reference), (builder) {
if (returnType != null) {
builder.write(utils.getNodeText(returnType));
builder.write(' ');
@@ -71,7 +77,7 @@
if (typeParameters != null) {
builder.write(utils.getNodeText(typeParameters));
}
- String groupEnd;
+ String? groupEnd;
builder.write('(');
for (var i = 0; i < parameters.length; i++) {
var parameter = parameters[i];
@@ -90,7 +96,7 @@
builder.write('[');
}
}
- parameter = (parameter as DefaultFormalParameter).parameter;
+ parameter = parameter.parameter;
}
if (parameter is FunctionTypedFormalParameter) {
builder.write(utils.getNodeText(parameter));
@@ -109,14 +115,18 @@
if (keyword != null && keyword.type != Keyword.VAR) {
builder.write(keyword.lexeme);
}
- if (parameter.type == null) {
+ var typeAnnotation = parameter.type;
+ if (typeAnnotation == null) {
builder.write('dynamic');
} else {
- builder.write(utils.getNodeText(parameter.type));
+ builder.write(utils.getNodeText(typeAnnotation));
}
if (parameter.isNamed) {
- builder.write(' ');
- builder.write(parameter.identifier.name);
+ var identifier = parameter.identifier;
+ if (identifier != null) {
+ builder.write(' ');
+ builder.write(identifier.name);
+ }
}
}
}
@@ -135,7 +145,7 @@
class _ReferenceFinder extends RecursiveAstVisitor {
final String typeName;
- TypeName reference;
+ TypeName? reference;
int count = 0;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/insert_semicolon.dart b/pkg/analysis_server/lib/src/services/correction/dart/insert_semicolon.dart
index 8c837c1..60ad47b 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/insert_semicolon.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/insert_semicolon.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -16,6 +14,11 @@
@override
Future<void> compute(ChangeBuilder builder) async {
+ var diagnostic = this.diagnostic;
+ if (diagnostic == null) {
+ return;
+ }
+
var message = diagnostic.problemMessage;
if (message.message.contains("';'")) {
if (_isAwaitNode()) {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/introduce_local_cast_type.dart b/pkg/analysis_server/lib/src/services/correction/dart/introduce_local_cast_type.dart
index c696b43..e3c3b29 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/introduce_local_cast_type.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/introduce_local_cast_type.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/name_suggestion.dart';
@@ -19,42 +17,25 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- var node = this.node;
- if (node is IfStatement) {
- node = (node as IfStatement).condition;
- } else if (node is WhileStatement) {
- node = (node as WhileStatement).condition;
- }
- // prepare IsExpression
- if (node is! IsExpression) {
+ var isExpression = _getCondition(node);
+ if (isExpression is! IsExpression) {
return;
}
- IsExpression isExpression = node;
var castType = isExpression.type.type;
var castTypeCode = utils.getNodeText(isExpression.type);
// prepare environment
- var indent = utils.getIndent(1);
- String prefix;
- Block targetBlock;
- {
- var statement = node.thisOrAncestorOfType<Statement>();
- if (statement is IfStatement && statement.thenStatement is Block) {
- targetBlock = statement.thenStatement;
- } else if (statement is WhileStatement && statement.body is Block) {
- targetBlock = statement.body;
- } else {
- return;
- }
- prefix = utils.getNodePrefix(statement);
+ var enclosingStatement = _enclosingStatement(isExpression);
+ if (enclosingStatement == null) {
+ return;
}
// prepare location
int offset;
String statementPrefix;
if (isExpression.notOperator == null) {
- offset = targetBlock.leftBracket.end;
- statementPrefix = indent;
+ offset = enclosingStatement.block.leftBracket.end;
+ statementPrefix = utils.getIndent(1);
} else {
- offset = targetBlock.rightBracket.end;
+ offset = enclosingStatement.block.rightBracket.end;
statementPrefix = '';
}
// prepare excluded names
@@ -69,7 +50,7 @@
if (suggestions.isNotEmpty) {
await builder.addDartFileEdit(file, (builder) {
builder.addInsertion(offset, (builder) {
- builder.write(eol + prefix + statementPrefix);
+ builder.write(eol + enclosingStatement.prefix + statementPrefix);
builder.write(castTypeCode);
builder.write(' ');
builder.addSimpleLinkedEdit('NAME', suggestions[0],
@@ -84,6 +65,54 @@
}
}
+ _EnclosingStatement? _enclosingStatement(IsExpression condition) {
+ var statement = condition.thisOrAncestorOfType<Statement>();
+ if (statement is IfStatement) {
+ var thenStatement = statement.thenStatement;
+ if (thenStatement is Block) {
+ return _EnclosingStatement(
+ utils.getNodePrefix(statement),
+ thenStatement,
+ );
+ }
+ } else if (statement is WhileStatement) {
+ var body = statement.body;
+ if (body is Block) {
+ return _EnclosingStatement(
+ utils.getNodePrefix(statement),
+ body,
+ );
+ }
+ }
+ return null;
+ }
+
/// Return an instance of this class. Used as a tear-off in `AssistProcessor`.
static IntroduceLocalCastType newInstance() => IntroduceLocalCastType();
+
+ static Expression? _getCondition(AstNode node) {
+ if (node is IfStatement) {
+ return node.condition;
+ } else if (node is WhileStatement) {
+ return node.condition;
+ }
+
+ if (node is Expression) {
+ var parent = node.parent;
+ if (parent is IfStatement && parent.condition == node) {
+ return node;
+ } else if (parent is WhileStatement && parent.condition == node) {
+ return node;
+ }
+ }
+
+ return null;
+ }
+}
+
+class _EnclosingStatement {
+ final String prefix;
+ final Block block;
+
+ _EnclosingStatement(this.prefix, this.block);
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/invert_if_statement.dart b/pkg/analysis_server/lib/src/services/correction/dart/invert_if_statement.dart
index 2fa703ac..20e22c9 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/invert_if_statement.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/invert_if_statement.dart
@@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
@@ -17,15 +15,15 @@
@override
Future<void> compute(ChangeBuilder builder) async {
- if (node is! IfStatement) {
+ var ifStatement = node;
+ if (ifStatement is! IfStatement) {
return;
}
- var ifStatement = node as IfStatement;
var condition = ifStatement.condition;
// should have both "then" and "else"
var thenStatement = ifStatement.thenStatement;
var elseStatement = ifStatement.elseStatement;
- if (thenStatement == null || elseStatement == null) {
+ if (elseStatement == null) {
return;
}
// prepare source
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_inner.dart b/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_inner.dart
index 00337c6..9b123a07 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_inner.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_inner.dart
@@ -2,11 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/util.dart';
+import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/assist/assist.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
@@ -19,25 +18,20 @@
@override
Future<void> compute(ChangeBuilder builder) async {
// climb up condition to the (supposedly) "if" statement
- var node = this.node;
- while (node is Expression) {
- node = node.parent;
- }
+ var targetIfStatement = node.enclosingIfStatement;
// prepare target "if" statement
- if (node is! IfStatement) {
+ if (targetIfStatement == null) {
return;
}
- var targetIfStatement = node as IfStatement;
if (targetIfStatement.elseStatement != null) {
return;
}
// prepare inner "if" statement
var targetThenStatement = targetIfStatement.thenStatement;
- var innerStatement = getSingleStatement(targetThenStatement);
- if (innerStatement is! IfStatement) {
+ var innerIfStatement = getSingleStatement(targetThenStatement);
+ if (innerIfStatement is! IfStatement) {
return;
}
- var innerIfStatement = innerStatement as IfStatement;
if (innerIfStatement.elseStatement != null) {
return;
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_outer.dart b/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_outer.dart
index 22761fe..5d17b46 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_outer.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/join_if_with_outer.dart
@@ -2,11 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/util.dart';
+import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/assist/assist.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
@@ -19,22 +18,18 @@
@override
Future<void> compute(ChangeBuilder builder) async {
// climb up condition to the (supposedly) "if" statement
- var node = this.node;
- while (node is Expression) {
- node = node.parent;
- }
+ var targetIfStatement = node.enclosingIfStatement;
// prepare target "if" statement
- if (node is! IfStatement) {
+ if (targetIfStatement == null) {
return;
}
- var targetIfStatement = node as IfStatement;
if (targetIfStatement.elseStatement != null) {
return;
}
// prepare outer "if" statement
var parent = targetIfStatement.parent;
if (parent is Block) {
- if ((parent as Block).statements.length != 1) {
+ if (parent.statements.length != 1) {
return;
}
parent = parent.parent;
@@ -42,7 +37,7 @@
if (parent is! IfStatement) {
return;
}
- var outerIfStatement = parent as IfStatement;
+ var outerIfStatement = parent;
if (outerIfStatement.elseStatement != null) {
return;
}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/join_variable_declaration.dart b/pkg/analysis_server/lib/src/services/correction/dart/join_variable_declaration.dart
index c7713a2..015acb8 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/join_variable_declaration.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/join_variable_declaration.dart
@@ -2,13 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-// @dart = 2.9
-
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer_plugin/utilities/assist/assist.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/range_factory.dart';
@@ -19,12 +16,13 @@
@override
Future<void> compute(ChangeBuilder builder) async {
+ var node = this.node;
if (node is SimpleIdentifier) {
var parent = node.parent;
if (parent is AssignmentExpression &&
parent.leftHandSide == node &&
parent.parent is ExpressionStatement) {
- await _joinOnAssignment(builder, parent);
+ await _joinOnAssignment(builder, node, parent);
return;
}
}
@@ -36,58 +34,57 @@
/// Join the declaration when the variable is on the left-hand side of an
/// assignment.
- Future<void> _joinOnAssignment(
- ChangeBuilder builder, AssignmentExpression assignExpression) async {
+ Future<void> _joinOnAssignment(ChangeBuilder builder, SimpleIdentifier left,
+ AssignmentExpression assignment) async {
// Check that assignment is not a compound assignment.
- if (assignExpression.operator.type != TokenType.EQ) {
+ if (assignment.operator.type != TokenType.EQ) {
return;
}
- // prepare "declaration" statement
- var element = (node as SimpleIdentifier).staticElement;
- if (element == null) {
+
+ // The assignment must be a separate statement.
+ var assignmentStatement = assignment.parent;
+ if (assignmentStatement is! ExpressionStatement) {
return;
}
- var declOffset = element.nameOffset;
- var unit = resolvedResult.unit;
- var declNode = NodeLocator(declOffset).searchWithin(unit);
- if (declNode != null &&
- declNode.parent is VariableDeclaration &&
- (declNode.parent as VariableDeclaration).name == declNode &&
- declNode.parent.parent is VariableDeclarationList &&
- declNode.parent.parent.parent is VariableDeclarationStatement) {
- } else {
+
+ // ...in a Block.
+ var block = assignmentStatement.parent;
+ if (block is! Block) {
return;
}
- var decl = declNode.parent as VariableDeclaration;
- var declStatement = decl.parent.parent as VariableDeclarationStatement;
- // may be has initializer
- if (decl.initializer != null) {
+
+ // Prepare the index in the enclosing Block.
+ var statements = block.statements;
+ var assignmentStatementIndex = statements.indexOf(assignmentStatement);
+ if (assignmentStatementIndex < 1) {
return;
}
- // check that "declaration" statement declared only one variable
- if (declStatement.variables.variables.length != 1) {
+
+ // The immediately previous statement must be a declaration.
+ var declarationStatement = statements[assignmentStatementIndex - 1];
+ if (declarationStatement is! VariableDeclarationStatement) {
return;
}
- // check that the "declaration" and "assignment" statements are
- // parts of the same Block
- var assignStatement = node.parent.parent as ExpressionStatement;
- if (assignStatement.parent is Block &&
- assignStatement.parent == declStatement.parent) {
- } else {
+
+ // Only one variable must be declared.
+ var declaredVariables = declarationStatement.variables.variables;
+ if (declaredVariables.length != 1) {
return;
}
- var block = assignStatement.parent as Block;
- // check that "declaration" and "assignment" statements are adjacent
- List<Statement> statements = block.statements;
- if (statements.indexOf(assignStatement) ==
- statements.indexOf(declStatement) + 1) {
- } else {
+
+ // The declared variable must be the one that is assigned.
+ // There must be no initializer.
+ var declaredVariable = declaredVariables.single;
+ if (declaredVariable.declaredElement != left.staticElement ||
+ declaredVariable.initializer != null) {
return;
}
await builder.addDartFileEdit(file, (builder) {
builder.addSimpleReplacement(
- range.endStart(declNode, assignExpression.operator), ' ');
+ range.endStart(declaredVariable, assignment.operator),
+ ' ',
+ );
});
}
@@ -95,50 +92,65 @@
/// assignment.
Future<void> _joinOnDeclaration(
ChangeBuilder builder, VariableDeclarationList declList) async {
- // prepare enclosing VariableDeclarationList
- var decl = declList.variables[0];
- // already initialized
- if (decl.initializer != null) {
+ // Only one variable must be declared.
+ var declaredVariables = declList.variables;
+ if (declaredVariables.length != 1) {
return;
}
- // prepare VariableDeclarationStatement in Block
- if (declList.parent is VariableDeclarationStatement &&
- declList.parent.parent is Block) {
- } else {
+
+ // The declared variable must not be initialized.
+ var declaredVariable = declaredVariables.single;
+ if (declaredVariable.initializer != null) {
return;
}
- var declStatement = declList.parent as VariableDeclarationStatement;
- var block = declStatement.parent as Block;
- List<Statement> statements = block.statements;
- // prepare assignment
- // declaration should not be last Statement
- var declIndex = statements.indexOf(declStatement);
- if (declIndex < statements.length - 1) {
- } else {
+
+ // The declaration must be a separate statement.
+ var declarationStatement = declList.parent;
+ if (declarationStatement is! VariableDeclarationStatement) {
return;
}
- // next Statement should be assignment
- var assignStatement = statements[declIndex + 1];
- if (assignStatement is ExpressionStatement) {
- } else {
+
+ // ...in a Block.
+ var block = declarationStatement.parent;
+ if (block is! Block) {
return;
}
- var expressionStatement = assignStatement as ExpressionStatement;
- // expression should be assignment
- if (expressionStatement.expression is AssignmentExpression) {
- } else {
+
+ // The declaration statement must not be the last in the block.
+ var statements = block.statements;
+ var declarationStatementIndex = statements.indexOf(declarationStatement);
+ if (declarationStatementIndex < 0 ||
+ declarationStatementIndex >= statements.length - 1) {
return;
}
- var assignExpression =
- expressionStatement.expression as AssignmentExpression;
- // check that pure assignment
- if (assignExpression.operator.type != TokenType.EQ) {
+
+ // The immediately following statement must be an assignment statement.
+ var assignmentStatement = statements[declarationStatementIndex + 1];
+ if (assignmentStatement is! ExpressionStatement) {
+ return;
+ }
+
+ // Really an assignment.
+ var assignment = assignmentStatement.expression;
+ if (assignment is! AssignmentExpression) {
+ return;
+ }
+
+ // The assignment should write into the declared variable.
+ if (assignment.writeElement != declaredVariable.declaredElement) {
+ return;
+ }
+
+ // The assignment must be pure.
+ if (assignment.operator.type != TokenType.EQ) {
return;
}
await builder.addDartFileEdit(file, (builder) {
builder.addSimpleReplacement(
- range.endStart(decl.name, assignExpression.operator), ' ');
+ range.endStart(declaredVariable.name, assignment.operator),
+ ' ',
+ );
});
}
diff --git a/pkg/analysis_server/lib/src/services/correction/util.dart b/pkg/analysis_server/lib/src/services/correction/util.dart
index 7480d17..c61a3fd 100644
--- a/pkg/analysis_server/lib/src/services/correction/util.dart
+++ b/pkg/analysis_server/lib/src/services/correction/util.dart
@@ -482,14 +482,9 @@
/// If the given [expression] is the `expression` property of a
/// [NamedExpression] then returns this [NamedExpression], otherwise returns
/// [expression].
-Expression? stepUpNamedExpression(Expression? expression) {
- if (expression != null) {
- var parent = expression.parent;
- if (parent is NamedExpression && parent.expression == expression) {
- return parent;
- }
- }
- return expression;
+Expression stepUpNamedExpression(Expression expression) {
+ var parent = expression.parent;
+ return parent is NamedExpression ? parent : expression;
}
/// Return `true` if the given [lists] are identical at the given [position].
diff --git a/pkg/analysis_server/lib/src/utilities/extensions/ast.dart b/pkg/analysis_server/lib/src/utilities/extensions/ast.dart
index 3448861..92403c0 100644
--- a/pkg/analysis_server/lib/src/utilities/extensions/ast.dart
+++ b/pkg/analysis_server/lib/src/utilities/extensions/ast.dart
@@ -62,6 +62,17 @@
bool get inWhileLoop => thisOrAncestorOfType<WhileStatement>() != null;
+ /// Return the [IfStatement] associated with `this`.
+ IfStatement? get enclosingIfStatement {
+ for (var node in withParents) {
+ if (node is IfStatement) {
+ return node;
+ } else if (node is! Expression) {
+ return null;
+ }
+ }
+ }
+
/// Return this node and all its parents.
Iterable<AstNode> get withParents sync* {
var current = this;