Skip to content
Open
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
11 changes: 11 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import 'package:solid_lints/src/lints/cyclomatic_complexity/cyclomatic_complexit
import 'package:solid_lints/src/lints/double_literal_format/double_literal_format_rule.dart';
import 'package:solid_lints/src/lints/double_literal_format/fixes/double_literal_format_fix.dart';
import 'package:solid_lints/src/lints/function_lines_of_code/function_lines_of_code_rule.dart';
import 'package:solid_lints/src/lints/prefer_conditional_expressions/fixes/prefer_conditional_expressions_fix.dart';
import 'package:solid_lints/src/lints/prefer_conditional_expressions/prefer_conditional_expressions_rule.dart';
import 'package:solid_lints/src/lints/prefer_first/fixes/prefer_first_fix.dart';
import 'package:solid_lints/src/lints/prefer_first/prefer_first_rule.dart';
import 'package:solid_lints/src/lints/proper_super_calls/proper_super_calls_rule.dart';
Expand Down Expand Up @@ -42,6 +44,9 @@ class SolidLintsPlugin extends Plugin {
AvoidUnnecessaryTypeAssertionsRule();
final doubleLiteralFormatRule = DoubleLiteralFormatRule();
final preferFirstRule = PreferFirstRule();
final preferConditionalExpressionsRule = PreferConditionalExpressionsRule(
analysisOptionsLoader: analysisLoader,
);

final lintRules = [
AvoidFinalWithGetterRule(),
Expand All @@ -65,6 +70,7 @@ class SolidLintsPlugin extends Plugin {
),
UseNearestContextRule(),
preferFirstRule,
preferConditionalExpressionsRule,
// TODO: Add more lint rules and use analysisLoader
// for rules that need parameters
// For example: `CyclomaticComplexityRule(analysisLoader)`
Expand Down Expand Up @@ -97,5 +103,10 @@ class SolidLintsPlugin extends Plugin {
preferFirstRule.diagnosticCode,
PreferFirstFix.new,
);

registry.registerFixForRule(
preferConditionalExpressionsRule.diagnosticCode,
PreferConditionalExpressionsFix.new,
);
}
}
Original file line number Diff line number Diff line change
@@ -1,56 +1,55 @@
import 'package:analysis_server_plugin/edit/dart/correction_producer.dart';
import 'package:analysis_server_plugin/edit/dart/dart_fix_kind_priority.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/diagnostic/diagnostic.dart';
import 'package:analyzer/source/source_range.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';
import 'package:solid_lints/src/lints/prefer_conditional_expressions/visitors/prefer_conditional_expressions_visitor.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
import 'package:solid_lints/src/lints/prefer_conditional_expressions/models/statement_info.dart';
import 'package:solid_lints/src/lints/prefer_conditional_expressions/prefer_conditional_expressions_rule.dart';

