Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/leancode_lint/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,59 @@ None.

</details>

<details>
<summary>`bloc_related_class_naming`</summary>

### `bloc_related_class_naming`

**DO** follow the naming convention for Bloc/Cubit related classes.

For `ExampleBloc`:
- Event class: `ExampleEvent`
- State class: `ExampleState`
- Presentation Event class: `ExamplePresentationEvent`

For `ExampleCubit`:
- State class: `ExampleState`
- Presentation Event class: `ExamplePresentationEvent`

> [!NOTE]
> This lint only checks classes defined in the same library (including parts) as the Bloc/Cubit.
> Presentation events are only checked if the `bloc_presentation` package is used.

**BAD:**

```dart
class MyBloc extends Bloc<WrongEvent, WrongState> {}
```

**GOOD:**

```dart
class MyBloc extends Bloc<MyEvent, MyState> {}
```

#### Configuration

Configured via `LeanCodeLintConfig.blocRelatedClassNaming`:

```dart
import 'package:leancode_lint/plugin.dart';

final plugin = LeanCodeLintPlugin(
name: 'my_lints',
config: LeanCodeLintConfig(
blocRelatedClassNaming: BlocRelatedClassNamingConfig(
stateSuffix: 'State',
eventSuffix: 'Event',
presentationEventSuffix: 'PresentationEvent',
),
),
);
```

</details>

<details>
<summary><code>catch_parameter_names</code></summary>

Expand Down
25 changes: 25 additions & 0 deletions packages/leancode_lint/lib/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ final class LeanCodeLintConfig {
this.applicationPrefix,
this.designSystemItemReplacements = const {},
this.catchParameterNames = const .new(),
this.blocRelatedClassNaming = const .new(),
});

/// Used by some rules (e.g. `prefix_widgets_returning_slivers`) to match
Expand All @@ -19,6 +20,30 @@ final class LeanCodeLintConfig {

/// Configuration for the `catch_parameter_names` rule.
final CatchParameterNamesConfig catchParameterNames;

/// Configuration for the `bloc_related_class_naming` rule.
final BlocRelatedClassNamingConfig blocRelatedClassNaming;
}

/// Configuration for the `bloc_related_class_naming` rule.
///
/// Each suffix is appended to the BLoC/Cubit subject name (the part before
/// `Bloc` or `Cubit`) to form the expected class name.
///
/// For example, for `FooBloc` the default expected names are:
/// - state → `FooState`
/// - event → `FooEvent`
/// - presentation event → `FooPresentationEvent`
class BlocRelatedClassNamingConfig {
const BlocRelatedClassNamingConfig({
this.stateSuffix = 'State',
this.eventSuffix = 'Event',
this.presentationEventSuffix = 'PresentationEvent',
});

final String stateSuffix;
final String eventSuffix;
final String presentationEventSuffix;
}

