Skip to content

Commit

Permalink
[element model] cleanup extensions (partial)
Browse files Browse the repository at this point in the history
Bug: #59548
Change-Id: I46d1bc371ca05bac98c112eb0122c5a71af914ef
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/399280
Reviewed-by: Konstantin Shcheglov <[email protected]>
Commit-Queue: Phil Quitslund <[email protected]>
  • Loading branch information
pq authored and Commit Queue committed Dec 5, 2024
1 parent cf1f51e commit 935a985
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 60 deletions.
60 changes: 24 additions & 36 deletions pkg/linter/lib/src/extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ extension AstNodeExtension on AstNode {
MethodDeclaration() => self.augmentKeyword != null,
MixinDeclaration() => self.augmentKeyword != null,
TopLevelVariableDeclaration() => self.augmentKeyword != null,
VariableDeclaration(declaredElement: var element) =>
element is PropertyInducingElement && element.isAugmentation,
VariableDeclaration(declaredFragment: var fragment?) =>
fragment is PropertyInducingFragment && fragment.isAugmentation,
_ => false
};
}
Expand All @@ -64,7 +64,7 @@ extension AstNodeExtension on AstNode {
var node = this;
if (node.isInternal) return true;
if (node is ClassDeclaration) {
var classElement = node.declaredElement;
var classElement = node.declaredFragment?.element;
if (classElement != null) {
if (classElement.isSealed) return true;
if (classElement.isAbstract) {
Expand All @@ -80,27 +80,15 @@ extension AstNodeExtension on AstNode {
var parent = thisOrAncestorOfType<CompilationUnitMember>();
if (parent == null) return false;

var element = parent.declaredElement;
return element != null && element.hasInternal;
return switch (parent.declaredFragment?.element) {
Annotatable(:var metadata2) => metadata2.hasInternal,
_ => false,
};
}
}

extension AstNodeNullableExtension on AstNode? {
Element? get canonicalElement {
var self = this;
if (self is Expression) {
var node = self.unParenthesized;
if (node is Identifier) {
return node.staticElement?.canonicalElement;
} else if (node is PropertyAccess) {
return node.propertyName.staticElement?.canonicalElement;
}
}
return null;
}

Element2? get canonicalElement2 {
// TODO(pq): can this be replaced w/ a use of an `ElementLocator2`?
Element2? get canonicalElement {
var self = this;
if (self is Expression) {
var node = self.unParenthesized;
Expand Down Expand Up @@ -276,7 +264,7 @@ extension DartTypeExtension on DartType? {
bool extendsClass(String? className, String library) {
var self = this;
if (self is InterfaceType) {
return _extendsClass(self, <InterfaceElement>{}, className, library);
return _extendsClass(self, <InterfaceElement2>{}, className, library);
}
return false;
}
Expand All @@ -291,8 +279,8 @@ extension DartTypeExtension on DartType? {
}
if (typeToCheck is InterfaceType) {
return isAnyInterface(typeToCheck) ||
!typeToCheck.element.isSynthetic &&
typeToCheck.element.allSupertypes.any(isAnyInterface);
!typeToCheck.element3.isSynthetic &&
typeToCheck.element3.allSupertypes.any(isAnyInterface);
} else {
return false;
}
Expand All @@ -304,7 +292,7 @@ extension DartTypeExtension on DartType? {
return false;
}
bool predicate(InterfaceType i) => i.isSameAs(interface, library);
var element = self.element;
var element = self.element3;
return predicate(self) ||
!element.isSynthetic && element.allSupertypes.any(predicate);
}
Expand All @@ -314,17 +302,17 @@ extension DartTypeExtension on DartType? {
bool isSameAs(String? interface, String? library) {
var self = this;
return self is InterfaceType &&
self.element.name == interface &&
self.element.library.name == library;
self.element3.name3 == interface &&
self.element3.library2.name3 == library;
}

static bool _extendsClass(
InterfaceType? type,
Set<InterfaceElement> seenElements,
Set<InterfaceElement2> seenElements,
String? className,
String? library) =>
type != null &&
seenElements.add(type.element) &&
seenElements.add(type.element3) &&
(type.isSameAs(className, library) ||
_extendsClass(type.superclass, seenElements, className, library));
}
Expand Down Expand Up @@ -399,15 +387,15 @@ extension ExpressionExtension on Expression? {
case ArgumentList():
// Allow `function(LinkedHashSet())` for `function(LinkedHashSet mySet)`
// and `function(LinkedHashMap())` for `function(LinkedHashMap myMap)`.
return self.staticParameterElement?.type ?? InvalidTypeImpl.instance;
return self.correspondingParameter?.type ?? InvalidTypeImpl.instance;
case AssignmentExpression():
// Allow `x = LinkedHashMap()`.
return ancestor.staticType;
case ConditionalExpression():
return ancestor.staticType;
case ConstructorFieldInitializer():
var fieldElement = ancestor.fieldName.staticElement;
return (fieldElement is VariableElement) ? fieldElement.type : null;
var fieldElement = ancestor.fieldName.element;
return (fieldElement is VariableElement2) ? fieldElement.type : null;
case ExpressionFunctionBody(parent: var function)
when function is FunctionExpression:
// Allow `<int, LinkedHashSet>{}.putIfAbsent(3, () => LinkedHashSet())`
Expand All @@ -426,7 +414,7 @@ extension ExpressionExtension on Expression? {
return function.returnType?.type;
case NamedExpression():
// Allow `void f({required LinkedHashSet<Foo> s})`.
return ancestor.staticParameterElement?.type ??
return ancestor.correspondingParameter?.type ??
InvalidTypeImpl.instance;
case ReturnStatement():
return ancestor.thisOrAncestorOfType<FunctionBody>().expectedReturnType;
Expand Down Expand Up @@ -460,7 +448,7 @@ extension FunctionBodyExtension on FunctionBody? {
if (parent is FunctionExpression) {
var grandparent = parent.parent;
if (grandparent is FunctionDeclaration) {
var returnType = grandparent.declaredElement?.returnType;
var returnType = grandparent.declaredFragment?.element.returnType;
return self._expectedReturnableOrYieldableType(returnType);
}
var functionType = parent.approximateContextType;
Expand All @@ -469,7 +457,7 @@ extension FunctionBodyExtension on FunctionBody? {
return self._expectedReturnableOrYieldableType(returnType);
}
if (parent is MethodDeclaration) {
var returnType = parent.declaredElement?.returnType;
var returnType = parent.declaredFragment?.element.returnType;
return self._expectedReturnableOrYieldableType(returnType);
}
return null;
Expand Down Expand Up @@ -546,9 +534,9 @@ extension InterfaceTypeExtension on InterfaceType {
Iterable<InterfaceType> get implementedInterfaces {
void searchSupertypes(
InterfaceType? type,
Set<InterfaceElement> alreadyVisited,
Set<InterfaceElement2> alreadyVisited,
List<InterfaceType> interfaceTypes) {
if (type == null || !alreadyVisited.add(type.element)) {
if (type == null || !alreadyVisited.add(type.element3)) {
return;
}
interfaceTypes.add(type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ bool _isComparingParameterWithNull(
_isParameter(node.leftOperand, parameter)));

bool _isParameter(Expression expression, Element2? parameter) =>
expression.canonicalElement2 == parameter;
expression.canonicalElement == parameter;

bool _isParameterWithQuestionQuestion(
BinaryExpression node, Element2? parameter) =>
Expand Down Expand Up @@ -69,7 +69,7 @@ class _BodyVisitor extends RecursiveAstVisitor<void> {
@override
visitMethodInvocation(MethodInvocation node) {
if (node.operator?.type == TokenType.QUESTION_PERIOD &&
node.target.canonicalElement2 == parameter) {
node.target.canonicalElement == parameter) {
rule.reportLint(node);
}
super.visitMethodInvocation(node);
Expand All @@ -78,7 +78,7 @@ class _BodyVisitor extends RecursiveAstVisitor<void> {
@override
visitPropertyAccess(PropertyAccess node) {
if (node.operator.type == TokenType.QUESTION_PERIOD &&
node.target.canonicalElement2 == parameter) {
node.target.canonicalElement == parameter) {
rule.reportLint(node);
}
super.visitPropertyAccess(node);
Expand Down
16 changes: 8 additions & 8 deletions pkg/linter/lib/src/rules/cascade_invocations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Element2? _getElementFromVariableDeclarationStatement(
ExecutableElement2? _getExecutableElementFromMethodInvocation(
MethodInvocation node) {
if (_isInvokedWithoutNullAwareOperator(node.operator)) {
var executableElement = node.methodName.canonicalElement2;
var executableElement = node.methodName.canonicalElement;
if (executableElement is ExecutableElement2) {
return executableElement;
}
Expand All @@ -44,20 +44,20 @@ ExecutableElement2? _getExecutableElementFromMethodInvocation(
Element2? _getPrefixElementFromExpression(Expression rawExpression) {
var expression = rawExpression.unParenthesized;
if (expression is PrefixedIdentifier) {
return expression.prefix.canonicalElement2;
return expression.prefix.canonicalElement;
} else if (expression is PropertyAccess &&
_isInvokedWithoutNullAwareOperator(expression.operator) &&
expression.target is SimpleIdentifier) {
return expression.target.canonicalElement2;
return expression.target.canonicalElement;
}
return null;
}

Element2? _getTargetElementFromCascadeExpression(CascadeExpression node) =>
node.target.canonicalElement2;
node.target.canonicalElement;

Element2? _getTargetElementFromMethodInvocation(MethodInvocation node) =>
node.target.canonicalElement2;
node.target.canonicalElement;

bool _isInvokedWithoutNullAwareOperator(Token? token) =>
token?.type == TokenType.PERIOD;
Expand Down Expand Up @@ -201,12 +201,12 @@ class _CascadableExpression {

factory _CascadableExpression._fromPrefixedIdentifier(
PrefixedIdentifier node) =>
_CascadableExpression._internal(node.prefix.canonicalElement2, [],
_CascadableExpression._internal(node.prefix.canonicalElement, [],
canJoin: true, canReceive: true, canBeCascaded: true);

factory _CascadableExpression._fromPropertyAccess(PropertyAccess node) {
var targetIsSimple = node.target is SimpleIdentifier;
return _CascadableExpression._internal(node.target.canonicalElement2, [],
return _CascadableExpression._internal(node.target.canonicalElement, [],
canJoin: targetIsSimple,
canReceive: targetIsSimple,
canBeCascaded: true);
Expand Down Expand Up @@ -248,7 +248,7 @@ class _NodeVisitor extends UnifyingAstVisitor<void> {
_NodeVisitor(this.expressionBox);

bool isCriticalNode(AstNode node) =>
node.canonicalElement2 == expressionBox.element;
node.canonicalElement == expressionBox.element;

bool isOrHasCriticalNode(AstNode node) {
node.accept(this);
Expand Down
2 changes: 1 addition & 1 deletion pkg/linter/lib/src/rules/prefer_final_fields.dart
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ extension on VariableElement2 {
/// Whether `this` is initialized in [initializer].
bool isSetInInitializer(ConstructorInitializer initializer) =>
initializer is ConstructorFieldInitializer &&
initializer.fieldName.canonicalElement2 == this;
initializer.fieldName.canonicalElement == this;

/// Whether `this` is initialized with [parameter].
bool isSetInParameter(FormalParameter parameter) {
Expand Down
8 changes: 4 additions & 4 deletions pkg/linter/lib/src/rules/prefer_foreach.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class _PreferForEachVisitor extends SimpleAstVisitor<void> {
@override
void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
var arguments = node.argumentList.arguments;
if (arguments.length == 1 && arguments.first.canonicalElement2 == element) {
if (arguments.length == 1 && arguments.first.canonicalElement == element) {
rule.reportLint(forEachStatement);
}
}
Expand All @@ -74,7 +74,7 @@ class _PreferForEachVisitor extends SimpleAstVisitor<void> {
var arguments = node.argumentList.arguments;
var target = node.target;
if (arguments.length == 1 &&
arguments.first.canonicalElement2 == element &&
arguments.first.canonicalElement == element &&
(target == null || !_ReferenceFinder(element).references(target))) {
rule.reportLint(forEachStatement);
}
Expand All @@ -92,7 +92,7 @@ class _ReferenceFinder extends UnifyingAstVisitor<void> {
_ReferenceFinder(this.element);

bool references(Expression target) {
if (target.canonicalElement2 == element) return true;
if (target.canonicalElement == element) return true;

target.accept(this);
return found;
Expand All @@ -102,7 +102,7 @@ class _ReferenceFinder extends UnifyingAstVisitor<void> {
visitNode(AstNode node) {
if (found) return;

found = node.canonicalElement2 == element;
found = node.canonicalElement == element;
if (!found) {
super.visitNode(node);
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/linter/lib/src/rules/prefer_initializing_formals.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Iterable<FormalParameterElement?> _getParameters(ConstructorDeclaration node) =>
node.parameters.parameters.map((e) => e.declaredFragment?.element);

Element2? _getRightElement(AssignmentExpression assignment) =>
assignment.rightHandSide.canonicalElement2;
assignment.rightHandSide.canonicalElement;

class PreferInitializingFormals extends LintRule {
PreferInitializingFormals()
Expand Down
4 changes: 2 additions & 2 deletions pkg/linter/lib/src/rules/unnecessary_overrides.dart
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ class _UnnecessaryOperatorOverrideVisitor
parameters != null &&
parameters.length == 1 &&
parameters.first.declaredFragment?.element ==
node.rightOperand.canonicalElement2) {
node.rightOperand.canonicalElement) {
var leftPart = node.leftOperand.unParenthesized;
if (leftPart is SuperExpression) {
visitSuperExpression(leftPart);
Expand Down Expand Up @@ -310,7 +310,7 @@ class _UnnecessarySetterOverrideVisitor
if (parameters != null &&
parameters.length == 1 &&
parameters.first.declaredFragment?.element ==
node.rightHandSide.canonicalElement2) {
node.rightHandSide.canonicalElement) {
var leftPart = node.leftHandSide.unParenthesized;
if (leftPart is PropertyAccess) {
if (node.writeElement2?.name3 == _inheritedMethod.name3) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/linter/lib/src/rules/use_rethrow_when_possible.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class _Visitor extends SimpleAstVisitor<void> {
void visitThrowExpression(ThrowExpression node) {
if (node.parent is! ExpressionStatement) return;

var element = node.expression.canonicalElement2;
var element = node.expression.canonicalElement;
if (element != null) {
var catchClause = node.thisOrAncestorOfType<CatchClause>();
var exceptionParameter =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class _Visitor extends SimpleAstVisitor<void> {
if (expression is AssignmentExpression &&
expression.operator.type == TokenType.EQ) {
var leftOperand = expression.writeElement2?.canonicalElement2;
var rightOperand = expression.rightHandSide.canonicalElement2;
var rightOperand = expression.rightHandSide.canonicalElement;
var parameterElement =
node.declaredFragment?.element.formalParameters.first;
if (rightOperand == parameterElement && leftOperand is FieldElement2) {
Expand Down
6 changes: 3 additions & 3 deletions pkg/linter/lib/src/util/dart_type_utilities.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ bool argumentsMatchParameters(
}
for (var argument in arguments) {
if (argument is NamedExpression) {
var element = argument.expression.canonicalElement2;
var element = argument.expression.canonicalElement;
if (element == null) {
return false;
}
namedArguments[argument.name.label.name] = element;
} else {
var element = argument.canonicalElement2;
var element = argument.canonicalElement;
if (element == null) {
return false;
}
Expand Down Expand Up @@ -69,7 +69,7 @@ bool canonicalElementsAreEqual(Element2? element1, Element2? element2) =>

/// Returns whether the canonical elements from two nodes are equal.
///
/// As in, [AstNodeNullableExtension.canonicalElement2], the two nodes must be
/// As in, [AstNodeNullableExtension.canonicalElement], the two nodes must be
/// [Expression]s in order to be compared (otherwise `false` is returned).
///
/// The two nodes must both be a [SimpleIdentifier], [PrefixedIdentifier], or
Expand Down

0 comments on commit 935a985

Please sign in to comment.