refactor: migrate member_ordering rule#297
Conversation
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request refactors the member_ordering lint rule to extend SolidMultiLintRule (a new base class for rules with multiple diagnostic codes), splits several model classes into separate files, and replaces the old test file with a comprehensive unit test suite. The review feedback correctly identifies two critical compilation errors in MemberOrderingVisitor: first, the use of the non-existent BlockClassBody class, and second, attempting to access a .name property on ConstructorDeclaration.typeName (which is a Token and should use .lexeme instead).
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
|
||
| @override | ||
| List<MemberInfo> visitClassDeclaration(ClassDeclaration node) { | ||
| void visitClassDeclaration(ClassDeclaration node) { |
There was a problem hiding this comment.
I think some of the blocks in this method should be extracted:
void _visitClassDeclaration(ClassDeclaration node) {
final type = node.extendsClause?.superclass.type;
final isFlutterWidget =
isWidgetOrSubclass(type) || isWidgetStateOrSubclass(type);
final body = node.body;
if (body is BlockClassBody) {
for (final member in body.members) {
if (member is FieldDeclaration) {
_visitFieldDeclaration(member, isFlutterWidget);
} else if (member is ConstructorDeclaration) {
_visitConstructorDeclaration(member, isFlutterWidget);
} else if (member is MethodDeclaration) {
_visitMethodDeclaration(member, isFlutterWidget);
}
}
}
}
void _reportWrongOrder() {
final wrongOrderMembers = _membersInfo.where(
(info) => info.memberOrder.isWrong,
);
for (final memberInfo in wrongOrderMembers) {
final memberGroup = memberInfo.memberOrder.memberGroup;
final previousMemberGroup = memberInfo.memberOrder.previousMemberGroup;
_rule.reportAtNode(
memberInfo.classMember,
diagnosticCode: MemberOrderingRule.wrongOrderCode,
arguments: [
memberGroup.toString(),
previousMemberGroup?.toString() ?? '',
],
);
}
}
void _reportAlphabeticalOrder() {
final alphabeticallyWrongOrderMembers = _membersInfo.where(
(info) => info.memberOrder.isAlphabeticallyWrong,
);
for (final memberInfo in alphabeticallyWrongOrderMembers) {
final names = memberInfo.memberOrder.memberNames;
_rule.reportAtNode(
memberInfo.classMember,
diagnosticCode: MemberOrderingRule.alphabeticalOrderCode,
arguments: [
names.currentName,
names.previousName ?? '',
],
);
}
}
void _reportAlphabeticalTypeOrder() {
final alphabeticallyByTypeWrongOrderMembers = _membersInfo.where(
(info) => info.memberOrder.isByTypeWrong,
);
for (final memberInfo in alphabeticallyByTypeWrongOrderMembers) {
final names = memberInfo.memberOrder.memberNames;
_rule.reportAtNode(
memberInfo.classMember,
diagnosticCode: MemberOrderingRule.alphabeticalByTypeOrderCode,
arguments: [
names.currentName,
names.previousName ?? '',
],
);
}
}
void _reportMembers(bool Function(MemberInfo) filter, DiagnosticCode code) {
final filtered = _membersInfo.where(filter);
for (final memberInfo in filtered) {
final names = memberInfo.memberOrder.memberNames;
_rule.reportAtNode(
memberInfo.classMember,
diagnosticCode: code,
arguments: [
names.currentName,
names.previousName ?? '',
],
);
}
}
// Similar repetition in _visitX
I feel like we should also extract the bool _isXGroup methods into an extension on MemberGroup and move it to a separate file
There was a problem hiding this comment.
Implemented the refactoring!
…implify visitor reporting methods
| _rule.reportAtNode( | ||
| memberInfo.classMember, | ||
| diagnosticCode: code, | ||
| arguments: getArguments(memberInfo), |
There was a problem hiding this comment.
Looks like all the callers only use .memberOrder anyway
| arguments: getArguments(memberInfo), | |
| arguments: getArguments(memberInfo.memberOrder), |
| required ClassMember classMember, | ||
| required MemberGroup parsedGroup, | ||
| required bool isFlutterWidget, | ||
| required String name, |
There was a problem hiding this comment.
| required String name, | |
| required Token? token, |
and then do token?.name.lexeme ?? '' inside to make the calls shorter
There was a problem hiding this comment.
I played around refactoring it and I was able to get rid of this file completely:
lib/src/utils/implies.dart:
/// Logical implication operation.
extension BoolImplies on bool {
/// Logical implication operation.
///
/// True implies that [other] is also true.
// ignore: avoid_positional_boolean_parameters
bool implies(bool other) => objectImplies(this, other, false);
}
/// Sugar syntax helper to write extensions analogus to bool implies.
///
/// A truthy (!= [falsy]) value of [a] implies an equal value of [b].
bool objectImplies<T>(T a, T b, T falsy) => a == falsy || a == b;
/// A class that supports logical implication of it's objects.
abstract class Implicable {
/// Logical implication operation.
///
/// A truthy value of this object implies an equal value of [other].
bool implies(Implicable other);
}
Add a new method to abstract class MemberGroup:
abstract class MemberGroup implements Implicable {
...
@override
bool implies(covariant MemberGroup other) =>
modifier.implies(other.modifier) && annotation.implies(other.annotation);
}and same for subclasses and relevant enums:
@override
bool implies(covariant ConstructorMemberGroup other) =>
isFactory.implies(other.isFactory) && isNamed.implies(other.isNamed); @override
bool implies(covariant FieldMemberGroup other) =>
isLate.implies(other.isLate) &&
isStatic.implies(other.isStatic) &&
isNullable.implies(other.isNullable) &&
keyword.implies(other.keyword); @override
bool implies(covariant Modifier other) =>
objectImplies(this, other, Modifier.unset); @override
bool implies(covariant Annotation other) =>
objectImplies(this, other, Annotation.unset); @override
bool implies(covariant FieldKeyword other) =>
objectImplies(this, other, FieldKeyword.unset); @override
bool implies(MemberGroup other) =>
super.implies(other) &&
other is MethodMemberGroup &&
isStatic.implies(other.isStatic) &&
isNullable.implies(other.isNullable) &&
name.implies(other.name);
}
extension on String? {
bool implies(String? other) => objectImplies(this, other, null);
} @override
bool implies(covariant FieldMemberGroup other) =>
isLate.implies(other.isLate) &&
isStatic.implies(other.isStatic) &&
isNullable.implies(other.isNullable) &&
keyword.implies(other.keyword);One thing I'm not entirely sure about is covariant - maybe we should just check is in the method instead.
WDYT?
There was a problem hiding this comment.
I implemented the implies pattern, but dropped covariant to maintain compile-time type safety.
I also decided to drop the Implicable interface entirely. Since we cannot implement interfaces for primitive types like bool and String?, dropping it allowed me to keep a uniform, consistent approach across the codebase using just extensions and method overrides.
In case you still want to add the Implicable class, we can use a generic Implicable<T> to get rid of covariant.
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
There was a problem hiding this comment.
nvm I think that won't work because for simple case we need more then just ==unset
There was a problem hiding this comment.
I think that's a great idea!
There was a problem hiding this comment.
Let's leave that part as-is
…s and clean up formatting
There was a problem hiding this comment.
We can split it into 3 classes
// MIT License
//
// Copyright (c) 2020-2021 Dart Code Checker team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import 'package:analyzer/dart/ast/ast.dart' hide Annotation;
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:solid_lints/src/lints/member_ordering/member_ordering_rule.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_ordering_parameters.dart';
import 'package:solid_lints/src/lints/member_ordering/visitors/declaration_ordering_visitor.dart';
import 'package:solid_lints/src/lints/member_ordering/visitors/member_ordering_reporter.dart';
import 'package:solid_lints/src/utils/types_utils.dart';
/// AST Visitor which finds all class members and checks if they are
/// in order provided from rule config or default config
class MemberOrderingVisitor extends SimpleAstVisitor<void> {
final MemberOrderingRule _rule;
final MemberOrderingParameters _parameters;
/// Creates instance of [MemberOrderingVisitor]
MemberOrderingVisitor(this._rule, this._parameters);
@override
void visitClassDeclaration(ClassDeclaration node) {
super.visitClassDeclaration(node);
final body = node.body;
if (body is! BlockClassBody) return;
final type = node.extendsClause?.superclass.type;
final declarationVisitor = DeclarationOrderingVisitor(
parameters: _parameters,
isFlutterWidget:
isWidgetOrSubclass(type) || isWidgetStateOrSubclass(type),
);
body.members.forEach(declarationVisitor.visit);
MemberOrderingReporter(
membersInfo: declarationVisitor.membersInfo,
rule: _rule,
).report(
declarationVisitor.membersInfo,
alphabetize: _parameters.alphabetize,
alphabetizeByType: _parameters.alphabetizeByType,
);
}
}// MIT License
//
// Copyright (c) 2020-2021 Dart Code Checker team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import 'package:analyzer/error/error.dart';
import 'package:solid_lints/src/lints/member_ordering/member_ordering_rule.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_info.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_order.dart';
class MemberOrderingReporter {
final MemberOrderingRule _rule;
final List<MemberInfo> _membersInfo;
const MemberOrderingReporter({
required List<MemberInfo> membersInfo,
required MemberOrderingRule rule,
}) : _membersInfo = membersInfo,
_rule = rule;
void report(
List<MemberInfo> membersInfo, {
required bool alphabetize,
required bool alphabetizeByType,
}) {
_reportWrongOrder();
if (alphabetize) {
_reportAlphabeticalOrder();
} else if (alphabetizeByType) {
_reportAlphabeticalTypeOrder();
}
}
void _reportWrongOrder() => _reportMembers(
(order) => order.isWrong,
MemberOrderingRule.wrongOrderCode,
(order) => [
order.memberGroup.toString(),
order.previousMemberGroup?.toString() ?? '',
],
);
void _reportAlphabeticalOrder() => _reportMembers(
(order) => order.isAlphabeticallyWrong,
MemberOrderingRule.alphabeticalOrderCode,
(order) => [
order.memberNames.currentName,
order.memberNames.previousName ?? '',
],
);
void _reportAlphabeticalTypeOrder() => _reportMembers(
(order) => order.isByTypeWrong,
MemberOrderingRule.alphabeticalByTypeOrderCode,
(order) => [
order.memberNames.currentTypeName,
order.memberNames.previousTypeName ?? '',
],
);
void _reportMembers(
bool Function(MemberOrder) filter,
LintCode code,
List<String> Function(MemberOrder) getArguments,
) {
final filtered = _membersInfo.where((info) => filter(info.memberOrder));
for (final memberInfo in filtered) {
_rule.reportAtNode(
memberInfo.classMember,
diagnosticCode: code,
arguments: getArguments(memberInfo.memberOrder),
);
}
}
}// MIT License
//
// Copyright (c) 2020-2021 Dart Code Checker team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:collection/collection.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_group/constructor_member_group.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_group/field_member_group.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_group/get_set_member_group.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_group/member_group.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_group/method_member_group.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_info.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_names.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_order.dart';
import 'package:solid_lints/src/lints/member_ordering/models/member_ordering_parameters.dart';
class DeclarationOrderingVisitor {
final bool _isFlutterWidget;
final MemberOrderingParameters _parameters;
final membersInfo = <MemberInfo>[];
DeclarationOrderingVisitor({
required MemberOrderingParameters parameters,
required bool isFlutterWidget,
}) : _parameters = parameters,
_isFlutterWidget = isFlutterWidget;
void visit(ClassMember member) => switch (member) {
FieldDeclaration() => _visitFieldDeclaration(member),
ConstructorDeclaration() => _visitConstructorDeclaration(member),
MethodDeclaration() => _visitMethodDeclaration(member),
_ => (),
};
void _visitFieldDeclaration(FieldDeclaration declaration) => _addMemberInfo(
classMember: declaration,
parsedGroup: FieldMemberGroup.parse(declaration),
token: declaration.fields.variables.first.name,
type: declaration.fields.type?.type?.getDisplayString() ?? '_',
);
void _visitConstructorDeclaration(ConstructorDeclaration declaration) =>
_addMemberInfo(
classMember: declaration,
parsedGroup: ConstructorMemberGroup.parse(declaration),
token: declaration.name,
type: declaration.typeName?.name ?? '',
);
void _visitMethodDeclaration(MethodDeclaration declaration) {
final group = (declaration.isGetter || declaration.isSetter)
? GetSetMemberGroup.parse(declaration)
: MethodMemberGroup.parse(declaration);
_addMemberInfo(
classMember: declaration,
parsedGroup: group,
token: declaration.name,
type: declaration.returnType?.type?.getDisplayString() ?? '_',
);
}
void _addMemberInfo({
required ClassMember classMember,
required MemberGroup parsedGroup,
required Token? token,
required String type,
}) {
final closestGroup = _getClosestGroup(parsedGroup);
if (closestGroup == null) return;
membersInfo.add(
MemberInfo(
classMember: classMember,
memberOrder: _getOrder(
closestGroup,
token?.lexeme ?? '',
type,
),
),
);
}
MemberGroup? _getClosestGroup(MemberGroup parsedGroup) {
final closestGroups =
(_isFlutterWidget
? _parameters.widgetsGroupsOrder
: _parameters.groupsOrder)
.where((group) => group.implies(parsedGroup))
.sorted(
(a, b) => b.getSortingCoefficient() - a.getSortingCoefficient(),
);
return closestGroups.firstOrNull;
}
MemberOrder _getOrder(
MemberGroup memberGroup,
String memberName,
String typeName,
) {
if (membersInfo.isEmpty) {
return MemberOrder(
memberNames: MemberNames(
currentName: memberName,
currentTypeName: typeName,
),
isAlphabeticallyWrong: false,
isByTypeWrong: false,
memberGroup: memberGroup,
isWrong: false,
);
}
final lastMemberOrder = membersInfo.last.memberOrder;
final hasSameGroup = lastMemberOrder.memberGroup == memberGroup;
final previousMemberGroup =
hasSameGroup && lastMemberOrder.previousMemberGroup != null
? lastMemberOrder.previousMemberGroup
: lastMemberOrder.memberGroup;
final memberNames = MemberNames(
currentName: memberName,
previousName: lastMemberOrder.memberNames.currentName,
currentTypeName: typeName,
previousTypeName: lastMemberOrder.memberNames.currentTypeName,
);
return MemberOrder(
memberNames: memberNames,
isAlphabeticallyWrong:
hasSameGroup &&
memberNames.currentName.compareTo(memberNames.previousName!) < 0,
isByTypeWrong:
hasSameGroup &&
memberNames.currentTypeName.toLowerCase().compareTo(
memberNames.previousTypeName!.toLowerCase(),
) <
0,
memberGroup: memberGroup,
previousMemberGroup: previousMemberGroup,
isWrong:
(hasSameGroup && lastMemberOrder.isWrong) ||
_isCurrentGroupBefore(
lastMemberOrder.memberGroup,
memberGroup,
),
);
}
bool _isCurrentGroupBefore(
MemberGroup lastMemberGroup,
MemberGroup memberGroup,
) {
final group = _isFlutterWidget
? _parameters.widgetsGroupsOrder
: _parameters.groupsOrder;
return group.indexOf(lastMemberGroup) > group.indexOf(memberGroup);
}
}
Closes #252