class CatchParameterNamesConfig {
Expand Down
14 changes: 12 additions & 2 deletions packages/leancode_lint/lib/plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'package:leancode_lint/src/assists/convert_record_into_nominal_type.dart'
import 'package:leancode_lint/src/lints/add_cubit_suffix_for_cubits.dart';
import 'package:leancode_lint/src/lints/avoid_conditional_hooks.dart';
import 'package:leancode_lint/src/lints/avoid_single_child_in_multi_child_widget.dart';
import 'package:leancode_lint/src/lints/bloc_related_class_naming.dart';
import 'package:leancode_lint/src/lints/catch_parameter_names.dart';
import 'package:leancode_lint/src/lints/constructor_parameters_and_fields_should_have_the_same_order.dart';
import 'package:leancode_lint/src/lints/hook_widget_does_not_use_hooks.dart';
Expand Down Expand Up @@ -40,13 +41,22 @@ final class LeanCodeLintPlugin extends Plugin {
).forEach(registry.registerWarningRule);
registry
..registerWarningRule(StartCommentsWithSpace())
..registerWarningRule(PrefixWidgetsReturningSlivers(config: config))
..registerWarningRule(
PrefixWidgetsReturningSlivers(
applicationPrefix: config.applicationPrefix,
),
)
..registerFixForRule(
StartCommentsWithSpace.code,
AddStartingSpaceToComment.new,
)
..registerWarningRule(AddCubitSuffixForYourCubits())
..registerWarningRule(CatchParameterNames(config: config))
..registerWarningRule(
BlocRelatedClassNaming(config: config.blocRelatedClassNaming),
)
..registerWarningRule(
CatchParameterNames(config: config.catchParameterNames),
)
..registerWarningRule(AvoidConditionalHooks())
..registerWarningRule(HookWidgetDoesNotUseHooks())
..registerFixForRule(
Expand Down
93 changes: 93 additions & 0 deletions packages/leancode_lint/lib/src/bloc_utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:leancode_lint/src/type_checker.dart';

const blocChecker = TypeChecker.fromName('Bloc', packageName: 'bloc');

const cubitChecker = TypeChecker.fromName('Cubit', packageName: 'bloc');

const blocPresentationMixinChecker = TypeChecker.fromName(
'BlocPresentationMixin',
packageName: 'bloc_presentation',
);

String? getBlocSubject(String className, {required BlocType blocType}) =>
switch (blocType) {
.bloc when className.endsWith('Bloc') => className.substring(
0,
className.length - 4,
),
.cubit when className.endsWith('Cubit') => className.substring(
0,
className.length - 5,
),
_ => null,
};

enum BlocType { bloc, cubit }

BlocType? determineBlocType(Element? element) {
if (element == null) {
return null;
}

if (blocChecker.isAssignableFrom(element)) {
return .bloc;
} else if (cubitChecker.isAssignableFrom(element)) {
return .cubit;
}

return null;
}

class BlocInfo {
const BlocInfo({
required this.type,
this.stateType,
this.eventType,
this.presentationEventType,
});

final BlocType type;
final TypeAnnotation? stateType;
final TypeAnnotation? eventType;
final TypeAnnotation? presentationEventType;
}

BlocInfo? getBlocInfo(ClassDeclaration node) {
final extendsClause = node.extendsClause;
final superclass = extendsClause?.superclass;
final superclassElement = superclass?.element;

final type = determineBlocType(superclassElement);
if (type == null) {
return null;
}

final typeArguments = superclass?.typeArguments?.arguments;

final (eventType, stateType) = switch (typeArguments) {
[final state] when type == .cubit => (null, state),
[final event, final state] when type == .bloc => (event, state),
_ => (null, null),
};

TypeAnnotation? presentationEventType;
if (node.withClause case final withClause?) {
for (final mixin in withClause.mixinTypes) {
if (mixin.element case final mixinElement?
when blocPresentationMixinChecker.isExactly(mixinElement)) {
if (mixin.typeArguments?.arguments case [_, final presentationEvent]) {
presentationEventType = presentationEvent;
}
}
}
}

return .new(
type: type,
stateType: stateType,
eventType: eventType,
presentationEventType: presentationEventType,
);
}
106 changes: 106 additions & 0 deletions packages/leancode_lint/lib/src/lints/bloc_related_class_naming.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import 'package:analyzer/analysis_rule/analysis_rule.dart';
import 'package:analyzer/analysis_rule/rule_context.dart';
import 'package:analyzer/analysis_rule/rule_visitor_registry.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/error/error.dart';
import 'package:leancode_lint/config.dart';
import 'package:leancode_lint/src/bloc_utils.dart';
import 'package:leancode_lint/src/utils.dart';

/// Enforces consistent naming of state, event, and presentation event classes
/// related to a BLoC or Cubit.
///
/// Given a BLoC or Cubit named `FooBloc` or `FooCubit`, the associated classes
/// should be named:
/// - state → `FooState`
/// - event → `FooEvent`
/// - presentation event → `FooPresentationEvent`
///
/// The suffixes are configurable via [BlocRelatedClassNamingConfig].
class BlocRelatedClassNaming extends AnalysisRule {
Comment thread
Albert221 marked this conversation as resolved.
BlocRelatedClassNaming({this.config = const .new()})
: super(name: code.lowerCaseName, description: code.problemMessage);

final BlocRelatedClassNamingConfig config;

static const code = LintCode(
'bloc_related_class_naming',
"The name of {0}'s {1} should be {2}.",
severity: .WARNING,
);

@override
LintCode get diagnosticCode => code;

@override
void registerNodeProcessors(
RuleVisitorRegistry registry,
RuleContext context,
) {
registry.addClassDeclaration(this, _Visitor(this, context, config));
}
}

class _Visitor extends SimpleAstVisitor<void> {
_Visitor(this.rule, this.context, this.config);

final AnalysisRule rule;
final RuleContext context;
final BlocRelatedClassNamingConfig config;

@override
void visitClassDeclaration(ClassDeclaration node) {
final blocInfo = getBlocInfo(node);
if (blocInfo == null) {
return;
}

final classElement = node.declaredFragment?.element;
final className = node.namePart.typeName.lexeme;
final subject = getBlocSubject(className, blocType: blocInfo.type);

if (subject == null) {
return;
}

void checkName(TypeAnnotation type, String classType, String suffix) {
final expectedName = '$subject$suffix';

if (type case NamedType(
:final name,
:final element?,
:final CompilationUnit root,
) when name.lexeme != expectedName) {
if (element.library != classElement?.library) {
return;
}

final declaration = root.declarations
.whereType<ClassDeclaration>()
.firstWhereOrNull((d) => d.declaredFragment?.element == element);

rule.reportAtToken(
Comment thread
PiotrRogulski marked this conversation as resolved.
declaration?.namePart.typeName ?? name,
arguments: [className, classType, expectedName],
);
}
}

if (blocInfo.stateType case final stateType?) {
checkName(stateType, 'state', config.stateSuffix);
}

if (blocInfo.eventType case final eventType?) {
checkName(eventType, 'event', config.eventSuffix);
}

if (blocInfo.presentationEventType case final presentationEventType?) {
checkName(
presentationEventType,
'presentation event',
config.presentationEventSuffix,
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class CatchParameterNames extends AnalysisRule {
CatchParameterNames({required this.config})
: super(name: code.lowerCaseName, description: code.problemMessage);

final LeanCodeLintConfig config;
final CatchParameterNamesConfig config;

static const code = LintCode(
'catch_parameter_names',
Expand All @@ -46,7 +46,7 @@ class _Visitor extends SimpleAstVisitor<void> {

final AnalysisRule rule;
final RuleContext context;
final LeanCodeLintConfig config;
final CatchParameterNamesConfig config;

@override
void visitCatchClause(CatchClause node) {
Expand Down Expand Up @@ -81,8 +81,8 @@ enum _CatchClauseParameter {
exception,
stackTrace;

String preferredName(LeanCodeLintConfig config) => switch (this) {
exception => config.catchParameterNames.exception,
stackTrace => config.catchParameterNames.stackTrace,
String preferredName(CatchParameterNamesConfig config) => switch (this) {
exception => config.exception,
stackTrace => config.stackTrace,
};
}
Loading