From adfbfbd36b6aba8b1b0708588ae46420b44e959b Mon Sep 17 00:00:00 2001 From: vladimir-beloded Date: Wed, 15 Nov 2023 16:10:25 +0200 Subject: [PATCH] Fix no_magic_number missing reports --- .../no_magic_number/no_magic_number_rule.dart | 15 ++++++++++----- lint_test/no_magic_number_test.dart | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/lib/lints/no_magic_number/no_magic_number_rule.dart b/lib/lints/no_magic_number/no_magic_number_rule.dart index c9e1e201..3e065a2c 100644 --- a/lib/lints/no_magic_number/no_magic_number_rule.dart +++ b/lib/lints/no_magic_number/no_magic_number_rule.dart @@ -83,11 +83,16 @@ class NoMagicNumberRule extends SolidLintRule { (l is IntegerLiteral && !config.parameters.allowedNumbers.contains(l.value)); - bool _isNotInsideVariable(Literal l) => - l.thisOrAncestorMatching( - (ancestor) => ancestor is VariableDeclaration, - ) == - null; + bool _isNotInsideVariable(Literal l) { + AstNode? node = l; + while (node != null && node is! InstanceCreationExpression) { + if (node is VariableDeclaration) return false; + + node = node.parent; + } + + return true; + } bool _isNotInDateTime(Literal l) => l.thisOrAncestorMatching( diff --git a/lint_test/no_magic_number_test.dart b/lint_test/no_magic_number_test.dart index b215ec4b..9d651c03 100644 --- a/lint_test/no_magic_number_test.dart +++ b/lint_test/no_magic_number_test.dart @@ -54,4 +54,18 @@ void fun() { // Allowed in DateTime because it doesn't have cons constructor final apocalypse = DateTime(2012, 12, 21); + + const count = 5; + const total = 10; + // expect_lint: no_magic_number + final percent = TestMagicNumber(percent: (count / total) * 100); + + // expect_lint: no_magic_number + TestMagicNumber(percent: (count / total) * 100); +} + +class TestMagicNumber { + final double percent; + + TestMagicNumber({required this.percent}); }