/// A Quick fix for `prefer_conditional_expressions` rule
/// Suggests to remove unnecessary assertions
class PreferConditionalExpressionsFix extends DartFix {
final Expando<StatementInfo> _diagnosticsInfoExpando;
/// Suggests to convert simple if statements to conditional expressions
class PreferConditionalExpressionsFix extends ResolvedCorrectionProducer {
static const _fixComment = "Convert to conditional expression.";

/// A Quick fix for `prefer_conditional_expressions` rule
/// Suggests to remove unnecessary assertions
PreferConditionalExpressionsFix(this._diagnosticsInfoExpando);
/// Creates a new instance of [PreferConditionalExpressionsFix]
PreferConditionalExpressionsFix({required super.context});

@override
void run(
CustomLintResolver resolver,
ChangeReporter reporter,
CustomLintContext context,
Diagnostic diagnostic,
List<Diagnostic> others,
) {
context.registry.addIfStatement((node) {
if (!diagnostic.sourceRange.intersects(node.sourceRange)) return;
FixKind get fixKind => const FixKind(
'solid_lints.fix.${PreferConditionalExpressionsRule.lintName}',
DartFixKindPriority.standard,
_fixComment,
);

final statementInfo = _diagnosticsInfoExpando[diagnostic];
if (statementInfo == null) return;
@override
FixKind get multiFixKind => const FixKind(
'solid_lints.fix.multi.${PreferConditionalExpressionsRule.lintName}',
DartFixKindPriority.standard,
'$_fixComment across files',
);

final correction = _createCorrection(statementInfo);
if (correction == null) return;
@override
CorrectionApplicability get applicability =>
CorrectionApplicability.automatically;

_addReplacement(reporter, statementInfo.statement, correction);
});
}
@override
Future<void> compute(ChangeBuilder builder) async {
final statement = node.thisOrAncestorOfType<IfStatement>();
if (statement == null) return;

void _addReplacement(
ChangeReporter reporter,
IfStatement node,
String correction,
) {
final changeBuilder = reporter.createChangeBuilder(
message: "Convert to conditional expression.",
priority: 1,
);
final statementInfo = StatementInfo.fromIfStatement(statement);
if (statementInfo == null) return;

changeBuilder.addDartFileEdit((builder) {
builder.addSimpleReplacement(
SourceRange(node.offset, node.length),
final correction = _createCorrection(statementInfo);
if (correction == null) return;

await builder.addDartFileEdit(
file,
(builder) => builder.addSimpleReplacement(
statement.sourceRange,
correction,
);
});
),
);
}

String? _createCorrection(StatementInfo info) {
Expand All @@ -64,28 +63,15 @@ class PreferConditionalExpressionsFix extends DartFix {
final target = thenStatement.leftHandSide;
final firstExpression = thenStatement.rightHandSide;
final secondExpression = elseStatement.rightHandSide;

final thenStatementOperator = thenStatement.operator.type;
final elseStatementOperator = elseStatement.operator.type;

if (_isAssignmentOperatorNotEq(thenStatementOperator) &&
_isAssignmentOperatorNotEq(elseStatementOperator)) {
final prefix = thenStatement.leftHandSide;
final thenPart =
'$prefix ${thenStatementOperator.stringValue} $firstExpression';
final elsePart =
'$prefix ${elseStatementOperator.stringValue} $secondExpression;';

return '$condition ? $thenPart : $elsePart';
}
final op = thenStatement.operator.lexeme;

final correctionForLiterals = _createCorrectionForLiterals(
condition,
firstExpression,
secondExpression,
);

return '$target = $correctionForLiterals';
return '$target $op $correctionForLiterals';
}

if (thenStatement is ReturnStatement && elseStatement is ReturnStatement) {
Expand All @@ -110,14 +96,23 @@ class PreferConditionalExpressionsFix extends DartFix {
) {
if (firstExpression is BooleanLiteral &&
secondExpression is BooleanLiteral) {
if (firstExpression.value == secondExpression.value) {
return '${firstExpression.value};';
}
final isInverted = !firstExpression.value && secondExpression.value;
if (isInverted) {
final useParentheses =
condition is! Identifier &&
condition is! PropertyAccess &&
condition is! MethodInvocation &&
condition is! IndexExpression &&
condition is! ParenthesizedExpression;
return '${useParentheses ? '!($condition)' : '!$condition'};';
}

return '${isInverted ? "!" : ""}$condition;';
return '$condition;';
}

return '$condition ? $firstExpression : $secondExpression;';
}

bool _isAssignmentOperatorNotEq(TokenType token) =>
token.isAssignmentOperator && token != TokenType.EQ;
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,16 @@ class PreferConditionalExpressionsParameters {
required this.ignoreNested,
});

/// Empty [PreferConditionalExpressionsParameters] model.
factory PreferConditionalExpressionsParameters.empty() =>
const PreferConditionalExpressionsParameters(
ignoreNested: false,
);

/// Method for creating from json data
factory PreferConditionalExpressionsParameters.fromJson(
Map<String, Object?> json,
) =>
PreferConditionalExpressionsParameters(
ignoreNested: json[_ignoreNestedConfig] as bool? ?? false,
);
) => PreferConditionalExpressionsParameters(
ignoreNested: json[_ignoreNestedConfig] as bool? ?? false,
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// 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';

/// Data class contains info required for fix
class StatementInfo {
/// If statement node
final IfStatement statement;

/// Contents of if block
final AstNode unwrappedThenStatement;

/// Contents of else block
final AstNode unwrappedElseStatement;

/// Creates instance of an [StatementInfo]
const StatementInfo({
required this.statement,
required this.unwrappedThenStatement,
required this.unwrappedElseStatement,
});

/// Factory constructor to create [StatementInfo] from [IfStatement] if it
/// can be simplified.
static StatementInfo? fromIfStatement(IfStatement statement) {
if (statement.parent is IfStatement ||
statement.elseStatement == null ||
statement.elseStatement is IfStatement) {
return null;
}

final thenAssignment = _getAssignmentExpression(statement.thenStatement);
final elseAssignment = _getAssignmentExpression(statement.elseStatement);

if (thenAssignment != null &&
elseAssignment != null &&
thenAssignment.operator.type == elseAssignment.operator.type &&
_haveEqualNames(thenAssignment, elseAssignment)) {
return StatementInfo(
statement: statement,
unwrappedThenStatement: thenAssignment,
unwrappedElseStatement: elseAssignment,
);
}

final thenReturn = _getReturnStatement(statement.thenStatement);
final elseReturn = _getReturnStatement(statement.elseStatement);

if (thenReturn != null &&
elseReturn != null &&
thenReturn.expression != null &&
elseReturn.expression != null) {
return StatementInfo(
statement: statement,
unwrappedThenStatement: thenReturn,
unwrappedElseStatement: elseReturn,
);
}

return null;
}

static AssignmentExpression? _getAssignmentExpression(Statement? statement) {
if (statement is ExpressionStatement &&
statement.expression is AssignmentExpression) {
return statement.expression as AssignmentExpression;
}

if (statement is Block && statement.statements.length == 1) {
return _getAssignmentExpression(statement.statements.first);
}

return null;
}

static bool _haveEqualNames(
AssignmentExpression thenAssignment,
AssignmentExpression elseAssignment,
) =>
thenAssignment.leftHandSide is Identifier &&
elseAssignment.leftHandSide is Identifier &&
(thenAssignment.leftHandSide as Identifier).name ==
(elseAssignment.leftHandSide as Identifier).name;

static ReturnStatement? _getReturnStatement(Statement? statement) {
if (statement is ReturnStatement) {
return statement;
}

if (statement is Block && statement.statements.length == 1) {
return _getReturnStatement(statement.statements.first);
}

return null;
}
}
Loading