From 048df9d706c37b0fd00a88c65b7ce772ce125b8c Mon Sep 17 00:00:00 2001 From: Alexander Markov Date: Mon, 13 Jan 2025 07:30:16 -0800 Subject: [PATCH 01/76] [vm] Fix tree-shaking of mixin applications when mixin has a member with entry point pragma Cloned static members of mixins are not used (dead code) and usually tree shaken in AOT mode. However, if static member is annotated with @pragma('vm:entry-point'), its clone in the mixin application is also retained. If such mixin application is not used, tree shaker drops its supertypes which removes the link from mixin application to the original mixin. As a result, gen_snapshot crashes when trying to access original mixin in order to print qualified name of the member. The first part of the fix is to avoid cloning static members into mixin applications, which would allow tree shaker to remove unused mixin applications entirely. This change also reduces size of the non-AOT kernel binaries. However, instance members of mixins are cloned and they could be annotated with entry point pragmas too. The second part of the fix is to clear isEliminatedMixin flag in tree shaker when dropping supertypes. TEST=pkg/front_end/testcases/general/mixin_with_static_member.dart TEST=pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart Fixes https://github.com/flutter/flutter/issues/160030 Change-Id: I1b36c4a7f64a4530c8b4799ec785f1077ce65de6 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403963 Reviewed-by: Slava Egorov Commit-Queue: Alexander Markov --- ...e_libraries.dart.strong.transformed.expect | 38 -------- ...ries_legacy.dart.strong.transformed.expect | 38 -------- ...stantiation.dart.strong.transformed.expect | 2 - .../static.dart.strong.transformed.expect | 3 - .../issue40982.dart.strong.transformed.expect | 2 - .../issue52302.dart.strong.transformed.expect | 88 +------------------ ...atic_member.dart.strong.transformed.expect | 2 - ...type_scopes.dart.strong.transformed.expect | 2 - .../no_outline_change_22.yaml.world.1.expect | 5 -- .../no_outline_change_22.yaml.world.2.expect | 5 -- ...ccess_order.dart.strong.transformed.expect | 7 +- ...che_lookups.dart.strong.transformed.expect | 7 +- ...g_constants.dart.strong.transformed.expect | 73 ++------------- ...lement_once.dart.strong.transformed.expect | 7 +- ...tive_length.dart.strong.transformed.expect | 7 +- .../mixin_full_resolution.dart | 4 + .../type_flow/transformer.dart | 11 +-- .../transformer/regress_flutter160030.dart | 27 ++++++ .../regress_flutter160030.dart.expect | 33 +++++++ runtime/vm/kernel_loader.cc | 1 + runtime/vm/object.cc | 1 + 21 files changed, 88 insertions(+), 275 deletions(-) create mode 100644 pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart create mode 100644 pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart.expect diff --git a/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries.dart.strong.transformed.expect b/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries.dart.strong.transformed.expect index 9207be487131..5cbaf29a1100 100644 --- a/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries.dart.strong.transformed.expect @@ -20,15 +20,12 @@ library; import self as self; import "dart:core" as core; import "dart:_internal" as _in; -import "dart:convert" as con; abstract class _A&Object&Comparable extends core::Object implements core::Comparable /*isAnonymousMixin,isEliminatedMixin,hasConstConstructor*/ { const synthetic constructor •() → self::_A&Object&Comparable : super core::Object::•() ; abstract method /* from org-dartlang-sdk:///sdk/lib/core/comparable.dart */ compareTo(covariant-by-class core::int other) → core::int; - static method /* from org-dartlang-sdk:///sdk/lib/core/comparable.dart */ compare(core::Comparable a, core::Comparable b) → core::int - return a.{core::Comparable::compareTo}(b){(dynamic) → core::int}; } class A extends self::_A&Object&Comparable { synthetic constructor •() → self::A @@ -46,33 +43,6 @@ abstract class _B&Object&Error extends core::Object implements core::Error /*isA @#C4 get /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ stackTrace() → core::StackTrace? return this.{core::Error::_stackTrace}{core::StackTrace?}; - static method /* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ safeToString(core::Object? object) → core::String { - if(object is core::num || object is core::bool || object == null) { - return object.{core::Object::toString}{}.(){() → core::String}; - } - if(object{core::Object} is core::String) { - return core::Error::_stringToSafeString(object{core::String}); - } - return core::Error::_objectToString(object{core::Object}); - } - @#C4 - static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _stringToSafeString(core::String string) → core::String { - return #C5.{con::JsonCodec::encode}(string){(core::Object?, {toEncodable: (dynamic) →? core::Object?}) → core::String}; - } - @#C4 - static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _objectToString(core::Object object) → core::String { - return core::Object::_toString(object); - } - @#C7 - static method /* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ throwWithStackTrace(core::Object error, core::StackTrace stackTrace) → Never { - _in::checkNotNullable(error, "error"); - _in::checkNotNullable(stackTrace, "stackTrace"); - core::Error::_throw(error, stackTrace); - } - @#C4 - @#C10 - @/* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ #C12 - external static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _throw(core::Object error, core::StackTrace stackTrace) → Never; } class B extends self::_B&Object&Error { synthetic constructor •() → self::B @@ -85,12 +55,4 @@ constants { #C2 = null #C3 = core::pragma {name:#C1, options:#C2} #C4 = _in::_Patch {} - #C5 = con::JsonCodec {_reviver:#C2, _toEncodable:#C2} - #C6 = "2.16" - #C7 = _in::Since {version:#C6} - #C8 = "vm:external-name" - #C9 = "Error_throwWithStackTrace" - #C10 = core::pragma {name:#C8, options:#C9} - #C11 = "wasm:entry-point" - #C12 = core::pragma {name:#C11, options:#C2} } diff --git a/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries_legacy.dart.strong.transformed.expect b/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries_legacy.dart.strong.transformed.expect index 0b98e4ba4e7a..c7f5dafd98ac 100644 --- a/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries_legacy.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/class_modifiers/mixin/mixin_class_core_libraries_legacy.dart.strong.transformed.expect @@ -12,15 +12,12 @@ library; import self as self; import "dart:core" as core; import "dart:_internal" as _in; -import "dart:convert" as con; abstract class _A&Object&Comparable extends core::Object implements core::Comparable /*isAnonymousMixin,isEliminatedMixin,hasConstConstructor*/ { const synthetic constructor •() → self::_A&Object&Comparable : super core::Object::•() ; abstract method /* from org-dartlang-sdk:///sdk/lib/core/comparable.dart */ compareTo(covariant-by-class core::int other) → core::int; - static method /* from org-dartlang-sdk:///sdk/lib/core/comparable.dart */ compare(core::Comparable a, core::Comparable b) → core::int - return a.{core::Comparable::compareTo}(b){(dynamic) → core::int}; } class A extends self::_A&Object&Comparable { synthetic constructor •() → self::A @@ -38,33 +35,6 @@ abstract class _B&Object&Error extends core::Object implements core::Error /*isA @#C4 get /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ stackTrace() → core::StackTrace? return this.{core::Error::_stackTrace}{core::StackTrace?}; - static method /* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ safeToString(core::Object? object) → core::String { - if(object is core::num || object is core::bool || object == null) { - return object.{core::Object::toString}{}.(){() → core::String}; - } - if(object{core::Object} is core::String) { - return core::Error::_stringToSafeString(object{core::String}); - } - return core::Error::_objectToString(object{core::Object}); - } - @#C4 - static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _stringToSafeString(core::String string) → core::String { - return #C5.{con::JsonCodec::encode}(string){(core::Object?, {toEncodable: (dynamic) →? core::Object?}) → core::String}; - } - @#C4 - static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _objectToString(core::Object object) → core::String { - return core::Object::_toString(object); - } - @#C7 - static method /* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ throwWithStackTrace(core::Object error, core::StackTrace stackTrace) → Never { - _in::checkNotNullable(error, "error"); - _in::checkNotNullable(stackTrace, "stackTrace"); - core::Error::_throw(error, stackTrace); - } - @#C4 - @#C10 - @/* from org-dartlang-sdk:///sdk/lib/core/errors.dart */ #C12 - external static method /* from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/errors_patch.dart */ _throw(core::Object error, core::StackTrace stackTrace) → Never; } class B extends self::_B&Object&Error { synthetic constructor •() → self::B @@ -77,12 +47,4 @@ constants { #C2 = null #C3 = core::pragma {name:#C1, options:#C2} #C4 = _in::_Patch {} - #C5 = con::JsonCodec {_reviver:#C2, _toEncodable:#C2} - #C6 = "2.16" - #C7 = _in::Since {version:#C6} - #C8 = "vm:external-name" - #C9 = "Error_throwWithStackTrace" - #C10 = core::pragma {name:#C8, options:#C9} - #C11 = "wasm:entry-point" - #C12 = core::pragma {name:#C11, options:#C2} } diff --git a/pkg/front_end/testcases/constructor_tearoffs/explicit_instantiation.dart.strong.transformed.expect b/pkg/front_end/testcases/constructor_tearoffs/explicit_instantiation.dart.strong.transformed.expect index b86ef6fb0872..4d467bda26ce 100644 --- a/pkg/front_end/testcases/constructor_tearoffs/explicit_instantiation.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/constructor_tearoffs/explicit_instantiation.dart.strong.transformed.expect @@ -48,8 +48,6 @@ abstract class _D&C&M extends self::C implements self::M /*isAnonymousMixin,isEl (core::int) → core::int f3 = this.{self::M::minst}{(T%) → T%}; core::String f3TypeName = (this.{self::M::minst}{(T%) → T%}).{core::Object::runtimeType}{core::Type}.{core::Type::toString}(){() → core::String}; } - static method mstat(self::_D&C&M::mstat::T% value) → self::_D&C&M::mstat::T% - return value; } class D extends self::_D&C&M { synthetic constructor •() → self::D diff --git a/pkg/front_end/testcases/general/hierarchy/static.dart.strong.transformed.expect b/pkg/front_end/testcases/general/hierarchy/static.dart.strong.transformed.expect index 9ef6ff7f44d4..76e8d6818154 100644 --- a/pkg/front_end/testcases/general/hierarchy/static.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/general/hierarchy/static.dart.strong.transformed.expect @@ -121,9 +121,6 @@ abstract class _Class&Super&Mixin extends self::Super implements self::Mixin /*i method mixedInInstanceDeclaredStaticMethod() → void {} method mixedInInstanceImplementedStaticMethod() → void {} method extendedStaticMixedInInstanceMethod() → void {} - static method mixedInStaticDeclaredInstanceMethod() → void {} - static method mixedInStaticImplementedInstanceMethod() → void {} - static method extendedInstanceMixedInStaticMethod() → void {} } abstract class Class extends self::_Class&Super&Mixin implements self::Interface { synthetic constructor •() → self::Class diff --git a/pkg/front_end/testcases/general/issue40982.dart.strong.transformed.expect b/pkg/front_end/testcases/general/issue40982.dart.strong.transformed.expect index b0e5807cb107..05002fd40723 100644 --- a/pkg/front_end/testcases/general/issue40982.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/general/issue40982.dart.strong.transformed.expect @@ -22,7 +22,6 @@ abstract class B extends core::Object /*isMixinDeclaration*/ { static const field core::int value = #C1; } abstract class _C1&A&B extends self::A implements self::B /*isAnonymousMixin,isEliminatedMixin,hasConstConstructor*/ { - static const field core::int value = #C1; const synthetic constructor •() → self::_C1&A&B : super self::A::•() ; @@ -33,7 +32,6 @@ class C1 extends self::_C1&A&B /*hasConstConstructor*/ { ; } class C2 extends self::A implements self::B /*isEliminatedMixin,hasConstConstructor*/ { - static const field core::int value = #C1; const synthetic constructor •() → self::C2 : super self::A::•() ; diff --git a/pkg/front_end/testcases/general/issue52302.dart.strong.transformed.expect b/pkg/front_end/testcases/general/issue52302.dart.strong.transformed.expect index 1e5d3a5fade3..c4aa16cb85ff 100644 --- a/pkg/front_end/testcases/general/issue52302.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/general/issue52302.dart.strong.transformed.expect @@ -242,45 +242,6 @@ abstract class _MixesInMixesInMixin&Object&MixesInMixin extends core::Object imp } method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ toString() → core::String return core::Iterable::iterableToShortString(this, "(", ")"); - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ castFrom(core::Iterable source) → core::Iterable - return _in::CastIterable::•(source); - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ iterableToShortString(core::Iterable iterable, [core::String leftDelimiter = #C4, core::String rightDelimiter = #C5]) → core::String { - if(_in::isToStringVisiting(iterable)) { - if(leftDelimiter =={core::String::==}{(core::Object) → core::bool} "(" && rightDelimiter =={core::String::==}{(core::Object) → core::bool} ")") { - return "(...)"; - } - return "${leftDelimiter}...${rightDelimiter}"; - } - core::List parts = core::_GrowableList::•(0); - _in::toStringVisiting.{core::List::add}(iterable){(core::Object) → void}; - try { - core::_iterablePartsToStrings(iterable, parts); - } - finally { - assert(core::identical(_in::toStringVisiting.{core::Iterable::last}{core::Object}, iterable)); - _in::toStringVisiting.{core::List::removeLast}(){() → core::Object}; - } - return (let final core::StringBuffer #t2 = new core::StringBuffer::•(leftDelimiter) in block { - #t2.{core::StringBuffer::writeAll}(parts, ", "){(core::Iterable, [core::String]) → void}; - #t2.{core::StringBuffer::write}(rightDelimiter){(core::Object?) → void}; - } =>#t2).{core::StringBuffer::toString}(){() → core::String}; - } - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ iterableToFullString(core::Iterable iterable, [core::String leftDelimiter = #C4, core::String rightDelimiter = #C5]) → core::String { - if(_in::isToStringVisiting(iterable)) { - return "${leftDelimiter}...${rightDelimiter}"; - } - core::StringBuffer buffer = new core::StringBuffer::•(leftDelimiter); - _in::toStringVisiting.{core::List::add}(iterable){(core::Object) → void}; - try { - buffer.{core::StringBuffer::writeAll}(iterable, ", "){(core::Iterable, [core::String]) → void}; - } - finally { - assert(core::identical(_in::toStringVisiting.{core::Iterable::last}{core::Object}, iterable)); - _in::toStringVisiting.{core::List::removeLast}(){() → core::Object}; - } - buffer.{core::StringBuffer::write}(rightDelimiter){(core::Object?) → void}; - return buffer.{core::StringBuffer::toString}(){() → core::String}; - } } abstract base class MixesInMixesInMixin extends self::_MixesInMixesInMixin&Object&MixesInMixin { synthetic constructor •() → self::MixesInMixesInMixin @@ -390,10 +351,10 @@ abstract mixin class MixesInMixin extends core::Object implements core::Iterable } else { do { - let final core::StringBuffer #t3 = buffer in block { - #t3.{core::StringBuffer::write}(separator){(core::Object?) → void}; - #t3.{core::StringBuffer::write}(iterator.{core::Iterator::current}{core::int}.{core::Object::toString}{}.(){() → core::String}){(core::Object?) → void}; - } =>#t3; + let final core::StringBuffer #t2 = buffer in block { + #t2.{core::StringBuffer::write}(separator){(core::Object?) → void}; + #t2.{core::StringBuffer::write}(iterator.{core::Iterator::current}{core::int}.{core::Object::toString}{}.(){() → core::String}){(core::Object?) → void}; + } =>#t2; } while (iterator.{core::Iterator::moveNext}(){() → core::bool}) } @@ -530,51 +491,10 @@ abstract mixin class MixesInMixin extends core::Object implements core::Iterable } method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ toString() → core::String return core::Iterable::iterableToShortString(this, "(", ")"); - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ castFrom(core::Iterable source) → core::Iterable - return _in::CastIterable::•(source); - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ iterableToShortString(core::Iterable iterable, [core::String leftDelimiter = #C4, core::String rightDelimiter = #C5]) → core::String { - if(_in::isToStringVisiting(iterable)) { - if(leftDelimiter =={core::String::==}{(core::Object) → core::bool} "(" && rightDelimiter =={core::String::==}{(core::Object) → core::bool} ")") { - return "(...)"; - } - return "${leftDelimiter}...${rightDelimiter}"; - } - core::List parts = core::_GrowableList::•(0); - _in::toStringVisiting.{core::List::add}(iterable){(core::Object) → void}; - try { - core::_iterablePartsToStrings(iterable, parts); - } - finally { - assert(core::identical(_in::toStringVisiting.{core::Iterable::last}{core::Object}, iterable)); - _in::toStringVisiting.{core::List::removeLast}(){() → core::Object}; - } - return (let final core::StringBuffer #t4 = new core::StringBuffer::•(leftDelimiter) in block { - #t4.{core::StringBuffer::writeAll}(parts, ", "){(core::Iterable, [core::String]) → void}; - #t4.{core::StringBuffer::write}(rightDelimiter){(core::Object?) → void}; - } =>#t4).{core::StringBuffer::toString}(){() → core::String}; - } - static method /* from org-dartlang-sdk:///sdk/lib/core/iterable.dart */ iterableToFullString(core::Iterable iterable, [core::String leftDelimiter = #C4, core::String rightDelimiter = #C5]) → core::String { - if(_in::isToStringVisiting(iterable)) { - return "${leftDelimiter}...${rightDelimiter}"; - } - core::StringBuffer buffer = new core::StringBuffer::•(leftDelimiter); - _in::toStringVisiting.{core::List::add}(iterable){(core::Object) → void}; - try { - buffer.{core::StringBuffer::writeAll}(iterable, ", "){(core::Iterable, [core::String]) → void}; - } - finally { - assert(core::identical(_in::toStringVisiting.{core::Iterable::last}{core::Object}, iterable)); - _in::toStringVisiting.{core::List::removeLast}(){() → core::Object}; - } - buffer.{core::StringBuffer::write}(rightDelimiter){(core::Object?) → void}; - return buffer.{core::StringBuffer::toString}(){() → core::String}; - } } constants { #C1 = "" #C2 = true #C3 = null - #C4 = "(" - #C5 = ")" } diff --git a/pkg/front_end/testcases/general/mixin_with_static_member.dart.strong.transformed.expect b/pkg/front_end/testcases/general/mixin_with_static_member.dart.strong.transformed.expect index 619b760c45df..6fc9964eefae 100644 --- a/pkg/front_end/testcases/general/mixin_with_static_member.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/general/mixin_with_static_member.dart.strong.transformed.expect @@ -6,8 +6,6 @@ abstract class _A&B&M extends self::B implements self::M /*isAnonymousMixin,isEl synthetic constructor •() → self::_A&B&M : super self::B::•() ; - static method m() → core::Object - return new core::Object::•(); } class A extends self::_A&B&M { synthetic constructor •() → self::A diff --git a/pkg/front_end/testcases/general/type_scopes.dart.strong.transformed.expect b/pkg/front_end/testcases/general/type_scopes.dart.strong.transformed.expect index f3bdb6b94a59..0101b02da93a 100644 --- a/pkg/front_end/testcases/general/type_scopes.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/general/type_scopes.dart.strong.transformed.expect @@ -56,12 +56,10 @@ abstract class Mixin extends self::S imple } class NamedMixinApplication extends self::Class implements self::Mixin /*isEliminatedMixin*/ { field dynamic instanceField = null; - static field dynamic staticField = null; synthetic constructor •(self::NamedMixinApplication::T9% t3) → self::NamedMixinApplication : super self::Class::•(t3) ; method instanceMethod(covariant-by-class self::NamedMixinApplication::T9% t6, self::NamedMixinApplication::instanceMethod::T7% t7) → void {} - static method staticMethod(self::NamedMixinApplication::staticMethod::T8% t8) → void {} } abstract class _Enum&_Enum&M extends core::_Enum implements self::M /*isAnonymousMixin,isEliminatedMixin,hasConstConstructor*/ { const synthetic constructor •(core::int index, core::String _name) → self::_Enum&_Enum&M diff --git a/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.1.expect b/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.1.expect index 7326ea512104..c389fe89ea35 100644 --- a/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.1.expect +++ b/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.1.expect @@ -502,11 +502,6 @@ library from "org-dartlang-test:///main.dart" as main { return new dart._internal::ReversedListIterable::•(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → dart.core::String return dart.collection::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → dart.core::int { - return dart.core::Comparable::compare(a as dart.core::Comparable, b as dart.core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(dart.core::List list) → dart.core::String - return dart.core::Iterable::iterableToFullString(list, "[", "]"); } class WithListMixin extends main::_WithListMixin&Object&ListMixin { field dart.core::int length = 2; diff --git a/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.2.expect b/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.2.expect index 7326ea512104..c389fe89ea35 100644 --- a/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.2.expect +++ b/pkg/front_end/testcases/incremental/no_outline_change_22.yaml.world.2.expect @@ -502,11 +502,6 @@ library from "org-dartlang-test:///main.dart" as main { return new dart._internal::ReversedListIterable::•(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → dart.core::String return dart.collection::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → dart.core::int { - return dart.core::Comparable::compare(a as dart.core::Comparable, b as dart.core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(dart.core::List list) → dart.core::String - return dart.core::Iterable::iterableToFullString(list, "[", "]"); } class WithListMixin extends main::_WithListMixin&Object&ListMixin { field dart.core::int length = 2; diff --git a/pkg/front_end/testcases/patterns/access_order.dart.strong.transformed.expect b/pkg/front_end/testcases/patterns/access_order.dart.strong.transformed.expect index 10f49c0c2c46..f1a37254e45d 100644 --- a/pkg/front_end/testcases/patterns/access_order.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/patterns/access_order.dart.strong.transformed.expect @@ -507,11 +507,6 @@ abstract class _MyList&Object&ListMixin exten return new _in::ReversedListIterable::•(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → core::String return col::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → core::int { - return core::Comparable::compare(a as core::Comparable, b as core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(core::List list) → core::String - return core::Iterable::iterableToFullString(list, "[", "]"); } class MyList extends self::_MyList&Object&ListMixin { final field core::List list; @@ -654,4 +649,4 @@ Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:462:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:471:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:480:12 -> IntConstant(-1) -Extra constant evaluation: evaluated: 1239, effectively constant: 4 +Extra constant evaluation: evaluated: 1232, effectively constant: 4 diff --git a/pkg/front_end/testcases/patterns/cache_lookups.dart.strong.transformed.expect b/pkg/front_end/testcases/patterns/cache_lookups.dart.strong.transformed.expect index 79237dc6c881..d454194c0ac6 100644 --- a/pkg/front_end/testcases/patterns/cache_lookups.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/patterns/cache_lookups.dart.strong.transformed.expect @@ -574,11 +574,6 @@ abstract class _CustomList&Object&ListMixin e return new _in::ReversedListIterable::•(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → core::String return col::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → core::int { - return core::Comparable::compare(a as core::Comparable, b as core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(core::List list) → core::String - return core::Iterable::iterableToFullString(list, "[", "]"); } class CustomList extends cac::_CustomList&Object&ListMixin { final field core::List list; @@ -616,4 +611,4 @@ Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:462:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:471:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:480:12 -> IntConstant(-1) -Extra constant evaluation: evaluated: 1215, effectively constant: 4 +Extra constant evaluation: evaluated: 1208, effectively constant: 4 diff --git a/pkg/front_end/testcases/patterns/caching_constants.dart.strong.transformed.expect b/pkg/front_end/testcases/patterns/caching_constants.dart.strong.transformed.expect index 8e3f3e7ea6c9..55b7e388e554 100644 --- a/pkg/front_end/testcases/patterns/caching_constants.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/patterns/caching_constants.dart.strong.transformed.expect @@ -2,7 +2,6 @@ library; import self as self; import "dart:core" as core; import "dart:collection" as col; -import "dart:_internal" as _in; import "dart:collection"; @@ -134,61 +133,6 @@ abstract class _MyMap&Object&MapMixin(this); method /* from org-dartlang-sdk:///sdk/lib/collection/maps.dart */ toString() → core::String return col::MapBase::mapToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/maps.dart */ mapToString(core::Map m) → core::String { - if(_in::isToStringVisiting(m)) { - return "{...}"; - } - core::StringBuffer result = new core::StringBuffer::•(); - try { - _in::toStringVisiting.{core::List::add}(m){(core::Object) → void}; - result.{core::StringBuffer::write}("{"){(core::Object?) → void}; - core::bool first = true; - m.{core::Map::forEach}((core::Object? k, core::Object? v) → void { - if(!first) { - result.{core::StringBuffer::write}(", "){(core::Object?) → void}; - } - first = false; - result.{core::StringBuffer::write}(k){(core::Object?) → void}; - result.{core::StringBuffer::write}(": "){(core::Object?) → void}; - result.{core::StringBuffer::write}(v){(core::Object?) → void}; - }){((core::Object?, core::Object?) → void) → void}; - result.{core::StringBuffer::write}("}"){(core::Object?) → void}; - } - finally { - assert(core::identical(_in::toStringVisiting.{core::Iterable::last}{core::Object}, m)); - _in::toStringVisiting.{core::List::removeLast}(){() → core::Object}; - } - return result.{core::StringBuffer::toString}(){() → core::String}; - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/maps.dart */ _fillMapWithMappedIterable(core::Map map, core::Iterable iterable, (core::Object?) →? core::Object? key, (core::Object?) →? core::Object? value) → void { - key == null ?{(core::Object?) →? core::Object?} key = #C2 : null; - value == null ?{(core::Object?) →? core::Object?} value = #C2 : null; - { - synthesized core::Iterator :sync-for-iterator = iterable.{core::Iterable::iterator}{core::Iterator}; - for (; :sync-for-iterator.{core::Iterator::moveNext}(){() → core::bool}; ) { - core::Object? element = :sync-for-iterator.{core::Iterator::current}{core::Object?}; - { - map.{core::Map::[]=}(key{(core::Object?) → core::Object?}(element){(core::Object?) → core::Object?}, value{(core::Object?) → core::Object?}(element){(core::Object?) → core::Object?}){(core::Object?, core::Object?) → void}; - } - } - } - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/maps.dart */ _id(core::Object? x) → core::Object? - return x; - static method /* from org-dartlang-sdk:///sdk/lib/collection/maps.dart */ _fillMapWithIterables(core::Map map, core::Iterable keys, core::Iterable values) → void { - core::Iterator keyIterator = keys.{core::Iterable::iterator}{core::Iterator}; - core::Iterator valueIterator = values.{core::Iterable::iterator}{core::Iterator}; - core::bool hasNextKey = keyIterator.{core::Iterator::moveNext}(){() → core::bool}; - core::bool hasNextValue = valueIterator.{core::Iterator::moveNext}(){() → core::bool}; - while (hasNextKey && hasNextValue) { - map.{core::Map::[]=}(keyIterator.{core::Iterator::current}{core::Object?}, valueIterator.{core::Iterator::current}{core::Object?}){(core::Object?, core::Object?) → void}; - hasNextKey = keyIterator.{core::Iterator::moveNext}(){() → core::bool}; - hasNextValue = valueIterator.{core::Iterator::moveNext}(){() → core::bool}; - } - if(hasNextKey || hasNextValue) { - throw new core::ArgumentError::•("Iterables do not have same length."); - } - } } class MyMap extends self::_MyMap&Object&MapMixin { field core::int containsKeyCount = 0; @@ -215,7 +159,7 @@ class MyMap}.{core::Map::remove}(key){(core::Object?) → self::MyMap::V?}; } static get hasUnsoundNullSafety() → core::bool - return #C3 is core::List; + return #C2 is core::List; static method method(core::Map m) → core::int { #L1: { @@ -225,14 +169,14 @@ static method method(core::Map m) → core::int { synthesized core::bool #0#2; synthesized core::bool #0#2#isSet = false; { - if((!((#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t28 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C4){(core::Object?) → core::String?}) == null) || null is core::String? && (#0#2#isSet ?{core::bool} #0#2{core::bool} : let final core::bool #t29 = #0#2#isSet = true in #0#2 = #0#0.{core::Map::containsKey}(#C4){(core::Object?) → core::bool})) && #C5 =={core::String::==}{(core::Object) → core::bool} (#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t30 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C4){(core::Object?) → core::String?})) { + if((!((#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t28 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C3){(core::Object?) → core::String?}) == null) || null is core::String? && (#0#2#isSet ?{core::bool} #0#2{core::bool} : let final core::bool #t29 = #0#2#isSet = true in #0#2 = #0#0.{core::Map::containsKey}(#C3){(core::Object?) → core::bool})) && #C4 =={core::String::==}{(core::Object) → core::bool} (#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t30 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C3){(core::Object?) → core::String?})) { { return 0; } } } { - if((!((#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t31 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C4){(core::Object?) → core::String?}) == null) || null is core::String? && (#0#2#isSet ?{core::bool} #0#2{core::bool} : let final core::bool #t32 = #0#2#isSet = true in #0#2 = #0#0.{core::Map::containsKey}(#C4){(core::Object?) → core::bool})) && #C6 =={core::String::==}{(core::Object) → core::bool} (#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t33 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C4){(core::Object?) → core::String?})) { + if((!((#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t31 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C3){(core::Object?) → core::String?}) == null) || null is core::String? && (#0#2#isSet ?{core::bool} #0#2{core::bool} : let final core::bool #t32 = #0#2#isSet = true in #0#2 = #0#0.{core::Map::containsKey}(#C3){(core::Object?) → core::bool})) && #C5 =={core::String::==}{(core::Object) → core::bool} (#0#3#isSet ?{core::String?} #0#3{core::String?} : let final core::bool #t33 = #0#3#isSet = true in #0#3 = #0#0.{core::Map::[]}(#C3){(core::Object?) → core::String?})) { { return 1; } @@ -260,15 +204,14 @@ static method expect(dynamic expected, dynamic actual, dynamic message) → dyna constants { #C1 = null - #C2 = static-tearoff col::MapBase::_id - #C3 = [] - #C4 = 1 - #C5 = "foo" - #C6 = "bar" + #C2 = [] + #C3 = 1 + #C4 = "foo" + #C5 = "bar" } Extra constant evaluation status: Evaluated: IsExpression @ org-dartlang-testcase:///caching_constants.dart:7:49 -> BoolConstant(false) Evaluated: IsExpression @ org-dartlang-testcase:///caching_constants.dart:38:12 -> BoolConstant(true) Evaluated: IsExpression @ org-dartlang-testcase:///caching_constants.dart:40:12 -> BoolConstant(true) -Extra constant evaluation: evaluated: 513, effectively constant: 3 +Extra constant evaluation: evaluated: 428, effectively constant: 3 diff --git a/pkg/front_end/testcases/patterns/matching_and_capturing_accesses_list_element_once.dart.strong.transformed.expect b/pkg/front_end/testcases/patterns/matching_and_capturing_accesses_list_element_once.dart.strong.transformed.expect index d76b0079c71d..0b1ed84102bd 100644 --- a/pkg/front_end/testcases/patterns/matching_and_capturing_accesses_list_element_once.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/patterns/matching_and_capturing_accesses_list_element_once.dart.strong.transformed.expect @@ -507,11 +507,6 @@ abstract class _A&Object&ListMixin extends core::Object implements col::ListBase return new _in::ReversedListIterable::•(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → core::String return col::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → core::int { - return core::Comparable::compare(a as core::Comparable, b as core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(core::List list) → core::String - return core::Iterable::iterableToFullString(list, "[", "]"); } class A extends self::_A&Object&ListMixin { field core::int count = 0; @@ -571,4 +566,4 @@ Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:462:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:471:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:480:12 -> IntConstant(-1) -Extra constant evaluation: evaluated: 1108, effectively constant: 4 +Extra constant evaluation: evaluated: 1101, effectively constant: 4 diff --git a/pkg/front_end/testcases/patterns/negative_length.dart.strong.transformed.expect b/pkg/front_end/testcases/patterns/negative_length.dart.strong.transformed.expect index 447ba392381b..59594186d2c4 100644 --- a/pkg/front_end/testcases/patterns/negative_length.dart.strong.transformed.expect +++ b/pkg/front_end/testcases/patterns/negative_length.dart.strong.transformed.expect @@ -507,11 +507,6 @@ abstract class _NegativeLengthList&Object&ListMixin(this); method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ toString() → core::String return col::ListBase::listToString(this); - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ _compareAny(dynamic a, dynamic b) → core::int { - return core::Comparable::compare(a as core::Comparable, b as core::Comparable); - } - static method /* from org-dartlang-sdk:///sdk/lib/collection/list.dart */ listToString(core::List list) → core::String - return core::Iterable::iterableToFullString(list, "[", "]"); } class NegativeLengthList extends self::_NegativeLengthList&Object&ListMixin { final field core::List _list; @@ -588,4 +583,4 @@ Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:471:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-sdk:///sdk/lib/collection/list.dart:480:12 -> IntConstant(-1) Evaluated: InstanceInvocation @ org-dartlang-testcase:///negative_length.dart:12:41 -> IntConstant(-1) -Extra constant evaluation: evaluated: 1128, effectively constant: 5 +Extra constant evaluation: evaluated: 1121, effectively constant: 5 diff --git a/pkg/vm/lib/modular/transformations/mixin_full_resolution.dart b/pkg/vm/lib/modular/transformations/mixin_full_resolution.dart index cb00ec926afe..b9d84909f7df 100644 --- a/pkg/vm/lib/modular/transformations/mixin_full_resolution.dart +++ b/pkg/vm/lib/modular/transformations/mixin_full_resolution.dart @@ -122,6 +122,9 @@ class MixinFullResolution { } for (var field in class_.mixin.fields) { + if (field.isStatic) { + continue; + } Reference? fieldReference = indexedClass?.lookupFieldReference(field.name); Reference? getterReference = @@ -161,6 +164,7 @@ class MixinFullResolution { int originalLength = class_.procedures.length; outer: for (var procedure in class_.mixin.procedures) { + if (procedure.isStatic) continue; if (procedure.isSynthetic) continue; // Forwarding stubs in the mixin class are used when calling through the // mixin class's interface, not when calling through the mixin diff --git a/pkg/vm/lib/transformations/type_flow/transformer.dart b/pkg/vm/lib/transformations/type_flow/transformer.dart index 18d1031dc78e..05ffb3dcb959 100644 --- a/pkg/vm/lib/transformations/type_flow/transformer.dart +++ b/pkg/vm/lib/transformations/type_flow/transformer.dart @@ -1983,17 +1983,18 @@ class _TreeShakerPass2 extends RemovingTransformer { if (!shaker.isClassUsedInType(node)) { debugPrint('Dropped supers from class ${node.name}'); - // The class is only a namespace for static members. Remove its - // hierarchy information. This is mandatory, since these references - // might otherwise become dangling. + // The class is only a namespace for static members or + // unreachable members annotated with entry point pragmas. + // Remove its hierarchy information. This is mandatory, + // since these references might otherwise become dangling. node.supertype = shaker .typeFlowAnalysis.environment.coreTypes.objectClass.asRawSupertype; node.implementedTypes.clear(); node.typeParameters.clear(); node.isAbstract = true; node.isEnum = false; - // Mixin applications cannot have static members. - assert(node.mixedInType == null); + node.isEliminatedMixin = false; + node.mixedInType = null; node.annotations = const []; } diff --git a/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart b/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart new file mode 100644 index 000000000000..dbbc63869872 --- /dev/null +++ b/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// Regression test for https://github.com/flutter/flutter/issues/160030. +// Verifies the result of tree shaking of mixin application when mixin +// has members with entry-point pragma. + +mixin M { + @pragma('vm:entry-point') + static void foo() { + print('hi'); + } +} + +class Y with M {} + +mixin M2 { + @pragma('vm:entry-point') + void bar() { + print('hi'); + } +} + +class Z with M2 {} + +void main() {} diff --git a/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart.expect b/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart.expect new file mode 100644 index 000000000000..6a4387bea80d --- /dev/null +++ b/pkg/vm/testcases/transformations/type_flow/transformer/regress_flutter160030.dart.expect @@ -0,0 +1,33 @@ +library #lib; +import self as self; +import "dart:core" as core; + +abstract class M extends core::Object /*isMixinDeclaration*/ { + + [@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] + [@vm.unboxing-info.metadata=[!regcc]] + @#C3 + static method foo() → void { + core::print("hi"); + } +} +abstract class M2 extends core::Object /*isMixinDeclaration*/ { + + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasNonThisUses:false,hasTearOffUses:false,methodOrSetterSelectorId:1,getterSelectorId:2] + @#C3 + abstract method bar() → void; +} +abstract class _Z&Object&M2 extends core::Object /*isAnonymousMixin,hasConstConstructor*/ { + + [@vm.procedure-attributes.metadata=methodOrSetterCalledDynamically:false,getterCalledDynamically:false,hasThisUses:false,hasNonThisUses:false,hasTearOffUses:false,methodOrSetterSelectorId:3,getterSelectorId:4] + @#C3 + abstract method bar() → void; +} + +[@vm.inferred-return-type.metadata=dart.core::Null? (value: null)] +static method main() → void {} +constants { + #C1 = "vm:entry-point" + #C2 = null + #C3 = core::pragma {name:#C1, options:#C2} +} diff --git a/runtime/vm/kernel_loader.cc b/runtime/vm/kernel_loader.cc index 50e6d7fae2c3..34b16ac851f4 100644 --- a/runtime/vm/kernel_loader.cc +++ b/runtime/vm/kernel_loader.cc @@ -1310,6 +1310,7 @@ void KernelLoader::LoadPreliminaryClass(ClassHelper* class_helper, klass->set_is_abstract(); } if (class_helper->is_transformed_mixin_application()) { + ASSERT(interface_count > 0); klass->set_is_transformed_mixin_application(); } if (class_helper->has_const_constructor()) { diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc index 28fd80032909..fd57986d5bf7 100644 --- a/runtime/vm/object.cc +++ b/runtime/vm/object.cc @@ -3126,6 +3126,7 @@ const char* Class::NameCString(NameVisibility name_visibility) const { ClassPtr Class::Mixin() const { if (is_transformed_mixin_application()) { const Array& interfaces = Array::Handle(this->interfaces()); + ASSERT(interfaces.Length() > 0); const Type& mixin_type = Type::Handle(Type::RawCast(interfaces.At(interfaces.Length() - 1))); return mixin_type.type_class(); From 8d851b17c5dcc58f3033831f1fdd5783f125c5d9 Mon Sep 17 00:00:00 2001 From: Devon Carew Date: Mon, 13 Jan 2025 08:59:54 -0800 Subject: [PATCH 02/76] Bump dartdoc to e1295863b11c54680bf178ec9c2662a33b0e24be Changes: ``` > git log --format="%C(auto) %h %s" c7f1160..e129586 https://dart.googlesource.com/dartdoc.git/+/e1295863 Fix the check for the expected number of categorized libraries in Dart SDK (3962) https://dart.googlesource.com/dartdoc.git/+/591173b9 Fix enum links for exported enums (3957) https://dart.googlesource.com/dartdoc.git/+/c8dd09cb More cleanup from removal of SpecialClasses (3955) https://dart.googlesource.com/dartdoc.git/+/b082872d Bump the github-actions group with 3 updates (3954) https://dart.googlesource.com/dartdoc.git/+/30be5783 Bump dart_style to 3.0.0 (3950) https://dart.googlesource.com/dartdoc.git/+/65240335 Fix most comment reference issues (3946) https://dart.googlesource.com/dartdoc.git/+/51256a37 Avoid the PackageGraph.objectClass field. (3951) https://dart.googlesource.com/dartdoc.git/+/c8be8454 Combine two enums test classes into one. (3949) https://dart.googlesource.com/dartdoc.git/+/3d16206f Bump to version 8.3.1 (3944) https://dart.googlesource.com/dartdoc.git/+/e3ecb4d0 Append the href of each library with a slash (3940) https://dart.googlesource.com/dartdoc.git/+/7444b397 Bump the github-actions group with 2 updates (3938) https://dart.googlesource.com/dartdoc.git/+/ced0209e Split existing CSS styles into multiple scss partials (3920) ``` Diff: https://dart.googlesource.com/dartdoc.git/+/c7f11603effa88ddacabfd555993f322fca8b3fe..e1295863b11c54680bf178ec9c2662a33b0e24be/ Change-Id: I1b30aec2bb4aca4dff781f84fa45df91e6ca9904 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403941 Commit-Queue: Devon Carew Reviewed-by: Samuel Rawlins --- DEPS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEPS b/DEPS index 9a8e623fe1b5..1c3ac9a448f8 100644 --- a/DEPS +++ b/DEPS @@ -131,7 +131,7 @@ vars = { # EOL comment after a dependency to disable this and pin it at its current # revision. "core_rev": "7a71ad6b9170e09d5cbe39f3fccdee648659f1e7", - "dartdoc_rev": "c7f11603effa88ddacabfd555993f322fca8b3fe", + "dartdoc_rev": "e1295863b11c54680bf178ec9c2662a33b0e24be", "ecosystem_rev": "efe4ee4af6ac2e4c90aa525fae213b65c97295a9", "flute_rev": "e4ea0459a7debae5e9592c85141707b01fac86c9", "glob_rev": "eee18d1a577d5f965f6afbbd251798e065dced43", From 0f15e32ad3551ca492a5a7c62d9182d1e4fd4627 Mon Sep 17 00:00:00 2001 From: Mayank Patke Date: Mon, 13 Jan 2025 10:04:31 -0800 Subject: [PATCH 03/76] [DEPS] Update web browsers Change-Id: Ie4d6ec2ea4f43582d1e69dacb151ffb5bd02d492 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403931 Auto-Submit: Mayank Patke Commit-Queue: Nicholas Shahan Reviewed-by: Nicholas Shahan --- DEPS | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/DEPS b/DEPS index 1c3ac9a448f8..e99f37a21952 100644 --- a/DEPS +++ b/DEPS @@ -71,9 +71,9 @@ vars = { # self-service update these by following the go/dart-engprod/browsers.md # instructions. d8, the V8 shell, is always checked out. "checkout_javascript_engines": False, - "d8_tag": "version:13.3.255", - "jsshell_tag": "version:133.0", - "jsc_tag": "version:287397", + "d8_tag": "version:13.4.32", + "jsshell_tag": "version:134.0", + "jsc_tag": "version:288804", # https://chrome-infra-packages.appspot.com/p/fuchsia/third_party/clang "clang_version": "git_revision:684052173971868aab0e6b62d7770a6299e84141", @@ -180,9 +180,9 @@ vars = { # meant to be downloaded by users for local testing. You can self-service # update these by following the go/dart-engprod/browsers.md instructions. "download_chrome": False, - "chrome_tag": "132.0.6834.57", + "chrome_tag": "132.0.6834.83", "download_firefox": False, - "firefox_tag": "133.0.3", + "firefox_tag": "134.0", # Emscripten is used in dart2wasm tests. "download_emscripten": False, From efda4aff7cb5cdca3237a52e5fb6c805f4403c5a Mon Sep 17 00:00:00 2001 From: Ryan Macnak Date: Mon, 13 Jan 2025 10:57:09 -0800 Subject: [PATCH 04/76] Add GN target to build Debian package from regular output. Bug: https://github.com/dart-lang/sdk/issues/26953 Cq-Include-Trybots: luci.dart.try:dart-sdk-linux-arm64-try,dart-sdk-linux-riscv64-try,dart-sdk-linux-try Change-Id: I38dfcadee836733c2e8824c2da21b9619dd2fc77 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/281307 Reviewed-by: Alexander Thomas Commit-Queue: Ryan Macnak --- BUILD.gn | 3 + tools/debian_package/BUILD.gn | 47 +++++++++++++ tools/debian_package/create_debian_package.py | 69 +++++++++++++++++++ tools/debian_package/debian/compat | 1 + tools/debian_package/debian/control | 11 +++ tools/debian_package/debian/dart.install | 2 + tools/debian_package/debian/dart.links | 2 + tools/debian_package/debian/rules | 35 ++++++++++ tools/debian_package/debian/source/format | 1 + tools/debian_package/get_version.py | 20 ++++++ 10 files changed, 191 insertions(+) create mode 100644 tools/debian_package/BUILD.gn create mode 100755 tools/debian_package/create_debian_package.py create mode 100644 tools/debian_package/debian/compat create mode 100644 tools/debian_package/debian/control create mode 100644 tools/debian_package/debian/dart.install create mode 100644 tools/debian_package/debian/dart.links create mode 100755 tools/debian_package/debian/rules create mode 100644 tools/debian_package/debian/source/format create mode 100755 tools/debian_package/get_version.py diff --git a/BUILD.gn b/BUILD.gn index 133f8e43f98e..59b46d4365ca 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -119,6 +119,9 @@ group("runtime_precompiled") { group("create_sdk") { public_deps = [ "sdk:create_sdk" ] + if (is_linux) { + public_deps += [ "tools/debian_package" ] + } } group("create_platform_sdk") { diff --git a/tools/debian_package/BUILD.gn b/tools/debian_package/BUILD.gn new file mode 100644 index 000000000000..3aeaeb02013c --- /dev/null +++ b/tools/debian_package/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +if (is_linux) { + action("debian_package") { + version = exec_script("get_version.py", [], "trim string") + if (target_cpu == "x86" || target_cpu == "ia32") { + debian_arch = "i386" + lib_dir = "//buildtools/sysroot/linux/lib/i386-linux-gnu" + } else if (target_cpu == "x64") { + debian_arch = "amd64" + lib_dir = "//buildtools/sysroot/linux/lib/x86_64-linux-gnu" + } else if (target_cpu == "arm") { + debian_arch = "armhf" + lib_dir = "//buildtools/sysroot/linux/lib/arm-linux-gnueabihf" + } else if (target_cpu == "arm64") { + debian_arch = "arm64" + lib_dir = "//buildtools/sysroot/linux/lib/aarch64-linux-gnu" + } else if (target_cpu == "riscv64") { + debian_arch = "riscv64" + lib_dir = "//buildtools/sysroot/focal/lib/riscv64-linux-gnu/" + } else { + assert(false, "Don't know Debian name for $target_cpu") + } + + deps = [ "../../sdk:create_sdk" ] + inputs = [ + "create_debian_package.py", + "debian/compat", + "debian/control", + "debian/dart.install", + "debian/dart.links", + "debian/rules", + "debian/source/format", + ] + outputs = [ "$root_out_dir/dart_${version}-1_${debian_arch}.deb" ] + script = "../../build/gn_run_binary.py" + args = [ + "compiled_action", + rebase_path("create_debian_package.py"), + "--version=$version", + "--arch=$debian_arch", + "--lib_dir=" + rebase_path(lib_dir), + ] + } +} diff --git a/tools/debian_package/create_debian_package.py b/tools/debian_package/create_debian_package.py new file mode 100755 index 000000000000..4c6cb9bd1200 --- /dev/null +++ b/tools/debian_package/create_debian_package.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import optparse +import os +import shutil +import subprocess +import sys +from os.path import join, split, abspath, dirname + +sys.path.append(join(dirname(__file__), '..')) +import utils + +DART_DIR = abspath(join(dirname(__file__), '..', '..')) + + +def BuildOptions(): + result = optparse.OptionParser() + result.add_option("--version", default=None) + result.add_option("--arch", default=None) + result.add_option("--lib_dir", default=None) + return result + + +def GenerateCopyright(filename): + with open(join(DART_DIR, 'LICENSE')) as lf: + license_lines = lf.readlines() + + with open(filename, 'w') as f: + f.write('Name: dart\n') + f.write('Maintainer: Dart Team \n') + f.write('Source: https://dart.googlesource.com/sdk\n') + f.write('License:\n') + for line in license_lines: + f.write(' %s' % line) # Line already contains trailing \n. + + +def GenerateChangeLog(filename, version): + with open(filename, 'w') as f: + f.write('dart (%s-1) UNRELEASED; urgency=low\n' % version) + f.write('\n') + f.write(' * Generated file.\n') + f.write('\n') + f.write(' -- Dart Team \n') + + +def Main(): + parser = BuildOptions() + (options, args) = parser.parse_args() + + version = options.version + versiondir = 'dart-%s' % version + shutil.copytree(join(DART_DIR, 'tools', 'debian_package', 'debian'), + join(versiondir, 'debian'), + dirs_exist_ok=True) + GenerateCopyright(join(versiondir, 'debian', 'copyright')) + GenerateChangeLog(join(versiondir, 'debian', 'changelog'), version) + + cmd = ['dpkg-buildpackage', '-B', '-a', options.arch, '-us', '-uc'] + env = os.environ.copy() + env["LIB_DIR"] = options.lib_dir + process = subprocess.check_call(cmd, cwd=versiondir, env=env) + + +if __name__ == '__main__': + sys.exit(Main()) diff --git a/tools/debian_package/debian/compat b/tools/debian_package/debian/compat new file mode 100644 index 000000000000..f599e28b8ab0 --- /dev/null +++ b/tools/debian_package/debian/compat @@ -0,0 +1 @@ +10 diff --git a/tools/debian_package/debian/control b/tools/debian_package/debian/control new file mode 100644 index 000000000000..94d45b4eacab --- /dev/null +++ b/tools/debian_package/debian/control @@ -0,0 +1,11 @@ +Source: dart +Maintainer: Dart Team +Section: misc +Priority: optional +Standards-Version: 3.9.2 +Build-Depends: python3:native + +Package: dart +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: Dart SDK diff --git a/tools/debian_package/debian/dart.install b/tools/debian_package/debian/dart.install new file mode 100644 index 000000000000..0ea869a3aa60 --- /dev/null +++ b/tools/debian_package/debian/dart.install @@ -0,0 +1,2 @@ +debian/tmp/out/dart usr/lib + diff --git a/tools/debian_package/debian/dart.links b/tools/debian_package/debian/dart.links new file mode 100644 index 000000000000..30c3b93ec3f7 --- /dev/null +++ b/tools/debian_package/debian/dart.links @@ -0,0 +1,2 @@ +usr/lib/dart/bin/dart usr/bin/dart + diff --git a/tools/debian_package/debian/rules b/tools/debian_package/debian/rules new file mode 100755 index 000000000000..c9857cf2f872 --- /dev/null +++ b/tools/debian_package/debian/rules @@ -0,0 +1,35 @@ +#!/usr/bin/make -f +export DH_VERBOSE = 1 + +%: + dh $@ + +# Nop +override_dh_auto_clean: + +# Nop +override_dh_auto_configure: + +# Nop +override_dh_auto_build: + +# Nop +override_dh_auto_test: + +# Nop +override_dh_strip: + +# Nop +override_dh_strip_nondeterminism: + +# This override allows us to ignore spurious missing library errors when +# cross-compiling. +override_dh_shlibdeps: + dh_shlibdeps --dpkg-shlibdeps-params=--ignore-missing-info -l "${LIB_DIR}" + +override_dh_auto_install: + mkdir -p debian/tmp/out + cp -R ../dart-sdk debian/tmp/out + mv debian/tmp/out/dart-sdk debian/tmp/out/dart + dh_install + dh_link diff --git a/tools/debian_package/debian/source/format b/tools/debian_package/debian/source/format new file mode 100644 index 000000000000..163aaf8d82b6 --- /dev/null +++ b/tools/debian_package/debian/source/format @@ -0,0 +1 @@ +3.0 (quilt) diff --git a/tools/debian_package/get_version.py b/tools/debian_package/get_version.py new file mode 100755 index 000000000000..4a43d06c291b --- /dev/null +++ b/tools/debian_package/get_version.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file +# for details. All rights reserved. Use of this source code is governed by a +# BSD-style license that can be found in the LICENSE file. + +import sys +from os import listdir +from os.path import join, split, abspath, dirname + +sys.path.append(join(dirname(__file__), '..')) +import utils + + +def Main(): + print(utils.GetVersion()) + + +if __name__ == '__main__': + sys.exit(Main()) From cee59be7560f5906a82dc9330e756dbf1a218340 Mon Sep 17 00:00:00 2001 From: DEPS Autoroller Date: Mon, 13 Jan 2025 11:17:25 -0800 Subject: [PATCH 05/76] Roll Fuchsia SDK from 26.20241231.3.1 to 26.20250106.5.1 If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/fuchsia-sdk-dart-sdk Please CC dart-engprod@google.com,dart-vm-gardener@grotations.appspotmail.com,dart-vm-team@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Fuchsia SDK: https://bugs.fuchsia.dev/p/fuchsia/issues/list To file a bug in Dart SDK: https://github.com/dart-lang/sdk/issues To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Cq-Include-Trybots: luci.dart.try:vm-fuchsia-release-x64-try;luci.dart.try:vm-fuchsia-release-arm64-try Change-Id: If8b30ff12473f76b31668015717b25802cf3dcf9 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403221 Reviewed-by: Alexander Aprelev Reviewed-by: Ryan Macnak Commit-Queue: Alexander Aprelev --- DEPS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEPS b/DEPS index e99f37a21952..0103dd3c7aaf 100644 --- a/DEPS +++ b/DEPS @@ -85,7 +85,7 @@ vars = { "download_reclient": True, # Update from https://chrome-infra-packages.appspot.com/p/fuchsia/sdk/core - "fuchsia_sdk_version": "version:26.20241231.3.1", + "fuchsia_sdk_version": "version:26.20250106.5.1", "download_fuchsia_deps": False, # Ninja, runs the build based on files generated by GN. From 0f82db5a9ccaaab61a8135367a9120336f7b587f Mon Sep 17 00:00:00 2001 From: DEPS Autoroller Date: Mon, 13 Jan 2025 11:21:50 -0800 Subject: [PATCH 06/76] Roll Fuchsia Test Scripts from r9Dc5VRF6sE3pJH20... to 3SIihrAqX5c1w3ep7... If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/fuchsia-test-scripts-dart-sdk Please CC chrome-fuchsia-engprod@google.com,dart-vm-gardener@grotations.appspotmail.com on the revert to ensure that a human is aware of the problem. To file a bug in Fuchsia Test Scripts: https://bugs.fuchsia.dev/p/fuchsia/issues/list To file a bug in Dart SDK: https://github.com/dart-lang/sdk/issues To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md Cq-Include-Trybots: luci.dart.try:vm-fuchsia-release-x64-try;luci.dart.try:vm-fuchsia-release-arm64-try Change-Id: I354ba9420cd210fcc058f294d1c7c1306079a725 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403061 Reviewed-by: Ryan Macnak Commit-Queue: Alexander Aprelev Reviewed-by: Alexander Aprelev --- DEPS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DEPS b/DEPS index 0103dd3c7aaf..05af62964bf5 100644 --- a/DEPS +++ b/DEPS @@ -610,7 +610,7 @@ deps = { "packages": [ { "package": "chromium/fuchsia/test-scripts", - "version": "r9Dc5VRF6sE3pJH20k2d1Yko3xSlwljH_nuw7O8vcb4C", + "version": "3SIihrAqX5c1w3ep7-s9Yi4qLUITve0PUVs6COrU-eIC", } ], "condition": 'download_fuchsia_deps', From 22fe1947d24e51c2c57235a0dc1b60ddb6976221 Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 11:30:19 -0800 Subject: [PATCH 07/76] Elements. Migrate ThisLookup and LexicalLookup. Change-Id: I29d36ed43907871a0ffed8bd71619ef55a336530 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404240 Commit-Queue: Konstantin Shcheglov Reviewed-by: Phil Quitslund --- .../lib/src/dart/element/element.dart | 35 ++++++++++++-- .../lib/src/dart/resolver/lexical_lookup.dart | 18 ++++--- .../resolver/property_element_resolver.dart | 6 +-- .../lib/src/dart/resolver/this_lookup.dart | 10 ++-- .../lib/src/utilities/extensions/element.dart | 48 +++++++++---------- 5 files changed, 71 insertions(+), 46 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index 4efd68c9edb8..8d4c8c67a5c3 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -1661,6 +1661,11 @@ class ConstructorElementImpl2 extends ExecutableElementImpl2 @override ElementKind get kind => ElementKind.CONSTRUCTOR; + @override + ConstructorElementImpl get lastFragment { + return super.lastFragment as ConstructorElementImpl; + } + @override Element2 get nonSynthetic2 { if (isSynthetic) { @@ -3855,6 +3860,17 @@ abstract class ExecutableElementImpl2 extends FunctionTypedElementImpl2 return firstFragment.hasModifier(Modifier.INVOKES_SUPER_SELF); } + ExecutableElementImpl get lastFragment { + var result = firstFragment as ExecutableElementImpl; + while (true) { + if (result.nextFragment case ExecutableElementImpl nextFragment) { + result = nextFragment; + } else { + return result; + } + } + } + @override LibraryElement2 get library2 { var firstFragment = this.firstFragment as ExecutableElementImpl; @@ -5601,9 +5617,7 @@ abstract class InstanceElementImpl2 extends ElementImpl2 @override List get typeParameters2 => - firstFragment.typeParameters - .map((fragment) => fragment.element) - .toList(); + firstFragment.typeParameters.map((fragment) => fragment.element).toList(); @override String displayString2( @@ -8124,6 +8138,11 @@ class MethodElementImpl2 extends ExecutableElementImpl2 @override ElementKind get kind => ElementKind.METHOD; + @override + MethodElementImpl get lastFragment { + return super.lastFragment as MethodElementImpl; + } + @override String? get lookupName { if (name3 == '-' && formalParameters.isEmpty) { @@ -9762,6 +9781,11 @@ abstract class PropertyAccessorElementImpl2 extends ExecutableElementImpl2 @override bool get isExternal => firstFragment.isExternal; + @override + PropertyAccessorElementImpl get lastFragment { + return super.lastFragment as PropertyAccessorElementImpl; + } + @override String? get name3 => firstFragment.name2; @@ -10320,6 +10344,11 @@ class TopLevelFunctionElementImpl extends ExecutableElementImpl2 @override ElementKind get kind => ElementKind.FUNCTION; + @override + FunctionElementImpl get lastFragment { + return super.lastFragment as FunctionElementImpl; + } + @override LibraryElement2 get library2 { return firstFragment.library2!; diff --git a/pkg/analyzer/lib/src/dart/resolver/lexical_lookup.dart b/pkg/analyzer/lib/src/dart/resolver/lexical_lookup.dart index 5d64d65e6e50..fd8e0a450bcf 100644 --- a/pkg/analyzer/lib/src/dart/resolver/lexical_lookup.dart +++ b/pkg/analyzer/lib/src/dart/resolver/lexical_lookup.dart @@ -2,9 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/scope.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/extensions.dart'; @@ -21,8 +19,8 @@ class LexicalLookup { /// a getter. If a matching element is found, a [LexicalLookupResult] is /// returned. Otherwise `null` is returned. static LexicalLookupResult? resolveGetter(ScopeLookupResult scopeResult) { - var scopeGetter = scopeResult.getter; - var scopeSetter = scopeResult.setter; + var scopeGetter = scopeResult.getter2; + var scopeSetter = scopeResult.setter2; if (scopeGetter != null || scopeSetter != null) { if (scopeGetter != null) { return LexicalLookupResult(requested: scopeGetter); @@ -39,10 +37,10 @@ class LexicalLookup { /// a setter. If a matching element is found, a [LexicalLookupResult] is /// returned. Otherwise `null` is returned. static LexicalLookupResult? resolveSetter(ScopeLookupResult scopeResult) { - var scopeGetter = scopeResult.getter; - var scopeSetter = scopeResult.setter; + var scopeGetter = scopeResult.getter2; + var scopeSetter = scopeResult.setter2; if (scopeGetter != null || scopeSetter != null) { - if (scopeGetter is VariableElement) { + if (scopeGetter is VariableElement2) { return LexicalLookupResult(requested: scopeGetter); } if (scopeSetter != null) { @@ -58,8 +56,8 @@ class LexicalLookup { } class LexicalLookupResult { - final Element? requested; - final Element? recovery; + final Element2? requested; + final Element2? recovery; /// The type, usually [FunctionType] referenced with `call`. final DartType? callFunctionType; diff --git a/pkg/analyzer/lib/src/dart/resolver/property_element_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/property_element_resolver.dart index 5e99d32d3ecd..f7de9083e07f 100644 --- a/pkg/analyzer/lib/src/dart/resolver/property_element_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/property_element_resolver.dart @@ -266,7 +266,7 @@ class PropertyElementResolver with ScopeHelpers { ); } - readElementRequested = readLookup?.requested; + readElementRequested = readLookup?.requested.asElement; if (readElementRequested is PropertyAccessorElement && !readElementRequested.isStatic) { var unpromotedType = readElementRequested.returnType; @@ -285,8 +285,8 @@ class PropertyElementResolver with ScopeHelpers { if (hasWrite) { var writeLookup = LexicalLookup.resolveSetter(scopeLookupResult) ?? _resolver.thisLookupSetter(node); - writeElementRequested = writeLookup?.requested; - writeElementRecovery = writeLookup?.recovery; + writeElementRequested = writeLookup?.requested.asElement; + writeElementRecovery = writeLookup?.recovery.asElement; AssignmentVerifier(errorReporter).verify( node: node, diff --git a/pkg/analyzer/lib/src/dart/resolver/this_lookup.dart b/pkg/analyzer/lib/src/dart/resolver/this_lookup.dart index dba10f8b210c..222d81193944 100644 --- a/pkg/analyzer/lib/src/dart/resolver/this_lookup.dart +++ b/pkg/analyzer/lib/src/dart/resolver/this_lookup.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/src/dart/resolver/lexical_lookup.dart'; import 'package:analyzer/src/generated/resolver.dart'; @@ -51,11 +49,11 @@ class ThisLookup { ); } - var getterElement = propertyResult.getter; + var getterElement = propertyResult.getter2; if (getterElement != null) { return LexicalLookupResult(requested: getterElement); } else { - return LexicalLookupResult(recovery: propertyResult.setter); + return LexicalLookupResult(recovery: propertyResult.setter2); } } @@ -80,11 +78,11 @@ class ThisLookup { nameErrorEntity: node, ); - var setterElement = propertyResult.setter; + var setterElement = propertyResult.setter2; if (setterElement != null) { return LexicalLookupResult(requested: setterElement); } else { - return LexicalLookupResult(recovery: propertyResult.getter); + return LexicalLookupResult(recovery: propertyResult.getter2); } } } diff --git a/pkg/analyzer/lib/src/utilities/extensions/element.dart b/pkg/analyzer/lib/src/utilities/extensions/element.dart index a3662124a75e..0980624c1288 100644 --- a/pkg/analyzer/lib/src/utilities/extensions/element.dart +++ b/pkg/analyzer/lib/src/utilities/extensions/element.dart @@ -51,7 +51,7 @@ extension ConstructorElement2Extension on ConstructorElement2 { if (this case ConstructorMember member) { return member; } - return baseElement.firstFragment as ConstructorElement; + return (this as ConstructorElementImpl2).lastFragment; } } @@ -142,46 +142,46 @@ extension Element2OrNullExtension on Element2? { switch (self) { case null: return null; - case ConstructorElementImpl2(): - return self.firstFragment as Element; + case ConstructorElementImpl2 element2: + return element2.asElement; case DynamicElementImpl2(): return self.firstFragment; - case ExecutableMember(): - return self.declaration as Element; - case ExtensionElementImpl2(): - return self.firstFragment as Element; - case FieldElementImpl2(): - return self.firstFragment as Element; + case ExecutableMember element2: + return element2.asElement; + case ExtensionElementImpl2 element2: + return element2.asElement; + case FieldElementImpl2 element2: + return element2.asElement; case FieldMember(): return self.declaration as Element; case FormalParameterElement element2: return element2.asElement; - case GetterElementImpl(): - return self.firstFragment as Element; + case GetterElementImpl element2: + return element2.asElement; case LabelElementImpl2 element2: return element2.asElement; case LibraryElementImpl(): return self as Element; case LibraryImportElementImpl(): return self as Element; - case LocalFunctionElementImpl(): - return self.wrappedElement as Element; + case LocalFunctionElementImpl element2: + return element2.asElement; case LocalVariableElementImpl2(): return self.wrappedElement as Element; - case MethodElementImpl2(): - return self.firstFragment as Element; + case MethodElementImpl2 element2: + return element2.asElement; case MultiplyDefinedElementImpl2 element2: return element2.asElement; case NeverElementImpl2(): return NeverElementImpl.instance; case PrefixElement2 element2: return element2.asElement; - case SetterElementImpl(): - return self.firstFragment as Element; - case TopLevelFunctionElementImpl(): - return self.firstFragment as Element; - case TopLevelVariableElementImpl2(): - return self.firstFragment as Element; + case SetterElementImpl element2: + return element2.asElement; + case TopLevelFunctionElementImpl element2: + return element2.asElement; + case TopLevelVariableElementImpl2 element2: + return element2.asElement; case TypeDefiningElement2(): return self.firstFragment as Element; default: @@ -454,7 +454,7 @@ extension MethodElement2Extension on MethodElement2 { if (this case MethodMember member) { return member; } - return baseElement.firstFragment as MethodElement; + return (this as MethodElementImpl2).lastFragment; } } @@ -511,7 +511,7 @@ extension PropertyAccessorElement2Extension on PropertyAccessorElement2 { if (this case PropertyAccessorMember member) { return member; } - return firstFragment as PropertyAccessorElement; + return (this as PropertyAccessorElementImpl2).lastFragment; } } @@ -527,7 +527,7 @@ extension PropertyAccessorElementExtension on PropertyAccessorElement { extension TopLevelFunctionElementExtension on TopLevelFunctionElement { FunctionElement get asElement { - return firstFragment as FunctionElement; + return (this as TopLevelFunctionElementImpl).lastFragment; } } From 077a4c3545f3c78d9f29da68a6af22e367875a58 Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 11:38:23 -0800 Subject: [PATCH 08/76] Elements. Migrate SinceSdkVersionComputer. Change-Id: Iecc9e796903e3c3791db42b4678ee2511477e7fb Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403928 Commit-Queue: Konstantin Shcheglov Reviewed-by: Phil Quitslund --- pkg/analyzer/lib/dart/element/element2.dart | 68 +++++---- .../lib/src/dart/element/element.dart | 131 ++++++++++++------ .../src/dart/element/since_sdk_version.dart | 73 ++-------- .../lib/src/hint/sdk_constraint_verifier.dart | 4 +- .../test/src/summary/element_text.dart | 36 +++-- .../elements/since_sdk_version_test.dart | 34 ++--- 6 files changed, 175 insertions(+), 171 deletions(-) diff --git a/pkg/analyzer/lib/dart/element/element2.dart b/pkg/analyzer/lib/dart/element/element2.dart index 55ec4f875078..7c4c221889f6 100644 --- a/pkg/analyzer/lib/dart/element/element2.dart +++ b/pkg/analyzer/lib/dart/element/element2.dart @@ -256,7 +256,8 @@ abstract class ClassFragment implements InterfaceFragment { /// type. /// /// Clients may not extend, implement or mix-in this class. -abstract class ConstructorElement2 implements ExecutableElement2 { +abstract class ConstructorElement2 + implements ExecutableElement2, HasSinceSdkVersion { @override ConstructorElement2 get baseElement; @@ -845,7 +846,11 @@ abstract class FieldFragment implements PropertyInducingFragment { /// /// Clients may not extend, implement or mix-in this class. abstract class FormalParameterElement - implements PromotableElement2, Annotatable, LocalElement2 { + implements + PromotableElement2, + Annotatable, + HasSinceSdkVersion, + LocalElement2 { @override FormalParameterElement get baseElement; @@ -1140,11 +1145,35 @@ abstract class GetterFragment implements PropertyAccessorFragment { // GetterElement get element; } +/// The interface that is implemented by elements that can have `@Since()` +/// annotation. +abstract class HasSinceSdkVersion { + /// The version where the associated SDK API was added. + /// + /// A `@Since()` annotation can be applied to a library declaration, + /// any public declaration in a library, or in a class, or to an optional + /// parameter, etc. + /// + /// The returned version is "effective", so that if a library is annotated + /// then all elements of the library inherit it; or if a class is annotated + /// then all members and constructors of the class inherit it. + /// + /// If multiple `@Since()` annotations apply to the same element, the latest + /// version takes precedence. + /// + /// Returns `null` if the element is not declared in the SDK, or doesn't have + /// a `@Since()` annotation applied to it. + Version? get sinceSdkVersion; +} + /// An element whose instance members can refer to `this`. /// /// Clients may not extend, implement or mix-in this class. abstract class InstanceElement2 - implements TypeDefiningElement2, TypeParameterizedElement2 { + implements + TypeDefiningElement2, + TypeParameterizedElement2, + HasSinceSdkVersion { @override LibraryElement2 get enclosingElement2; @@ -1474,7 +1503,8 @@ abstract class LabelFragment implements Fragment { /// A library. /// /// Clients may not extend, implement or mix-in this class. -abstract class LibraryElement2 implements Element2, Annotatable { +abstract class LibraryElement2 + implements Element2, Annotatable, HasSinceSdkVersion { /// The classes defined in this library. /// /// There is no guarantee of the order in which the classes will be returned. @@ -1958,23 +1988,6 @@ abstract class Metadata { /// Whether the receiver has an annotation of the form `@widgetFactory`. bool get hasWidgetFactory; - - /// The version where the associated SDK API was added. - /// - /// A `@Since()` annotation can be applied to a library declaration, - /// any public declaration in a library, or in a class, or to an optional - /// parameter, etc. - /// - /// The returned version is "effective", so that if a library is annotated - /// then all elements of the library inherit it; or if a class is annotated - /// then all members and constructors of the class inherit it. - /// - /// If multiple `@Since()` annotations apply to the same element, the latest - /// version takes precedence. - /// - /// Returns `null` if the element is not declared in the SDK, or doesn't have - /// a `@Since()` annotation applied to it. - Version? get sinceSdkVersion; } /// A method. @@ -1983,7 +1996,8 @@ abstract class Metadata { /// method. /// /// Clients may not extend, implement or mix-in this class. -abstract class MethodElement2 implements ExecutableElement2 { +abstract class MethodElement2 + implements ExecutableElement2, HasSinceSdkVersion { /// The name of the method that can be implemented by a class to allow its /// instances to be invoked as if they were a function. static final String CALL_METHOD_NAME = "call"; @@ -2277,7 +2291,7 @@ abstract class PropertyAccessorFragment implements ExecutableFragment { /// /// Clients may not extend, implement or mix-in this class. abstract class PropertyInducingElement2 - implements VariableElement2, Annotatable { + implements VariableElement2, Annotatable, HasSinceSdkVersion { @override PropertyInducingFragment get firstFragment; @@ -2439,7 +2453,8 @@ abstract class SuperFormalParameterFragment implements FormalParameterFragment { /// A top-level function. /// /// Clients may not extend, implement or mix-in this class. -abstract class TopLevelFunctionElement implements ExecutableElement2 { +abstract class TopLevelFunctionElement + implements ExecutableElement2, HasSinceSdkVersion { @override TopLevelFunctionElement get baseElement; @@ -2512,7 +2527,10 @@ abstract class TopLevelVariableFragment implements PropertyInducingFragment { /// /// Clients may not extend, implement or mix-in this class. abstract class TypeAliasElement2 - implements TypeParameterizedElement2, TypeDefiningElement2 { + implements + TypeParameterizedElement2, + TypeDefiningElement2, + HasSinceSdkVersion { /// If the aliased type has structure, return the corresponding element. /// For example, it could be [GenericFunctionTypeElement]. /// diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index 8d4c8c67a5c3..d70ac761fc92 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -1612,7 +1612,8 @@ class ConstructorElementImpl2 extends ExecutableElementImpl2 FragmentedFunctionTypedElementMixin, FragmentedTypeParameterizedElementMixin, FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements ConstructorElement2 { @override final String? name3; @@ -2077,7 +2078,7 @@ class DynamicElementImpl2 extends TypeDefiningElementImpl2 { @override Metadata get metadata2 { - return MetadataImpl(0, const [], () => null); + return MetadataImpl(0, const []); } @override @@ -2507,14 +2508,6 @@ abstract class ElementImpl implements Element, Element2 { static const _metadataFlag_hasDeprecated = 1 << 1; static const _metadataFlag_hasOverride = 1 << 2; - /// Cached values for [sinceSdkVersion]. - /// - /// Only very few elements have `@Since()` annotations, so instead of adding - /// an instance field to [ElementImpl], we attach this information this way. - /// We ask it only when [Modifier.HAS_SINCE_SDK_VERSION_VALUE] is `true`, so - /// don't pay for a hash lookup when we know that the result is `null`. - static final Expando _sinceSdkVersion = Expando(); - static int _NEXT_ID = 0; @override @@ -3010,8 +3003,7 @@ abstract class ElementImpl implements Element, Element2 { _metadata = metadata; } - Metadata get metadata2 => - MetadataImpl(_getMetadataFlags(), metadata, () => sinceSdkVersion); + Metadata get metadata2 => MetadataImpl(_getMetadataFlags(), metadata); @override String? get name => _name; @@ -3049,18 +3041,7 @@ abstract class ElementImpl implements Element, Element2 { @override Version? get sinceSdkVersion { - if (!hasModifier(Modifier.HAS_SINCE_SDK_VERSION_COMPUTED)) { - setModifier(Modifier.HAS_SINCE_SDK_VERSION_COMPUTED, true); - var result = SinceSdkVersionComputer().compute(this); - if (result != null) { - _sinceSdkVersion[this] = result; - setModifier(Modifier.HAS_SINCE_SDK_VERSION_VALUE, true); - } - } - if (hasModifier(Modifier.HAS_SINCE_SDK_VERSION_VALUE)) { - return _sinceSdkVersion[this]; - } - return null; + return asElement2.ifTypeOrNull()?.sinceSdkVersion; } @override @@ -3315,6 +3296,9 @@ abstract class ElementImpl2 implements Element2 { @override final int id = ElementImpl._NEXT_ID++; + /// The modifiers associated with this element. + EnumSet _modifiers = EnumSet.empty(); + @override Element2 get baseElement => this; @@ -3401,6 +3385,9 @@ abstract class ElementImpl2 implements Element2 { return "$shortName (${source?.fullName})"; } + /// Whether this element has the [modifier]. + bool hasModifier(Modifier modifier) => _modifiers[modifier]; + @override bool isAccessibleIn2(LibraryElement2 library) { var name3 = this.name3; @@ -3410,6 +3397,11 @@ abstract class ElementImpl2 implements Element2 { return true; } + /// Update [modifier] of this element to [value]. + void setModifier(Modifier modifier, bool value) { + _modifiers = _modifiers.updated(modifier, value); + } + @override Element2? thisOrAncestorMatching2(bool Function(Element2 p1) predicate) { Element2? element = this; @@ -4003,6 +3995,7 @@ class ExtensionElementImpl extends InstanceElementImpl } class ExtensionElementImpl2 extends InstanceElementImpl2 + with _HasSinceSdkVersionMixin implements AugmentedExtensionElement, ExtensionElement2 { @override final Reference reference; @@ -4254,7 +4247,8 @@ class FieldElementImpl extends PropertyInducingElementImpl class FieldElementImpl2 extends PropertyInducingElementImpl2 with FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements FieldElement2 { @override final FieldElementImpl firstFragment; @@ -4402,6 +4396,7 @@ class FormalParameterElementImpl extends PromotableElementImpl2 FragmentedAnnotatableElementMixin, FragmentedElementMixin, FormalParameterElementMixin, + _HasSinceSdkVersionMixin, _NonTopLevelVariableOrParameter implements FormalParameterElementOrMember { final ParameterElementImpl wrappedElement; @@ -4885,12 +4880,12 @@ mixin FragmentedAnnotatableElementMixin return result; } - Metadata get metadata2 => MetadataImpl( - -1, metadata.cast(), () => sinceSdkVersion); + Metadata get metadata2 => + MetadataImpl(-1, metadata.cast()); Version? get sinceSdkVersion { if (this is Element2) { - return SinceSdkVersionComputer().compute2(this as Element2); + return SinceSdkVersionComputer().compute(this as Element2); } return null; } @@ -5332,7 +5327,8 @@ class GetterElementImpl extends PropertyAccessorElementImpl2 FragmentedFunctionTypedElementMixin, FragmentedTypeParameterizedElementMixin, FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements GetterElement { @override final PropertyAccessorElementImpl firstFragment; @@ -5365,6 +5361,14 @@ class GetterElementImpl extends PropertyAccessorElementImpl2 throw StateError('Synthetic getter has no variable'); } + @override + Version? get sinceSdkVersion { + if (isSynthetic) { + return variable3?.sinceSdkVersion; + } + return super.sinceSdkVersion; + } + @override T? accept2(ElementVisitor2 visitor) { return visitor.visitGetterElement(this); @@ -6353,6 +6357,7 @@ abstract class InterfaceElementImpl extends InstanceElementImpl } abstract class InterfaceElementImpl2 extends InstanceElementImpl2 + with _HasSinceSdkVersionMixin implements AugmentedInterfaceElement, InterfaceElement2 { @override List interfaces = []; @@ -7042,6 +7047,11 @@ class LibraryElementImpl extends ElementImpl return declarations.toList(); } + @override + Version? get sinceSdkVersion { + return SinceSdkVersionComputer().compute(this); + } + @override Source get source { return _definingCompilationUnit.source; @@ -7642,10 +7652,7 @@ final class MetadataImpl implements Metadata { @override final List annotations; - final Version? Function() _sinceSdkVersionComputer; - - MetadataImpl( - this._metadataFlags, this.annotations, this._sinceSdkVersionComputer); + MetadataImpl(this._metadataFlags, this.annotations); @override bool get hasAlwaysThrows { @@ -8003,9 +8010,6 @@ final class MetadataImpl implements Metadata { } return false; } - - @override - Version? get sinceSdkVersion => _sinceSdkVersionComputer(); } /// A concrete implementation of a [MethodElement]. @@ -8109,7 +8113,8 @@ class MethodElementImpl2 extends ExecutableElementImpl2 FragmentedFunctionTypedElementMixin, FragmentedTypeParameterizedElementMixin, FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements MethodElement2 { @override final Reference reference; @@ -8922,7 +8927,7 @@ class NeverElementImpl2 extends TypeDefiningElementImpl2 { @override Metadata get metadata2 { - return MetadataImpl(0, const [], () => null); + return MetadataImpl(0, const []); } @override @@ -10141,7 +10146,8 @@ class SetterElementImpl extends PropertyAccessorElementImpl2 FragmentedFunctionTypedElementMixin, FragmentedTypeParameterizedElementMixin, FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements SetterElement { @override final PropertyAccessorElementImpl firstFragment; @@ -10185,6 +10191,14 @@ class SetterElementImpl extends PropertyAccessorElementImpl2 throw StateError('Synthetic setter has no variable'); } + @override + Version? get sinceSdkVersion { + if (isSynthetic) { + return variable3?.sinceSdkVersion; + } + return super.sinceSdkVersion; + } + @override T? accept2(ElementVisitor2 visitor) { return visitor.visitSetterElement(this); @@ -10316,7 +10330,8 @@ class TopLevelFunctionElementImpl extends ExecutableElementImpl2 FragmentedFunctionTypedElementMixin, FragmentedTypeParameterizedElementMixin, FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements TopLevelFunctionElement { @override final Reference reference; @@ -10415,7 +10430,8 @@ class TopLevelVariableElementImpl extends PropertyInducingElementImpl class TopLevelVariableElementImpl2 extends PropertyInducingElementImpl2 with FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements TopLevelVariableElement2 { @override final Reference reference; @@ -10736,7 +10752,8 @@ class TypeAliasElementImpl extends _ExistingElementImpl class TypeAliasElementImpl2 extends TypeDefiningElementImpl2 with FragmentedAnnotatableElementMixin, - FragmentedElementMixin + FragmentedElementMixin, + _HasSinceSdkVersionMixin implements TypeAliasElement2 { @override final Reference reference; @@ -11314,6 +11331,34 @@ mixin _HasLibraryMixin on ElementImpl { Source get source => enclosingElement3!.source!; } +mixin _HasSinceSdkVersionMixin + on ElementImpl2, Annotatable + implements HasSinceSdkVersion { + /// Cached values for [sinceSdkVersion]. + /// + /// Only very few elements have `@Since()` annotations, so instead of adding + /// an instance field to [ElementImpl2], we attach this information this way. + /// We ask it only when [Modifier.HAS_SINCE_SDK_VERSION_VALUE] is `true`, so + /// don't pay for a hash lookup when we know that the result is `null`. + static final Expando _sinceSdkVersion = Expando(); + + @override + Version? get sinceSdkVersion { + if (!hasModifier(Modifier.HAS_SINCE_SDK_VERSION_COMPUTED)) { + setModifier(Modifier.HAS_SINCE_SDK_VERSION_COMPUTED, true); + var result = SinceSdkVersionComputer().compute(this); + if (result != null) { + _sinceSdkVersion[this] = result; + setModifier(Modifier.HAS_SINCE_SDK_VERSION_VALUE, true); + } + } + if (hasModifier(Modifier.HAS_SINCE_SDK_VERSION_VALUE)) { + return _sinceSdkVersion[this]; + } + return null; + } +} + mixin _NonTopLevelVariableOrParameter on Element2 { @override Element2? get enclosingElement2 { @@ -11381,7 +11426,7 @@ extension on Fragment { Metadata get metadataOrEmpty { return switch (this) { Annotatable(:var metadata2) => metadata2, - _ => MetadataImpl(-1, const [], () => null), + _ => MetadataImpl(-1, const []), }; } } diff --git a/pkg/analyzer/lib/src/dart/element/since_sdk_version.dart b/pkg/analyzer/lib/src/dart/element/since_sdk_version.dart index 0bbb26f7e1a6..edbf3cd29da8 100644 --- a/pkg/analyzer/lib/src/dart/element/since_sdk_version.dart +++ b/pkg/analyzer/lib/src/dart/element/since_sdk_version.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/element/element.dart'; @@ -14,49 +12,13 @@ class SinceSdkVersionComputer { /// The [element] is a `dart:xyz` library, so it can have `@Since` annotations. /// Evaluates its annotations and returns the version. - Version? compute(ElementImpl element) { - // Must be in a `dart:` library. - var librarySource = element.librarySource; - if (librarySource == null || !librarySource.uri.isScheme('dart')) { - return null; - } - - // Fields cannot be referenced outside. - if (element is FieldElementImpl && element.isSynthetic) { - return null; - } - - // We cannot add required parameters. - if (element is ParameterElementImpl && element.isRequired) { - return null; - } - - var specified = _specifiedVersion(element); - if (element.enclosingElement3 case var enclosingElement?) { - var enclosing = enclosingElement.sinceSdkVersion; - return specified.maxWith(enclosing); - } else if (element.library case var libraryElement?) { - var enclosing = libraryElement.sinceSdkVersion; - return specified.maxWith(enclosing); - } else { - return specified; - } - } - - /// The [element] is a `dart:xyz` library, so it can have `@Since` annotations. - /// Evaluates its annotations and returns the version. - Version? compute2(Element2 element) { + Version? compute(Element2 element) { // Must be in a `dart:` library. var libraryUri = element.library2?.uri; if (libraryUri == null || !libraryUri.isScheme('dart')) { return null; } - // Fields cannot be referenced outside. - if (element is FieldElement2 && element.isSynthetic) { - return null; - } - // We cannot add required parameters. if (element is FormalParameterElement && element.isRequired) { return null; @@ -64,13 +26,13 @@ class SinceSdkVersionComputer { Version? specified; if (element is Annotatable) { - specified = _specifiedVersion2(element as Annotatable); + specified = _specifiedVersion(element as Annotatable); } - if (element.enclosingElement2 case Annotatable enclosingElement?) { - var enclosing = enclosingElement.metadata2.sinceSdkVersion; - return specified.maxWith(enclosing); - } else if (element.library2 case var libraryElement?) { - var enclosing = libraryElement.metadata2.sinceSdkVersion; + + if (element is LibraryElement2) { + return specified; + } else if (element.enclosingElement2 case HasSinceSdkVersion hasSince?) { + var enclosing = hasSince.sinceSdkVersion; return specified.maxWith(enclosing); } else { return specified; @@ -93,26 +55,7 @@ class SinceSdkVersionComputer { } /// Returns the maximal specified `@Since()` version, `null` if none. - static Version? _specifiedVersion(ElementImpl element) { - Version? result; - for (var annotation in element.metadata) { - if (annotation.isDartInternalSince) { - var arguments = annotation.annotationAst.arguments?.arguments; - var versionNode = arguments?.singleOrNull; - if (versionNode is SimpleStringLiteralImpl) { - var versionStr = versionNode.value; - var version = _parseVersion(versionStr); - if (version != null) { - result = result.maxWith(version); - } - } - } - } - return result; - } - - /// Returns the maximal specified `@Since()` version, `null` if none. - static Version? _specifiedVersion2(Annotatable element) { + static Version? _specifiedVersion(Annotatable element) { var annotations = element.metadata2.annotations.cast(); Version? result; diff --git a/pkg/analyzer/lib/src/hint/sdk_constraint_verifier.dart b/pkg/analyzer/lib/src/hint/sdk_constraint_verifier.dart index b5780a9c7d39..94236e5fdb43 100644 --- a/pkg/analyzer/lib/src/hint/sdk_constraint_verifier.dart +++ b/pkg/analyzer/lib/src/hint/sdk_constraint_verifier.dart @@ -165,8 +165,8 @@ class SdkConstraintVerifier extends RecursiveAstVisitor { SyntacticEntity? errorEntity, }) { element = element?.nonSynthetic2; - if (element is Annotatable) { - var sinceSdkVersion = (element as Annotatable).metadata2.sinceSdkVersion; + if (element case HasSinceSdkVersion hasSince) { + var sinceSdkVersion = hasSince.sinceSdkVersion; if (sinceSdkVersion != null) { if (!_versionConstraint.requiresAtLeast(sinceSdkVersion)) { if (errorEntity == null) { diff --git a/pkg/analyzer/test/src/summary/element_text.dart b/pkg/analyzer/test/src/summary/element_text.dart index 9e77b895d80b..498662a03b3f 100644 --- a/pkg/analyzer/test/src/summary/element_text.dart +++ b/pkg/analyzer/test/src/summary/element_text.dart @@ -17,7 +17,6 @@ import 'package:analyzer/src/summary2/macro_application_error.dart'; import 'package:analyzer/src/summary2/macro_type_location.dart'; import 'package:analyzer_utilities/testing/tree_string_sink.dart'; import 'package:collection/collection.dart'; -import 'package:pub_semver/pub_semver.dart'; import 'package:test/test.dart'; import '../../util/element_printer.dart'; @@ -247,6 +246,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeList( // 'libraryExports', @@ -313,6 +313,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeDisplayName(e); _writeElementList( @@ -566,7 +567,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); // _writeDocumentation(e.documentationComment); // _writeMetadata(e.metadata); - // _writeSinceSdkVersion(e.sinceSdkVersion); + _writeSinceSdkVersion(e); // _writeCodeRange(e); // _writeTypeInferenceError(e); _writeType('type', e.type); @@ -682,6 +683,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeType('type', e.type); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeCodeRange(e); _writeElementList( 'typeParameters', @@ -899,6 +901,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); expect(e.typeParameters2, isEmpty); _writeElementList( @@ -1035,7 +1038,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); // _writeMetadata(e.metadata); - _writeSinceSdkVersion(e.metadata2.sinceSdkVersion); + _writeSinceSdkVersion(e); _writeElementList( 'typeParameters', e, e.typeParameters2, _writeTypeParameterElement); _writeMacroDiagnostics(e); @@ -1181,7 +1184,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('previousFragment', f.previousFragment); _writeFragmentReference('nextFragment', f.nextFragment); - _writeMetadata(f.metadata2, includeSince: false); + _writeMetadata(f.metadata2); if (configuration.withImports) { var imports = f.libraryImports2.where((import) { @@ -1246,7 +1249,7 @@ class _Element2Writer extends _AbstractElementWriter { }); _sink.withIndent(() { - _writeMetadata(e.metadata2, includeSince: false); + _writeMetadata(e.metadata2); // _writeNamespaceCombinators(e.combinators); }); } @@ -1521,7 +1524,7 @@ class _Element2Writer extends _AbstractElementWriter { } } - void _writeMetadata(Metadata metadata, {bool includeSince = true}) { + void _writeMetadata(Metadata metadata) { if (configuration.withMetadata) { var annotations = metadata.annotations; if (annotations.isNotEmpty) { @@ -1534,9 +1537,6 @@ class _Element2Writer extends _AbstractElementWriter { }); } } - if (includeSince) { - _writeSinceSdkVersion(metadata.sinceSdkVersion); - } } void _writeMethodElement(MethodElementImpl2 e) { @@ -1555,6 +1555,7 @@ class _Element2Writer extends _AbstractElementWriter { // _writeElementReference(e.enclosingElement2, label: 'enclosingElement2'); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeTypeInferenceError(e); _writeElementList( @@ -1687,6 +1688,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); expect(e.typeParameters2, isEmpty); _writeElementList( @@ -1766,9 +1768,12 @@ class _Element2Writer extends _AbstractElementWriter { }); } - void _writeSinceSdkVersion(Version? version) { - if (version != null) { - _sink.writelnWithIndent('sinceSdkVersion: $version'); + void _writeSinceSdkVersion(Element2 element) { + if (element case HasSinceSdkVersion hasSince) { + var version = hasSince.sinceSdkVersion; + if (version != null) { + _sink.writelnWithIndent('sinceSdkVersion: $version'); + } } } @@ -1787,6 +1792,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeCodeRange(e); _writeElementList( 'typeParameters', @@ -1886,6 +1892,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeTypeInferenceError(e); _writeType('type', e.type); // _writeShouldUseTypeForInitializerInference(e); @@ -1983,6 +1990,7 @@ class _Element2Writer extends _AbstractElementWriter { _writeFragmentReference('firstFragment', e.firstFragment); _writeDocumentation(e.documentationComment); _writeMetadata(e.metadata2); + _writeSinceSdkVersion(e); // _writeCodeRange(e); _writeElementList( 'typeParameters', e, e.typeParameters2, _writeTypeParameterElement); @@ -2063,7 +2071,7 @@ class _Element2Writer extends _AbstractElementWriter { // _writeType('defaultType', defaultType); // } - _writeMetadata(e.metadata2, includeSince: false); + _writeMetadata(e.metadata2); }); _assertNonSyntheticElementSelf(e); @@ -2089,7 +2097,7 @@ class _Element2Writer extends _AbstractElementWriter { // _writeType('defaultType', defaultType); // } - _writeMetadata(f.metadata2, includeSince: false); + _writeMetadata(f.metadata2); }); // _assertNonSyntheticElementSelf(f); diff --git a/pkg/analyzer/test/src/summary/elements/since_sdk_version_test.dart b/pkg/analyzer/test/src/summary/elements/since_sdk_version_test.dart index 43134614ebe8..cd28a445206f 100644 --- a/pkg/analyzer/test/src/summary/elements/since_sdk_version_test.dart +++ b/pkg/analyzer/test/src/summary/elements/since_sdk_version_test.dart @@ -81,7 +81,6 @@ library named @55 reference: dart:foo::::@class::A::@constructor::named element: dart:foo::::@class::A::@constructor::named#element - sinceSdkVersion: 2.15.0 typeName: A typeNameOffset: 53 periodOffset: 54 @@ -176,12 +175,10 @@ library synthetic get foo reference: dart:foo::::@class::A::@getter::foo element: dart:foo::::@class::A::@getter::foo#element - sinceSdkVersion: 2.15.0 setters synthetic set foo reference: dart:foo::::@class::A::@setter::foo element: dart:foo::::@class::A::@setter::foo#element - sinceSdkVersion: 2.15.0 formalParameters element: dart:foo::::@class::A::@setter::foo::@parameter::_foo#element @@ -193,6 +190,7 @@ library fields hasInitializer foo firstFragment: dart:foo::::@class::A::@field::foo + sinceSdkVersion: 2.15.0 type: int getter: dart:foo::::@class::A::@getter::foo#element setter: dart:foo::::@class::A::@setter::foo#element @@ -236,6 +234,7 @@ library synthetic foo @-1 reference: dart:foo::::@class::A::@field::foo enclosingElement3: dart:foo::::@class::A + sinceSdkVersion: 2.15.0 type: int accessors get foo @61 @@ -262,7 +261,6 @@ library get foo @61 reference: dart:foo::::@class::A::@getter::foo element: dart:foo::::@class::A::@getter::foo#element - sinceSdkVersion: 2.15.0 classes class A reference: dart:foo::@class::A @@ -271,6 +269,7 @@ library fields synthetic foo firstFragment: dart:foo::::@class::A::@field::foo + sinceSdkVersion: 2.15.0 type: int getter: dart:foo::::@class::A::@getter::foo#element getters @@ -322,7 +321,6 @@ library foo @58 reference: dart:foo::::@class::A::@method::foo element: dart:foo::::@class::A::@method::foo#element - sinceSdkVersion: 2.15.0 classes class A reference: dart:foo::@class::A @@ -379,7 +377,6 @@ library foo @75 reference: dart:foo::::@class::A::@method::foo element: dart:foo::::@class::A::@method::foo#element - sinceSdkVersion: 2.16.0 classes class A reference: dart:foo::@class::A @@ -436,7 +433,6 @@ library foo @75 reference: dart:foo::::@class::A::@method::foo element: dart:foo::::@class::A::@method::foo#element - sinceSdkVersion: 2.15.0 classes class A reference: dart:foo::@class::A @@ -476,6 +472,7 @@ library synthetic foo @-1 reference: dart:foo::::@class::A::@field::foo enclosingElement3: dart:foo::::@class::A + sinceSdkVersion: 2.15.0 type: int accessors set foo= @57 @@ -505,7 +502,6 @@ library set foo @57 reference: dart:foo::::@class::A::@setter::foo element: dart:foo::::@class::A::@setter::foo#element - sinceSdkVersion: 2.15.0 formalParameters _ @65 element: dart:foo::::@class::A::@setter::foo::@parameter::_#element @@ -517,6 +513,7 @@ library fields synthetic foo firstFragment: dart:foo::::@class::A::@field::foo + sinceSdkVersion: 2.15.0 type: int setter: dart:foo::::@class::A::@setter::foo#element setters @@ -612,7 +609,6 @@ library synthetic get v2 reference: dart:foo::::@enum::E::@getter::v2 element: dart:foo::::@enum::E::@getter::v2#element - sinceSdkVersion: 2.15.0 synthetic get values reference: dart:foo::::@enum::E::@getter::values element: dart:foo::::@enum::E::@getter::values#element @@ -628,6 +624,7 @@ library getter: dart:foo::::@enum::E::@getter::v1#element static const enumConstant hasInitializer v2 firstFragment: dart:foo::::@enum::E::@field::v2 + sinceSdkVersion: 2.15.0 type: E getter: dart:foo::::@enum::E::@getter::v2#element synthetic static const values @@ -639,6 +636,7 @@ library firstFragment: dart:foo::::@enum::E::@getter::v1 synthetic static get v2 firstFragment: dart:foo::::@enum::E::@getter::v2 + sinceSdkVersion: 2.15.0 synthetic static get values firstFragment: dart:foo::::@enum::E::@getter::values '''); @@ -678,6 +676,7 @@ library synthetic static const values @-1 reference: dart:foo::::@enum::E::@field::values enclosingElement3: dart:foo::::@enum::E + sinceSdkVersion: 2.15.0 type: List accessors synthetic static get v @-1 @@ -688,6 +687,7 @@ library synthetic static get values @-1 reference: dart:foo::::@enum::E::@getter::values enclosingElement3: dart:foo::::@enum::E + sinceSdkVersion: 2.15.0 returnType: List methods foo @62 @@ -718,7 +718,6 @@ library synthetic get v reference: dart:foo::::@enum::E::@getter::v element: dart:foo::::@enum::E::@getter::v#element - sinceSdkVersion: 2.15.0 synthetic get values reference: dart:foo::::@enum::E::@getter::values element: dart:foo::::@enum::E::@getter::values#element @@ -726,7 +725,6 @@ library foo @62 reference: dart:foo::::@enum::E::@method::foo element: dart:foo::::@enum::E::@method::foo#element - sinceSdkVersion: 2.15.0 enums enum E reference: dart:foo::@enum::E @@ -736,10 +734,12 @@ library fields static const enumConstant hasInitializer v firstFragment: dart:foo::::@enum::E::@field::v + sinceSdkVersion: 2.15.0 type: E getter: dart:foo::::@enum::E::@getter::v#element synthetic static const values firstFragment: dart:foo::::@enum::E::@field::values + sinceSdkVersion: 2.15.0 type: List getter: dart:foo::::@enum::E::@getter::values#element getters @@ -800,7 +800,6 @@ library foo @69 reference: dart:foo::::@extension::E::@method::foo element: dart:foo::::@extension::E::@method::foo#element - sinceSdkVersion: 2.15.0 extensions extension E reference: dart:foo::@extension::E @@ -858,7 +857,6 @@ library foo @58 reference: dart:foo::::@mixin::M::@method::foo element: dart:foo::::@mixin::M::@method::foo#element - sinceSdkVersion: 2.15.0 mixins mixin M reference: dart:foo::@mixin::M @@ -911,7 +909,6 @@ library foo @46 reference: dart:foo::::@function::foo element: dart:foo::@function::foo - sinceSdkVersion: 2.15.0 bar @61 reference: dart:foo::::@function::bar element: dart:foo::@function::bar @@ -959,7 +956,6 @@ library foo @54 reference: dart:foo::::@function::foo element: dart:foo::@function::foo - sinceSdkVersion: 2.15.3-dev.7 functions foo reference: dart:foo::@function::foo @@ -1000,7 +996,6 @@ library foo @48 reference: dart:foo::::@function::foo element: dart:foo::@function::foo - sinceSdkVersion: 2.15.3 functions foo reference: dart:foo::@function::foo @@ -1083,7 +1078,6 @@ library foo @56 reference: dart:foo::::@function::foo element: dart:foo::@function::foo - sinceSdkVersion: 2.15.0 functions foo reference: dart:foo::@function::foo @@ -1138,7 +1132,6 @@ library default p2 @67 reference: dart:foo::::@function::f::@parameter::p2 element: dart:foo::::@function::f::@parameter::p2#element - sinceSdkVersion: 2.15.0 functions f reference: dart:foo::@function::f @@ -1197,7 +1190,6 @@ library element: dart:foo::::@function::f::@parameter::p1#element default p2 @67 element: dart:foo::::@function::f::@parameter::p2#element - sinceSdkVersion: 2.15.0 functions f reference: dart:foo::@function::f @@ -1242,7 +1234,6 @@ library A @49 reference: dart:foo::::@typeAlias::A element: dart:foo::@typeAlias::A - sinceSdkVersion: 2.15.0 typeAliases A firstFragment: dart:foo::::@typeAlias::A @@ -1289,13 +1280,11 @@ library hasInitializer foo @47 reference: dart:foo::::@topLevelVariable::foo element: dart:foo::@topLevelVariable::foo - sinceSdkVersion: 2.15.0 getter2: dart:foo::::@getter::foo getters synthetic get foo reference: dart:foo::::@getter::foo element: dart:foo::::@getter::foo#element - sinceSdkVersion: 2.15.0 topLevelVariables final hasInitializer foo reference: dart:foo::@topLevelVariable::foo @@ -1306,6 +1295,7 @@ library getters synthetic static get foo firstFragment: dart:foo::::@getter::foo + sinceSdkVersion: 2.15.0 '''); } From a5c3b34173f2ac90c5be47e66f86e9d4b3dacf1b Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 11:40:08 -0800 Subject: [PATCH 09/76] Elements. Set element for a synthetic covariant merge. Change-Id: I61e7ba6c6753811eedf75acdfdfcc294467dc8e0 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404200 Reviewed-by: Brian Wilkerson Reviewed-by: Phil Quitslund Commit-Queue: Konstantin Shcheglov --- pkg/analyzer/lib/src/dart/element/inheritance_manager3.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/analyzer/lib/src/dart/element/inheritance_manager3.dart b/pkg/analyzer/lib/src/dart/element/inheritance_manager3.dart index c4b87a4eb81e..8a37ecb0f7bc 100644 --- a/pkg/analyzer/lib/src/dart/element/inheritance_manager3.dart +++ b/pkg/analyzer/lib/src/dart/element/inheritance_manager3.dart @@ -1071,6 +1071,11 @@ class InheritanceManager3 { result.parameters = transformedParameters; result.returnType = executable.returnType; result.typeParameters = executable.typeParameters.cast(); + result.element = MethodElementImpl2( + Reference.root(), // TODO(scheglov): wrong + executable.name, + result, + ); return result; } From 01f59564b87f859e229ec7a6f4fa6fe94478c96f Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 11:46:27 -0800 Subject: [PATCH 10/76] Elements. Migrate NormalizeHelper. Change-Id: I6a6bed4ef30e17297faa3828a1c55d52df982a8b Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403929 Reviewed-by: Phil Quitslund Commit-Queue: Konstantin Shcheglov --- .../lib/src/dart/element/extensions.dart | 19 ++++++ .../lib/src/dart/element/normalize.dart | 34 +++++------ pkg/analyzer/lib/src/dart/element/type.dart | 16 +++++ .../lib/src/dart/element/type_algebra.dart | 59 +++++++++++++++++++ 4 files changed, 110 insertions(+), 18 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/element/extensions.dart b/pkg/analyzer/lib/src/dart/element/extensions.dart index fa396172ea27..3c28355c0fbf 100644 --- a/pkg/analyzer/lib/src/dart/element/extensions.dart +++ b/pkg/analyzer/lib/src/dart/element/extensions.dart @@ -187,6 +187,25 @@ extension ExecutableElementExtensionQuestion on ExecutableElement? { } } +extension FormalParameterElementExtension on FormalParameterElement { + /// Returns [FormalParameterElementImpl] with the specified properties + /// replaced. + FormalParameterElementImpl copyWith({ + DartType? type, + ParameterKind? kind, + bool? isCovariant, + }) { + var firstFragment = this.firstFragment as ParameterElement; + return FormalParameterElementImpl( + firstFragment.copyWith( + type: type, + kind: kind, + isCovariant: isCovariant, + ), + ); + } +} + extension InterfaceTypeExtension on InterfaceType { bool get isDartCoreObjectNone { return isDartCoreObject && nullabilitySuffix == NullabilitySuffix.none; diff --git a/pkg/analyzer/lib/src/dart/element/normalize.dart b/pkg/analyzer/lib/src/dart/element/normalize.dart index cae916490734..9fed4174a5a0 100644 --- a/pkg/analyzer/lib/src/dart/element/normalize.dart +++ b/pkg/analyzer/lib/src/dart/element/normalize.dart @@ -2,9 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/extensions.dart'; @@ -22,7 +20,7 @@ class NormalizeHelper { final TypeSystemImpl typeSystem; final TypeProviderImpl typeProvider; - final Set _typeParameters = {}; + final Set _typeParameters = {}; NormalizeHelper(this.typeSystem) : typeProvider = typeSystem.typeProvider; @@ -35,7 +33,7 @@ class NormalizeHelper { /// * and B1 = NORM(B) /// * and S1 = NORM(S) FunctionTypeImpl _functionType(FunctionType functionType) { - var fresh = getFreshTypeParameters(functionType.typeFormals); + var fresh = getFreshTypeParameters2(functionType.typeParameters); for (var typeParameter in fresh.freshTypeParameters) { var bound = typeParameter.firstFragment.bound; if (bound != null) { @@ -45,9 +43,9 @@ class NormalizeHelper { functionType = fresh.applyToFunctionType(functionType); - return FunctionTypeImpl( - typeFormals: functionType.typeFormals, - parameters: functionType.parameters.map((e) { + return FunctionTypeImpl.v2( + typeParameters: functionType.typeParameters, + formalParameters: functionType.formalParameters.map((e) { return e.copyWith( type: _normalize(e.type), ); @@ -134,7 +132,7 @@ class NormalizeHelper { // NORM(C) = C where Ri is NORM(Ti) if (T is InterfaceType) { - return T.element.instantiate( + return T.element3.instantiate( typeArguments: T.typeArguments.map(_normalize).toFixedList(), nullabilitySuffix: NullabilitySuffix.none, ); @@ -202,7 +200,7 @@ class NormalizeHelper { /// NORM(X & T) /// NORM(X extends T) DartType _typeParameterType(TypeParameterTypeImpl T) { - var element = T.element; + var element = T.element3; // NORM(X & T) var promotedBound = T.promotedBound; @@ -237,7 +235,7 @@ class NormalizeHelper { /// NORM(X & T) /// * let S be NORM(T) - DartType _typeParameterType_promoted(TypeParameterElement X, DartType S) { + DartType _typeParameterType_promoted(TypeParameterElement2 X, DartType S) { // * if S is Never then Never if (identical(S, NeverTypeImpl.instance)) { return NeverTypeImpl.instance; @@ -245,7 +243,7 @@ class NormalizeHelper { // * if S is a top type then X if (typeSystem.isTop(S)) { - return X.declaration.instantiate( + return X.instantiate( nullabilitySuffix: NullabilitySuffix.none, ); } @@ -253,20 +251,20 @@ class NormalizeHelper { // * if S is X then X if (S is TypeParameterType && S.nullabilitySuffix == NullabilitySuffix.none && - S.element == X.declaration) { - return X.declaration.instantiate( + S.element3 == X) { + return X.instantiate( nullabilitySuffix: NullabilitySuffix.none, ); } // * if S is Object and NORM(B) is Object where B is the bound of X then X if (S.nullabilitySuffix == NullabilitySuffix.none && S.isDartCoreObject) { - var B = X.declaration.bound; + var B = X.bound; if (B != null) { var B_norm = _normalize(B); if (B_norm.nullabilitySuffix == NullabilitySuffix.none && B_norm.isDartCoreObject) { - return X.declaration.instantiate( + return X.instantiate( nullabilitySuffix: NullabilitySuffix.none, ); } @@ -274,8 +272,8 @@ class NormalizeHelper { } // * else X & S - return TypeParameterTypeImpl( - element: X.declaration, + return TypeParameterTypeImpl.v2( + element: X, nullabilitySuffix: NullabilitySuffix.none, promotedBound: S, ); diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart index 10989f5da66a..fe88fce9d4aa 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart @@ -1707,6 +1707,22 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { super.alias, }); + /// Initialize a newly created type parameter type to be declared by the given + /// [element] and to have the given name. + factory TypeParameterTypeImpl.v2({ + required TypeParameterElement2 element, + required NullabilitySuffix nullabilitySuffix, + DartType? promotedBound, + InstantiatedTypeAliasElement? alias, + }) { + return TypeParameterTypeImpl( + element: element.asElement, + nullabilitySuffix: nullabilitySuffix, + promotedBound: promotedBound, + alias: alias, + ); + } + @override DartType get bound => promotedBound ?? element.bound ?? DynamicTypeImpl.instance; diff --git a/pkg/analyzer/lib/src/dart/element/type_algebra.dart b/pkg/analyzer/lib/src/dart/element/type_algebra.dart index 74c4c6676698..e228b7c59d89 100644 --- a/pkg/analyzer/lib/src/dart/element/type_algebra.dart +++ b/pkg/analyzer/lib/src/dart/element/type_algebra.dart @@ -61,6 +61,55 @@ FreshTypeParameters getFreshTypeParameters( return FreshTypeParameters(freshParameters, substitution); } +/// Generates a fresh copy of the given type parameters, with their bounds +/// substituted to reference the new parameters. +/// +/// The returned object contains the fresh type parameter list as well as a +/// mapping to be used for replacing other types to use the new type parameters. +FreshTypeParameters getFreshTypeParameters2( + List typeParameters) { + var freshParameters = List.generate( + typeParameters.length, + (i) { + var name = typeParameters[i].name3; + var fragment = TypeParameterElementImpl(name ?? '', -1); + return TypeParameterElementImpl2( + firstFragment: fragment, + name3: name, + bound: null, + ); + }, + growable: false, + ); + + var map = {}; + for (int i = 0; i < typeParameters.length; ++i) { + map[typeParameters[i]] = TypeParameterTypeImpl.v2( + element: freshParameters[i], + nullabilitySuffix: NullabilitySuffix.none, + ); + } + + var substitution = Substitution.fromMap2(map); + + for (int i = 0; i < typeParameters.length; ++i) { + // TODO(kallentu): : Clean up TypeParameterElementImpl casting once + // variance is added to the interface. + var typeParameter = typeParameters[i] as TypeParameterElementImpl2; + if (!typeParameter.isLegacyCovariant) { + freshParameters[i].firstFragment.variance = typeParameter.variance; + } + + var bound = typeParameter.bound; + if (bound != null) { + var newBound = substitution.substituteType(bound); + freshParameters[i].firstFragment.bound = newBound; + } + } + + return FreshTypeParameters(freshParameters, substitution); +} + /// Given a generic function [type] of a class member (so that it does not /// carry its element and type arguments), substitute its type parameters with /// the [newTypeParameters] in the formal parameters and return type. @@ -200,6 +249,16 @@ abstract class Substitution { return _MapSubstitution(map); } + /// Substitutes each parameter to the type it maps to in [map]. + static MapSubstitution fromMap2(Map map) { + if (map.isEmpty) { + return _NullSubstitution.instance; + } + return _MapSubstitution( + map.map((key, value) => MapEntry(key.asElement, value)), + ); + } + /// Substitutes the Nth parameter in [parameters] with the Nth type in /// [types]. static MapSubstitution fromPairs( From 519e288797517e339f8b8333d045f23b5d98aba2 Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 12:00:00 -0800 Subject: [PATCH 11/76] Elements. Migrate ElementNameUnion. Change-Id: I163fb60cea95f8e7a53b4be75239864b65bdfbd1 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403925 Reviewed-by: Paul Berry Commit-Queue: Konstantin Shcheglov Reviewed-by: Brian Wilkerson --- .../lib/src/dart/element/element.dart | 37 +++-- .../lib/src/dart/element/name_union.dart | 44 +++--- .../src/dart/element/name_union_test.dart | 135 +++++++++++------- 3 files changed, 139 insertions(+), 77 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index d70ac761fc92..d4e5bb810ba9 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -5562,18 +5562,23 @@ abstract class InstanceElementImpl2 extends ElementImpl2 LibraryElement2 get enclosingElement2 => firstFragment.library; @override - List get fields2 => - fields.map((e) => e.asElement2 as FieldElement2?).nonNulls.toList(); + List get fields2 { + _readMembers(); + return fields.map((e) => e.asElement2 as FieldElement2?).nonNulls.toList(); + } @override InstanceElementImpl get firstFragment; @override - List get getters2 => accessors - .where((e) => e.isGetter) - .map((e) => e.asElement2 as GetterElement?) - .nonNulls - .toList(); + List get getters2 { + _readMembers(); + return accessors + .where((e) => e.isGetter) + .map((e) => e.asElement2 as GetterElement?) + .nonNulls + .toList(); + } @override String get identifier => name3 ?? firstFragment.identifier; @@ -5613,11 +5618,14 @@ abstract class InstanceElementImpl2 extends ElementImpl2 AnalysisSession? get session => firstFragment.session; @override - List get setters2 => accessors - .where((e) => e.isSetter) - .map((e) => e.asElement2 as SetterElement?) - .nonNulls - .toList(); + List get setters2 { + _readMembers(); + return accessors + .where((e) => e.isSetter) + .map((e) => e.asElement2 as SetterElement?) + .nonNulls + .toList(); + } @override List get typeParameters2 => @@ -5892,6 +5900,11 @@ abstract class InstanceElementImpl2 extends ElementImpl2 Iterable _implementationsOfSetter2(String name) { return _implementationsOfSetter(name).map((e) => e.asElement2); } + + void _readMembers() { + // TODO(scheglov): use better implementation + firstFragment.element; + } } abstract class InterfaceElementImpl extends InstanceElementImpl diff --git a/pkg/analyzer/lib/src/dart/element/name_union.dart b/pkg/analyzer/lib/src/dart/element/name_union.dart index cc1b53a67178..7c0c05afad88 100644 --- a/pkg/analyzer/lib/src/dart/element/name_union.dart +++ b/pkg/analyzer/lib/src/dart/element/name_union.dart @@ -2,12 +2,10 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'dart:typed_data'; -import 'package:analyzer/dart/element/element.dart'; -import 'package:analyzer/dart/element/visitor.dart'; +import 'package:analyzer/dart/element/element2.dart'; +import 'package:analyzer/dart/element/visitor2.dart'; /// Union of a set of names. class ElementNameUnion { @@ -92,33 +90,45 @@ class ElementNameUnion { return true; } - static ElementNameUnion forLibrary(LibraryElement libraryElement) { + static ElementNameUnion forLibrary(LibraryElement2 libraryElement) { var result = ElementNameUnion.empty(); - libraryElement.accept( - _ElementVisitor(result), + libraryElement.accept2( + _ElementVisitor2(result), ); return result; } + + static bool _hasInterestingElements(Element2 element) { + if (element is ExecutableElement2) { + return false; + } + return true; + } + + static bool _isInterestingElement(Element2 element) { + return element.enclosingElement2 is LibraryElement2 || + element is FieldElement2 || + element is MethodElement2 || + element is PropertyAccessorElement2; + } } -class _ElementVisitor extends GeneralizingElementVisitor { +class _ElementVisitor2 extends GeneralizingElementVisitor2 { final ElementNameUnion union; - _ElementVisitor(this.union); + _ElementVisitor2(this.union); @override - void visitElement(Element element) { - var enclosing = element.enclosingElement3; - if (enclosing is CompilationUnitElement || - element is FieldElement || - element is MethodElement || - element is PropertyAccessorElement) { - var name = element.name; + void visitElement(Element2 element) { + if (ElementNameUnion._isInterestingElement(element)) { + var name = element.name3; if (name != null) { union.add(name); } } - super.visitElement(element); + if (ElementNameUnion._hasInterestingElements(element)) { + super.visitElement(element); + } } } diff --git a/pkg/analyzer/test/src/dart/element/name_union_test.dart b/pkg/analyzer/test/src/dart/element/name_union_test.dart index 3cee531d577e..c6b9c3ce3113 100644 --- a/pkg/analyzer/test/src/dart/element/name_union_test.dart +++ b/pkg/analyzer/test/src/dart/element/name_union_test.dart @@ -2,16 +2,10 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - -import 'package:analyzer/dart/analysis/results.dart'; -import 'package:analyzer/dart/element/element.dart'; -import 'package:analyzer/dart/element/visitor.dart'; -import 'package:analyzer/src/dart/element/name_union.dart'; import 'package:test/test.dart'; import 'package:test_reflective_loader/test_reflective_loader.dart'; -import '../resolution/context_collection_resolution.dart'; +import '../../summary/elements_base.dart'; main() { defineReflectiveSuite(() { @@ -20,54 +14,99 @@ main() { } @reflectiveTest -class ElementNameUnionTest extends PubPackageResolutionTest { - test_it() async { - await _checkLibrary('dart:async'); - await _checkLibrary('dart:core'); - await _checkLibrary('dart:math'); - } +class ElementNameUnionTest extends ElementsBaseTest { + @override + bool get keepLinkingLibraries => false; + + test_class() async { + var library = await buildLibrary(r''' +class MyClass { + final myField = 0; + int get myGetter => 0; + set mySetter(int _) {} + void myMethod() {} +} +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyClass'), isTrue); + expect(nameUnion.contains('NotMyClass'), isFalse); - Future _checkLibrary(String uriStr) async { - var analysisContext = contextFor(testFile); - var analysisSession = analysisContext.currentSession; + expect(nameUnion.contains('myField'), isTrue); + expect(nameUnion.contains('NotMyField'), isFalse); - var result = await analysisSession.getLibraryByUri(uriStr); - result as LibraryElementResult; - var element = result.element; + expect(nameUnion.contains('myGetter'), isTrue); + expect(nameUnion.contains('NotMyGetter'), isFalse); - var union = ElementNameUnion.forLibrary(element); - element.accept( - _ElementVisitor(union), - ); + expect(nameUnion.contains('mySetter'), isTrue); + expect(nameUnion.contains('NotMySetter'), isFalse); + + expect(nameUnion.contains('myMethod'), isTrue); + expect(nameUnion.contains('NotMyMethod'), isFalse); } + + test_enum() async { + var library = await buildLibrary(r''' +enum MyEnum { + myValue } +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyEnum'), isTrue); + expect(nameUnion.contains('NotMyEnum'), isFalse); -/// Checks that the name of every interesting element is in [union]. -class _ElementVisitor extends GeneralizingElementVisitor { - final ElementNameUnion union; + expect(nameUnion.contains('MyValue'), isTrue); + expect(nameUnion.contains('NotMyValue'), isFalse); + } - _ElementVisitor(this.union); + test_extension() async { + var library = await buildLibrary(r''' +extension MyExtension on int {} +'''); - @override - void visitElement(Element element) { - var enclosing = element.enclosingElement3; - if (enclosing is CompilationUnitElement || - element is FieldElement || - element is MethodElement || - element is PropertyAccessorElement) { - var name = element.name; - if (name != null) { - expect(union.contains(name), isTrue, reason: 'Expected to find $name'); - // This might fail, but the probability is low. If this does fail, try - // adding another `z` to the prefix. - expect( - union.contains('zz$name'), - isFalse, - reason: 'Expected to not find $name', - ); - } - } - - super.visitElement(element); + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyExtension'), isTrue); + expect(nameUnion.contains('NotMyExtension'), isFalse); + } + + test_extensionType() async { + var library = await buildLibrary(r''' +extension type MyExtensionType(int it) {} +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyExtensionType'), isTrue); + expect(nameUnion.contains('NotMyExtensionType'), isFalse); + } + + test_mixin() async { + var library = await buildLibrary(r''' +mixin MyMixin {} +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyMixin'), isTrue); + expect(nameUnion.contains('NotMyMixin'), isFalse); + } + + test_topLevelVariable() async { + var library = await buildLibrary(r''' +final myVariable = 0; +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('myVariable'), isTrue); + expect(nameUnion.contains('NotMyVariable'), isFalse); + } + + test_typedef() async { + var library = await buildLibrary(r''' +typedef MyTypedef = int; +'''); + + var nameUnion = library.nameUnion; + expect(nameUnion.contains('MyTypedef'), isTrue); + expect(nameUnion.contains('NotMyTypedef'), isFalse); } } From 8a3b4ab3181b1d31e4a7440634893bce5412f22d Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 12:01:24 -0800 Subject: [PATCH 12/76] Elements. Restore lazy reading ClassElement members. Bug: https://github.com/flutter/flutter/issues/161306 Change-Id: I65b606b8aa012cebf62d866128bc35c5532e5638 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403924 Reviewed-by: Brian Wilkerson Commit-Queue: Konstantin Shcheglov --- .../lib/src/dart/analysis/driver.dart | 2 +- .../lib/src/dart/element/element.dart | 18 +++- .../lib/src/summary2/bundle_reader.dart | 92 ++++++++++++++----- .../lib/src/summary2/bundle_writer.dart | 12 +++ .../lib/src/summary2/informative_data.dart | 13 ++- .../lib/src/utilities/extensions/element.dart | 11 +++ 6 files changed, 120 insertions(+), 28 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/analysis/driver.dart b/pkg/analyzer/lib/src/dart/analysis/driver.dart index 4ff1baa06a79..537185f91b17 100644 --- a/pkg/analyzer/lib/src/dart/analysis/driver.dart +++ b/pkg/analyzer/lib/src/dart/analysis/driver.dart @@ -99,7 +99,7 @@ import 'package:meta/meta.dart'; // TODO(scheglov): Clean up the list of implicitly analyzed files. class AnalysisDriver { /// The version of data format, should be incremented on every format change. - static const int DATA_VERSION = 426; + static const int DATA_VERSION = 427; /// The number of exception contexts allowed to write. Once this field is /// zero, we stop writing any new exception contexts in this process. diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index d4e5bb810ba9..2a3a50483d54 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -451,7 +451,7 @@ class ClassElementImpl extends ClassOrMixinElementImpl } @override - ClassFragment? get nextFragment => super.nextFragment as ClassFragment?; + ClassElementImpl? get nextFragment => super.nextFragment as ClassElementImpl?; @override ClassFragment? get previousFragment => @@ -5433,6 +5433,11 @@ abstract class InstanceElementImpl extends _ExistingElementImpl @override List get accessors { + if (!identical(_accessors, _Sentinel.propertyAccessorElement)) { + return _accessors; + } + + linkedData?.readMembers(this); return _accessors; } @@ -5462,6 +5467,11 @@ abstract class InstanceElementImpl extends _ExistingElementImpl @override List get fields { + if (!identical(_fields, _Sentinel.fieldElement)) { + return _fields; + } + + linkedData?.readMembers(this); return _fields; } @@ -5490,6 +5500,11 @@ abstract class InstanceElementImpl extends _ExistingElementImpl @override List get methods { + if (!identical(_methods, _Sentinel.methodElement)) { + return _methods; + } + + linkedData?.readMembers(this); return _methods; } @@ -5975,6 +5990,7 @@ abstract class InterfaceElementImpl extends InstanceElementImpl } _buildMixinAppConstructors(); + linkedData?.readMembers(this); return _constructors; } diff --git a/pkg/analyzer/lib/src/summary2/bundle_reader.dart b/pkg/analyzer/lib/src/summary2/bundle_reader.dart index 31ec6d106bf5..68eefaf61cc9 100644 --- a/pkg/analyzer/lib/src/summary2/bundle_reader.dart +++ b/pkg/analyzer/lib/src/summary2/bundle_reader.dart @@ -76,6 +76,7 @@ class BundleReader { return _LibraryHeader( uri: uriCache.parse(_reader.readStringReference()), offset: _reader.readUInt30(), + classMembersLengths: _reader.readUInt30List(), macroGeneratedCode: _reader.readOptionalObject((reader) { return _reader.readStringUtf8(); }), @@ -94,6 +95,7 @@ class BundleReader { referenceReader: referenceReader, reference: reference, offset: libraryHeader.offset, + classMembersLengths: libraryHeader.classMembersLengths, infoDeclarationStore: _infoDeclarationStore, macroGeneratedCode: libraryHeader.macroGeneratedCode, ); @@ -103,6 +105,8 @@ class BundleReader { class ClassElementLinkedData extends ElementLinkedData { ApplyConstantOffsets? applyConstantOffsets; + void Function()? _readMembers; + void Function()? applyInformativeDataToMembers; ClassElementLinkedData({ required Reference reference, @@ -112,17 +116,14 @@ class ClassElementLinkedData extends ElementLinkedData { }) : super(reference, libraryReader, unitElement, offset); @override - void readMembers(InstanceElementImpl element) { - if (element is! ClassElementImpl) { - return; - } - - // We might read class members before other properties. - element.linkedData?.read(element); - element.linkedData = null; - - if (element.isMixinApplication) { - element.constructors; + void readMembers(covariant ClassElementImpl fragment) { + // Read members of all fragments, in order. + // So we always read a method augmentation after its target. + for (var fragment in fragment.element.fragments) { + var linkedData = fragment.linkedData; + if (linkedData is ClassElementLinkedData) { + linkedData._readSingleFragmentMembers(fragment); + } } } @@ -154,6 +155,22 @@ class ClassElementLinkedData extends ElementLinkedData { applyConstantOffsets?.perform(); } + + void _readSingleFragmentMembers(ClassElementImpl element) { + // We might read class members before other properties. + element.linkedData?.read(element); + element.linkedData = null; + + if (element.isMixinApplication) { + element.constructors; + } else { + _readMembers?.call(); + _readMembers = null; + + applyInformativeDataToMembers?.call(); + applyInformativeDataToMembers = null; + } + } } class CompilationUnitElementLinkedData @@ -615,6 +632,9 @@ class LibraryReader { final InfoDeclarationStore _deserializedDataStore; final String? macroGeneratedCode; + final Uint32List _classMembersLengths; + int _classMembersLengthsIndex = 0; + late final LibraryElementImpl _libraryElement; late InstanceElementImpl2 _currentInstanceElement; @@ -627,6 +647,7 @@ class LibraryReader { required _ReferenceReader referenceReader, required Reference reference, required int offset, + required Uint32List classMembersLengths, required InfoDeclarationStore infoDeclarationStore, required this.macroGeneratedCode, }) : _elementFactory = elementFactory, @@ -636,6 +657,7 @@ class LibraryReader { _referenceReader = referenceReader, _reference = reference, _offset = offset, + _classMembersLengths = classMembersLengths, _deserializedDataStore = infoDeclarationStore; LibraryElementImpl readElement({required Source librarySource}) { @@ -644,6 +666,11 @@ class LibraryReader { _reader.offset = _offset; + // TODO(scheglov): https://github.com/dart-lang/sdk/issues/51855 + // This should not be needed. + // But I have a suspicion that we attempt to read the library twice. + _classMembersLengthsIndex = 0; + // Read enough data to create the library. var name = _reader.readStringReference(); var featureSet = _readFeatureSet(); @@ -754,22 +781,37 @@ class LibraryReader { fragment.typeParameters = _readTypeParameters(); if (!fragment.isMixinApplication) { - var accessors = []; - var fields = []; - _readFields(unitElement, fragment, reference, accessors, fields); - _readPropertyAccessors( - unitElement, fragment, reference, accessors, fields, '@field'); - fragment.fields = fields.toFixedList(); - fragment.accessors = accessors.toFixedList(); - - fragment.constructors = - _readConstructors(unitElement, fragment, reference); - fragment.methods = _readMethods(unitElement, fragment, reference); + var membersOffset = _reader.offset; + linkedData._readMembers = () { + _reader.offset = membersOffset; + _readClassElementMembers(fragment, reference); + }; + _reader.offset += _classMembersLengths[_classMembersLengthsIndex++]; } return fragment; } + void _readClassElementMembers( + ClassElementImpl fragment, + Reference reference, + ) { + // print('[_readClassElementMembers][reference: $reference]'); + var unitElement = fragment.enclosingElement3; + _currentInstanceElement = fragment.element; + + var accessors = []; + var fields = []; + _readFields(unitElement, fragment, reference, accessors, fields); + _readPropertyAccessors( + unitElement, fragment, reference, accessors, fields, '@field'); + fragment.fields = fields.toFixedList(); + fragment.accessors = accessors.toFixedList(); + + fragment.constructors = _readConstructors(unitElement, fragment, reference); + fragment.methods = _readMethods(unitElement, fragment, reference); + } + void _readClasses( CompilationUnitElementImpl unitElement, Reference unitReference, @@ -2665,12 +2707,18 @@ class _LibraryHeader { final Uri uri; final int offset; + /// We don't read class members when reading libraries, by performance + /// reasons - in many cases only some classes of a library are used. But + /// we need to know how much data to skip for each class. + final Uint32List classMembersLengths; + /// The only (if any) macro generated augmentation code. final String? macroGeneratedCode; _LibraryHeader({ required this.uri, required this.offset, + required this.classMembersLengths, required this.macroGeneratedCode, }); } diff --git a/pkg/analyzer/lib/src/summary2/bundle_writer.dart b/pkg/analyzer/lib/src/summary2/bundle_writer.dart index c22e67c2f785..5141b468be4d 100644 --- a/pkg/analyzer/lib/src/summary2/bundle_writer.dart +++ b/pkg/analyzer/lib/src/summary2/bundle_writer.dart @@ -57,6 +57,11 @@ class BundleWriter { references: _references, ); + /// [_writeClassElement] remembers the length of data written into [_sink] + /// while writing members. So, when we read, we can skip members initially, + /// and read them later on demand. + List _classMembersLengths = []; + final StringIndexer _stringIndexer = StringIndexer(); final List<_Library> _libraries = []; @@ -73,6 +78,7 @@ class BundleWriter { _sink.writeList<_Library>(_libraries, (library) { _sink._writeStringReference(library.uriStr); _sink.writeUInt30(library.offset); + _sink.writeUint30List(library.classMembersOffsets); _sink.writeOptionalObject(library.macroGenerated, (it) { _sink.writeStringUtf8(it.code); }); @@ -99,6 +105,7 @@ class BundleWriter { void writeLibraryElement(LibraryElementImpl libraryElement) { var libraryOffset = _sink.offset; + _classMembersLengths = []; // Write non-resolution data for the library. _sink._writeStringReference(libraryElement.name); @@ -128,6 +135,7 @@ class BundleWriter { _Library( uriStr: '${libraryElement.source.uri}', offset: libraryOffset, + classMembersOffsets: _classMembersLengths, macroGenerated: macroGenerated, ), ); @@ -171,6 +179,7 @@ class BundleWriter { } if (!element.isMixinApplication) { + var membersOffset = _sink.offset; _writeList( element.fields.where((e) => !e.isSynthetic).toList(), _writeFieldElement, @@ -181,6 +190,7 @@ class BundleWriter { ); _writeList(element.constructors, _writeConstructorElement); _writeList(element.methods, _writeMethodElement); + _classMembersLengths.add(_sink.offset - membersOffset); } }); } @@ -1296,6 +1306,7 @@ class _BundleWriterReferences { class _Library { final String uriStr; final int offset; + final List classMembersOffsets; /// The only (if any) macro generated fragment. final MacroGeneratedLibraryFragment? macroGenerated; @@ -1303,6 +1314,7 @@ class _Library { _Library({ required this.uriStr, required this.offset, + required this.classMembersOffsets, required this.macroGenerated, }); } diff --git a/pkg/analyzer/lib/src/summary2/informative_data.dart b/pkg/analyzer/lib/src/summary2/informative_data.dart index ba15fabbfc43..32595940e861 100644 --- a/pkg/analyzer/lib/src/summary2/informative_data.dart +++ b/pkg/analyzer/lib/src/summary2/informative_data.dart @@ -227,10 +227,6 @@ class InformativeDataApplier { element.typeParameters_unresolved, info.typeParameters, ); - _applyToConstructors(element.constructors, info.constructors); - _applyToFields(element.fields, info.fields); - _applyToAccessors(element.accessors, info.accessors); - _applyToMethods(element.methods, info.methods); var applyOffsets = ApplyConstantOffsets( info.constantOffsets, @@ -240,11 +236,20 @@ class InformativeDataApplier { }, ); + void applyToMembers() { + _applyToConstructors(element.constructors, info.constructors); + _applyToFields(element.fields, info.fields); + _applyToAccessors(element.accessors, info.accessors); + _applyToMethods(element.methods, info.methods); + } + var linkedData = element.linkedData; if (linkedData is ClassElementLinkedData) { linkedData.applyConstantOffsets = applyOffsets; + linkedData.applyInformativeDataToMembers = applyToMembers; } else { applyOffsets.perform(); + applyToMembers(); } } diff --git a/pkg/analyzer/lib/src/utilities/extensions/element.dart b/pkg/analyzer/lib/src/utilities/extensions/element.dart index 0980624c1288..d234639f6a4a 100644 --- a/pkg/analyzer/lib/src/utilities/extensions/element.dart +++ b/pkg/analyzer/lib/src/utilities/extensions/element.dart @@ -25,6 +25,17 @@ extension ClassElementExtension on ClassElement { } } +extension ClassElementImpl2Extension on ClassElementImpl2 { + List get fragments { + return [ + for (ClassElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } +} + extension CompilationUnitElementExtension on CompilationUnitElement { LibraryFragment get asElement2 { return this as LibraryFragment; From 238db6e7017beb64193ffc01b508bd297f3e2f56 Mon Sep 17 00:00:00 2001 From: Ben Konyi Date: Mon, 13 Jan 2025 12:42:19 -0800 Subject: [PATCH 13/76] [ DDS ] Fix package:vm_service constraints before publishing 5.0.0 vm_service 14.3.0 is required for DDS to support id zones. Change-Id: I8c0c4a64e5910d222af87ee447c1b004d9eab5d5 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404040 Auto-Submit: Ben Konyi Commit-Queue: Ben Konyi Reviewed-by: Derek Xu --- pkg/dds/CHANGELOG.md | 2 +- pkg/dds/pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/dds/CHANGELOG.md b/pkg/dds/CHANGELOG.md index 835f40cd0619..341aad00d2a5 100644 --- a/pkg/dds/CHANGELOG.md +++ b/pkg/dds/CHANGELOG.md @@ -7,7 +7,7 @@ lifetime of instance references returned. This should avoid instances being collected while execution is paused, while releasing them once execution resumes. -- Updated `vm_service` constraint to `>=14.0.0 <16.0.0`. +- Updated `vm_service` constraint to `>=14.3.0 <16.0.0`. - [DAP] Updated `dap` constraint to ^1.4.0. - [DAP] Set `supportsANSIStyling` to `true` in debug adapter capabilities to indicate that `Output` events might contain ansi color codes. - [DAP] Stack traces in more formats will be parsed and have locations attached to `OutputEvents`s. diff --git a/pkg/dds/pubspec.yaml b/pkg/dds/pubspec.yaml index dae595599553..6562dfd06e2a 100644 --- a/pkg/dds/pubspec.yaml +++ b/pkg/dds/pubspec.yaml @@ -28,7 +28,7 @@ dependencies: shelf: ^1.0.0 sse: ^4.0.0 stream_channel: ^2.0.0 - vm_service: '>=14.0.0 <16.0.0' + vm_service: '>=14.3.0 <16.0.0' web_socket_channel: '>=2.0.0 <4.0.0' # We use 'any' version constraints here as we get our package versions from From 02483247a724a089e175a7b29125a8e64d743e33 Mon Sep 17 00:00:00 2001 From: pq Date: Mon, 13 Jan 2025 12:46:50 -0800 Subject: [PATCH 14/76] [cq] bump linter to 3.7 and tall-style format Change-Id: I08e8310c6133418fd99954c306601b277a85f3c5 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403932 Reviewed-by: Brian Wilkerson Commit-Queue: Phil Quitslund --- pkg/linter/lib/src/ast.dart | 7 +- pkg/linter/lib/src/extensions.dart | 68 +- pkg/linter/lib/src/lint_codes.g.dart | 394 +++--- .../rules/always_declare_return_types.dart | 31 +- .../always_put_control_body_on_new_line.dart | 12 +- ...s_put_required_named_parameters_first.dart | 12 +- ...ays_require_non_null_named_parameters.dart | 10 +- .../lib/src/rules/always_specify_types.dart | 108 +- .../src/rules/always_use_package_imports.dart | 14 +- .../src/rules/analyzer_use_new_elements.dart | 21 +- .../lib/src/rules/annotate_overrides.dart | 9 +- .../lib/src/rules/annotate_redeclares.dart | 23 +- .../rules/avoid_annotating_with_dynamic.dart | 9 +- pkg/linter/lib/src/rules/avoid_as.dart | 10 +- ...l_literals_in_conditional_expressions.dart | 12 +- .../avoid_catches_without_on_clauses.dart | 12 +- .../lib/src/rules/avoid_catching_errors.dart | 29 +- ...void_classes_with_only_static_members.dart | 12 +- .../rules/avoid_double_and_int_checks.dart | 9 +- .../lib/src/rules/avoid_dynamic_calls.dart | 5 +- .../lib/src/rules/avoid_empty_else.dart | 9 +- ...uals_and_hash_code_on_mutable_classes.dart | 18 +- .../rules/avoid_escaping_inner_quotes.dart | 15 +- ...d_field_initializers_in_const_classes.dart | 19 +- .../lib/src/rules/avoid_final_parameters.dart | 14 +- ...id_function_literals_in_foreach_calls.dart | 12 +- .../lib/src/rules/avoid_futureor_void.dart | 23 +- .../rules/avoid_implementing_value_types.dart | 16 +- .../lib/src/rules/avoid_init_to_null.dart | 9 +- .../lib/src/rules/avoid_js_rounded_ints.dart | 9 +- .../avoid_multiple_declarations_per_line.dart | 12 +- ...oid_null_checks_in_equality_operators.dart | 20 +- .../avoid_positional_boolean_parameters.dart | 18 +- pkg/linter/lib/src/rules/avoid_print.dart | 10 +- .../avoid_private_typedef_functions.dart | 12 +- .../avoid_redundant_argument_values.dart | 15 +- .../src/rules/avoid_relative_lib_imports.dart | 9 +- .../avoid_renaming_method_parameters.dart | 29 +- .../rules/avoid_return_types_on_setters.dart | 9 +- .../lib/src/rules/avoid_returning_null.dart | 10 +- .../avoid_returning_null_for_future.dart | 9 +- .../rules/avoid_returning_null_for_void.dart | 34 +- .../lib/src/rules/avoid_returning_this.dart | 9 +- .../rules/avoid_setters_without_getters.dart | 16 +- .../avoid_shadowing_type_parameters.dart | 51 +- ...ngle_cascade_in_expression_statements.dart | 12 +- .../lib/src/rules/avoid_slow_async_io.dart | 14 +- .../lib/src/rules/avoid_type_to_string.dart | 24 +- .../rules/avoid_types_as_parameter_names.dart | 16 +- .../avoid_types_on_closure_parameters.dart | 12 +- .../rules/avoid_unnecessary_containers.dart | 9 +- .../rules/avoid_unstable_final_fields.dart | 12 +- .../avoid_unused_constructor_parameters.dart | 34 +- .../lib/src/rules/avoid_void_async.dart | 19 +- .../rules/avoid_web_libraries_in_flutter.dart | 14 +- .../lib/src/rules/await_only_futures.dart | 9 +- .../lib/src/rules/camel_case_extensions.dart | 9 +- .../lib/src/rules/camel_case_types.dart | 9 +- .../lib/src/rules/cancel_subscriptions.dart | 13 +- .../lib/src/rules/cascade_invocations.dart | 118 +- .../rules/cast_nullable_to_non_nullable.dart | 9 +- pkg/linter/lib/src/rules/close_sinks.dart | 10 +- .../collection_methods_unrelated_type.dart | 209 +-- .../lib/src/rules/combinators_ordering.dart | 5 +- .../lib/src/rules/comment_references.dart | 9 +- .../rules/conditional_uri_does_not_exist.dart | 9 +- .../src/rules/constant_identifier_names.dart | 9 +- .../src/rules/control_flow_in_finally.dart | 38 +- ...rly_braces_in_flow_control_structures.dart | 12 +- .../rules/dangling_library_doc_comments.dart | 9 +- .../lib/src/rules/deprecated_consistency.dart | 37 +- ...precated_member_use_from_same_package.dart | 45 +- .../diagnostic_describe_all_properties.dart | 18 +- .../lib/src/rules/directives_ordering.dart | 93 +- .../lib/src/rules/discarded_futures.dart | 9 +- .../lib/src/rules/do_not_use_environment.dart | 9 +- .../lib/src/rules/document_ignores.dart | 14 +- pkg/linter/lib/src/rules/empty_catches.dart | 10 +- .../src/rules/empty_constructor_bodies.dart | 9 +- .../lib/src/rules/empty_statements.dart | 9 +- .../lib/src/rules/enable_null_safety.dart | 10 +- .../lib/src/rules/eol_at_end_of_file.dart | 9 +- .../erase_dart_type_extension_types.dart | 14 +- .../lib/src/rules/exhaustive_cases.dart | 20 +- pkg/linter/lib/src/rules/file_names.dart | 10 +- .../lib/src/rules/flutter_style_todos.dart | 17 +- pkg/linter/lib/src/rules/hash_and_equals.dart | 16 +- .../lib/src/rules/implementation_imports.dart | 9 +- .../lib/src/rules/implicit_call_tearoffs.dart | 9 +- pkg/linter/lib/src/rules/implicit_reopen.dart | 48 +- .../lib/src/rules/invalid_case_patterns.dart | 14 +- ...d_runtime_check_with_js_interop_types.dart | 145 +- .../lib/src/rules/invariant_booleans.dart | 10 +- .../iterable_contains_unrelated_type.dart | 13 +- .../rules/join_return_with_assignment.dart | 27 +- ...leading_newlines_in_multiline_strings.dart | 16 +- .../lib/src/rules/library_annotations.dart | 9 +- pkg/linter/lib/src/rules/library_names.dart | 10 +- .../lib/src/rules/library_prefixes.dart | 12 +- .../library_private_types_in_public_api.dart | 22 +- .../src/rules/lines_longer_than_80_chars.dart | 37 +- .../src/rules/list_remove_unrelated_type.dart | 10 +- .../literal_only_boolean_expressions.dart | 12 +- .../src/rules/matching_super_parameters.dart | 24 +- ...ng_code_block_language_in_doc_comment.dart | 12 +- ...g_whitespace_between_adjacent_strings.dart | 33 +- .../rules/no_adjacent_strings_in_list.dart | 9 +- .../lib/src/rules/no_default_cases.dart | 14 +- .../src/rules/no_duplicate_case_values.dart | 15 +- ...ding_underscores_for_library_prefixes.dart | 15 +- ...ing_underscores_for_local_identifiers.dart | 12 +- .../rules/no_literal_bool_comparisons.dart | 9 +- .../src/rules/no_logic_in_create_state.dart | 9 +- .../src/rules/no_runtimeType_toString.dart | 9 +- .../lib/src/rules/no_self_assignments.dart | 9 +- .../src/rules/no_wildcard_variable_uses.dart | 9 +- .../rules/non_constant_identifier_names.dart | 9 +- .../src/rules/noop_primitive_operations.dart | 14 +- ...null_check_on_nullable_type_parameter.dart | 12 +- pkg/linter/lib/src/rules/null_closures.dart | 153 ++- .../src/rules/omit_local_variable_types.dart | 15 +- .../omit_obvious_local_variable_types.dart | 14 +- .../rules/omit_obvious_property_types.dart | 14 +- .../lib/src/rules/one_member_abstracts.dart | 9 +- .../lib/src/rules/only_throw_errors.dart | 9 +- .../lib/src/rules/overridden_fields.dart | 21 +- .../lib/src/rules/package_api_docs.dart | 9 +- .../rules/package_prefixed_library_names.dart | 9 +- .../lib/src/rules/parameter_assignments.dart | 47 +- .../prefer_adjacent_string_concatenation.dart | 12 +- .../prefer_asserts_in_initializer_lists.dart | 35 +- .../rules/prefer_asserts_with_message.dart | 9 +- .../lib/src/rules/prefer_bool_in_asserts.dart | 10 +- .../src/rules/prefer_collection_literals.dart | 9 +- .../rules/prefer_conditional_assignment.dart | 13 +- .../src/rules/prefer_const_constructors.dart | 18 +- ...efer_const_constructors_in_immutables.dart | 22 +- .../src/rules/prefer_const_declarations.dart | 9 +- ...r_const_literals_to_create_immutables.dart | 12 +- ...efer_constructors_over_static_methods.dart | 26 +- pkg/linter/lib/src/rules/prefer_contains.dart | 54 +- .../lib/src/rules/prefer_double_quotes.dart | 9 +- .../prefer_equal_for_default_values.dart | 10 +- .../prefer_expression_function_bodies.dart | 12 +- .../lib/src/rules/prefer_final_fields.dart | 37 +- .../src/rules/prefer_final_in_for_each.dart | 52 +- .../lib/src/rules/prefer_final_locals.dart | 34 +- .../src/rules/prefer_final_parameters.dart | 19 +- ...efer_for_elements_to_map_fromIterable.dart | 15 +- pkg/linter/lib/src/rules/prefer_foreach.dart | 10 +- ..._function_declarations_over_variables.dart | 12 +- .../prefer_generic_function_type_aliases.dart | 12 +- ...f_elements_to_conditional_expressions.dart | 12 +- .../src/rules/prefer_if_null_operators.dart | 16 +- .../rules/prefer_initializing_formals.dart | 20 +- .../lib/src/rules/prefer_inlined_adds.dart | 26 +- .../lib/src/rules/prefer_int_literals.dart | 9 +- ...efer_interpolation_to_compose_strings.dart | 21 +- pkg/linter/lib/src/rules/prefer_is_empty.dart | 106 +- .../lib/src/rules/prefer_is_not_empty.dart | 9 +- .../lib/src/rules/prefer_is_not_operator.dart | 9 +- .../src/rules/prefer_iterable_whereType.dart | 9 +- pkg/linter/lib/src/rules/prefer_mixin.dart | 10 +- .../rules/prefer_null_aware_method_calls.dart | 9 +- .../rules/prefer_null_aware_operators.dart | 9 +- .../src/rules/prefer_relative_imports.dart | 14 +- .../lib/src/rules/prefer_single_quotes.dart | 29 +- .../src/rules/prefer_spread_collections.dart | 9 +- ...prefer_typing_uninitialized_variables.dart | 27 +- .../lib/src/rules/prefer_void_to_null.dart | 14 +- .../rules/provide_deprecation_message.dart | 9 +- .../pub/depend_on_referenced_packages.dart | 9 +- .../lib/src/rules/pub/package_names.dart | 6 +- .../src/rules/pub/secure_pubspec_urls.dart | 5 +- .../src/rules/pub/sort_pub_dependencies.dart | 10 +- .../lib/src/rules/public_member_api_docs.dart | 14 +- .../lib/src/rules/recursive_getters.dart | 9 +- .../src/rules/require_trailing_commas.dart | 11 +- .../src/rules/sized_box_for_whitespace.dart | 9 +- .../src/rules/sized_box_shrink_expand.dart | 15 +- .../lib/src/rules/slash_for_doc_comments.dart | 9 +- .../src/rules/sort_child_properties_last.dart | 28 +- .../src/rules/sort_constructors_first.dart | 9 +- .../sort_unnamed_constructors_first.dart | 12 +- ...ecify_nonobvious_local_variable_types.dart | 22 +- .../specify_nonobvious_property_types.dart | 26 +- .../src/rules/strict_top_level_inference.dart | 58 +- pkg/linter/lib/src/rules/super_goes_last.dart | 10 +- .../lib/src/rules/test_types_in_equals.dart | 9 +- .../lib/src/rules/throw_in_finally.dart | 9 +- .../tighten_type_of_initializing_formals.dart | 19 +- .../src/rules/type_annotate_public_apis.dart | 9 +- .../lib/src/rules/type_init_formals.dart | 9 +- .../type_literal_in_constant_pattern.dart | 12 +- .../lib/src/rules/unawaited_futures.dart | 12 +- .../rules/unintended_html_in_doc_comment.dart | 104 +- .../lib/src/rules/unnecessary_async.dart | 20 +- .../rules/unnecessary_await_in_return.dart | 19 +- .../unnecessary_brace_in_string_interps.dart | 12 +- .../lib/src/rules/unnecessary_breaks.dart | 9 +- .../lib/src/rules/unnecessary_const.dart | 9 +- .../rules/unnecessary_constructor_name.dart | 9 +- .../lib/src/rules/unnecessary_final.dart | 36 +- .../rules/unnecessary_getters_setters.dart | 9 +- .../lib/src/rules/unnecessary_lambdas.dart | 44 +- .../lib/src/rules/unnecessary_late.dart | 9 +- .../rules/unnecessary_library_directive.dart | 5 +- .../src/rules/unnecessary_library_name.dart | 9 +- pkg/linter/lib/src/rules/unnecessary_new.dart | 10 +- .../unnecessary_null_aware_assignments.dart | 12 +- ...are_operator_on_extension_on_nullable.dart | 42 +- .../src/rules/unnecessary_null_checks.dart | 19 +- ...unnecessary_null_in_if_null_operators.dart | 12 +- ...lable_for_final_variable_declarations.dart | 15 +- .../lib/src/rules/unnecessary_overrides.dart | 13 +- .../src/rules/unnecessary_parenthesis.dart | 12 +- .../src/rules/unnecessary_raw_strings.dart | 9 +- .../lib/src/rules/unnecessary_statements.dart | 9 +- .../src/rules/unnecessary_string_escapes.dart | 20 +- .../unnecessary_string_interpolations.dart | 12 +- .../lib/src/rules/unnecessary_this.dart | 16 +- .../rules/unnecessary_to_list_in_spreads.dart | 9 +- .../src/rules/unnecessary_underscores.dart | 9 +- .../lib/src/rules/unreachable_from_main.dart | 111 +- .../rules/unrelated_type_equality_checks.dart | 25 +- pkg/linter/lib/src/rules/unsafe_html.dart | 9 +- pkg/linter/lib/src/rules/unsafe_variance.dart | 14 +- .../use_build_context_synchronously.dart | 408 ++++-- pkg/linter/lib/src/rules/use_colored_box.dart | 10 +- .../lib/src/rules/use_decorated_box.dart | 9 +- pkg/linter/lib/src/rules/use_enums.dart | 10 +- ...se_full_hex_values_for_flutter_colors.dart | 12 +- ...e_function_type_syntax_for_parameters.dart | 12 +- ...use_if_null_to_convert_nulls_to_bools.dart | 12 +- .../rules/use_is_even_rather_than_modulo.dart | 9 +- .../rules/use_key_in_widget_constructors.dart | 15 +- ...late_for_private_fields_and_variables.dart | 21 +- .../lib/src/rules/use_named_constants.dart | 29 +- pkg/linter/lib/src/rules/use_raw_strings.dart | 15 +- .../src/rules/use_rethrow_when_possible.dart | 9 +- .../use_setters_to_change_properties.dart | 12 +- .../lib/src/rules/use_string_buffers.dart | 9 +- .../use_string_in_part_of_directives.dart | 8 +- .../lib/src/rules/use_super_parameters.dart | 89 +- .../src/rules/use_test_throws_matchers.dart | 9 +- .../rules/use_to_and_as_if_applicable.dart | 9 +- .../src/rules/use_truncating_division.dart | 17 +- pkg/linter/lib/src/rules/valid_regexps.dart | 20 +- pkg/linter/lib/src/rules/void_checks.dart | 76 +- .../lib/src/test_utilities/lint_driver.dart | 5 +- .../src/test_utilities/linter_options.dart | 5 +- .../lib/src/test_utilities/test_linter.dart | 8 +- .../lib/src/util/dart_type_utilities.dart | 56 +- pkg/linter/lib/src/util/flutter_utils.dart | 44 +- .../lib/src/util/leak_detector_visitor.dart | 132 +- pkg/linter/lib/src/util/obvious_types.dart | 12 +- pkg/linter/lib/src/util/scope.dart | 10 +- pkg/linter/lib/src/util/variance_checker.dart | 20 +- pkg/linter/lib/src/utils.dart | 19 +- pkg/linter/pubspec.yaml | 2 +- pkg/linter/test/ascii_utils_test.dart | 15 +- pkg/linter/test/engine_test.dart | 6 +- pkg/linter/test/formatter_test.dart | 13 +- pkg/linter/test/lint_code_test.dart | 25 +- pkg/linter/test/mocks.dart | 10 +- pkg/linter/test/rule_test.dart | 2 +- pkg/linter/test/rule_test_support.dart | 133 +- .../always_declare_return_types_test.dart | 78 +- ...ays_put_control_body_on_new_line_test.dart | 78 +- ..._required_named_parameters_first_test.dart | 36 +- .../test/rules/always_specify_types_test.dart | 907 ++++++------ .../always_use_package_imports_test.dart | 18 +- .../rules/analyzer_use_new_elements_test.dart | 50 +- .../test/rules/annotate_overrides_test.dart | 71 +- .../test/rules/annotate_redeclares_test.dart | 27 +- .../avoid_annotating_with_dynamic_test.dart | 70 +- ...erals_in_conditional_expressions_test.dart | 45 +- ...avoid_catches_without_on_clauses_test.dart | 42 +- .../rules/avoid_catching_errors_test.dart | 45 +- ...classes_with_only_static_members_test.dart | 26 +- .../avoid_double_and_int_checks_test.dart | 18 +- .../test/rules/avoid_dynamic_calls_test.dart | 396 +++--- .../test/rules/avoid_empty_else_test.dart | 33 +- ...and_hash_code_on_mutable_classes_test.dart | 49 +- .../avoid_escaping_inner_quotes_test.dart | 45 +- ...ld_initializers_in_const_classes_test.dart | 27 +- ...nitializers_in_non_const_classes_test.dart | 27 +- .../rules/avoid_final_parameters_test.dart | 128 +- ...nction_literals_in_foreach_calls_test.dart | 49 +- .../test/rules/avoid_futureor_void_test.dart | 162 ++- .../avoid_implementing_value_types_test.dart | 18 +- .../test/rules/avoid_init_to_null_test.dart | 161 ++- .../rules/avoid_js_rounded_ints_test.dart | 27 +- ...d_multiple_declarations_per_line_test.dart | 36 +- ...ull_checks_in_equality_operators_test.dart | 87 +- ...id_positional_boolean_parameters_test.dart | 99 +- pkg/linter/test/rules/avoid_print_test.dart | 27 +- .../avoid_private_typedef_functions_test.dart | 53 +- .../avoid_redundant_argument_values_test.dart | 132 +- .../avoid_relative_lib_imports_test.dart | 8 +- ...avoid_renaming_method_parameters_test.dart | 88 +- .../avoid_return_types_on_setters_test.dart | 27 +- .../avoid_returning_null_for_void_test.dart | 126 +- .../test/rules/avoid_returning_this_test.dart | 45 +- .../avoid_setters_without_getters_test.dart | 27 +- .../avoid_shadowing_type_parameters_test.dart | 124 +- ...cascade_in_expression_statements_test.dart | 9 +- .../test/rules/avoid_slow_async_io_test.dart | 81 +- .../test/rules/avoid_type_to_string_test.dart | 135 +- .../avoid_types_as_parameter_names_test.dart | 117 +- ...void_types_on_closure_parameters_test.dart | 54 +- .../avoid_unnecessary_containers_test.dart | 9 +- ...id_unused_constructor_parameters_test.dart | 45 +- .../test/rules/avoid_void_async_test.dart | 102 +- .../avoid_web_libraries_in_flutter_test.dart | 4 +- .../test/rules/await_only_futures_test.dart | 35 +- .../rules/camel_case_extensions_test.dart | 18 +- .../test/rules/camel_case_types_test.dart | 90 +- .../test/rules/cancel_subscriptions_test.dart | 36 +- .../test/rules/cascade_invocations_test.dart | 64 +- .../cast_nullable_to_non_nullable_test.dart | 22 +- pkg/linter/test/rules/close_sinks_test.dart | 18 +- ...ollection_methods_unrelated_type_test.dart | 48 +- .../test/rules/combinators_ordering_test.dart | 27 +- .../test/rules/comment_references_test.dart | 72 +- .../conditional_uri_does_not_exist_test.dart | 30 +- .../rules/constant_identifier_names_test.dart | 110 +- .../rules/control_flow_in_finally_test.dart | 27 +- ...races_in_flow_control_structures_test.dart | 144 +- .../depend_on_referenced_packages_test.dart | 60 +- .../rules/deprecated_consistency_test.dart | 36 +- ...ted_member_use_from_same_package_test.dart | 410 +++--- ...agnostic_describe_all_properties_test.dart | 27 +- .../test/rules/directives_ordering_test.dart | 177 +-- .../test/rules/discarded_futures_test.dart | 83 +- .../rules/do_not_use_environment_test.dart | 36 +- .../test/rules/document_ignores_test.dart | 12 +- pkg/linter/test/rules/empty_catches_test.dart | 9 +- .../rules/empty_constructor_bodies_test.dart | 9 +- .../test/rules/empty_statements_test.dart | 73 +- .../test/rules/eol_at_end_of_file_test.dart | 18 +- .../erase_dart_type_extension_types_test.dart | 18 +- .../test/rules/exhaustive_cases_test.dart | 31 +- pkg/linter/test/rules/file_names_test.dart | 9 +- .../test/rules/flutter_style_todos_test.dart | 75 +- .../test/rules/hash_and_equals_test.dart | 72 +- .../rules/implementation_imports_test.dart | 36 +- .../rules/implicit_call_tearoffs_test.dart | 216 +-- .../test/rules/implicit_reopen_test.dart | 229 ++-- .../rules/invalid_case_patterns_test.dart | 174 +-- ...time_check_with_js_interop_types_test.dart | 1218 ++++++++++------- .../join_return_with_assignment_test.dart | 73 +- ...ng_newlines_in_multiline_strings_test.dart | 18 +- .../test/rules/library_annotations_test.dart | 15 +- pkg/linter/test/rules/library_names_test.dart | 18 +- .../test/rules/library_prefixes_test.dart | 33 +- ...rary_private_types_in_public_api_test.dart | 357 ++--- .../lines_longer_than_80_chars_test.dart | 25 +- ...literal_only_boolean_expressions_test.dart | 134 +- .../rules/matching_super_parameters_test.dart | 45 +- ...de_block_language_in_doc_comment_test.dart | 27 +- ...tespace_between_adjacent_strings_test.dart | 31 +- .../no_adjacent_strings_in_list_test.dart | 63 +- .../test/rules/no_default_cases_test.dart | 18 +- .../rules/no_duplicate_case_values_test.dart | 96 +- ...underscores_for_library_prefixes_test.dart | 24 +- ...nderscores_for_local_identifiers_test.dart | 217 +-- .../no_literal_bool_comparisons_test.dart | 36 +- .../rules/no_logic_in_create_state_test.dart | 45 +- .../rules/no_runtimeType_toString_test.dart | 45 +- .../test/rules/no_self_assignments_test.dart | 28 +- .../rules/no_wildcard_variable_uses_test.dart | 18 +- .../non_constant_identifier_names_test.dart | 389 +++--- .../rules/noop_primitive_operations_test.dart | 106 +- ...check_on_nullable_type_parameter_test.dart | 191 +-- pkg/linter/test/rules/null_closures_test.dart | 50 +- .../rules/omit_local_variable_types_test.dart | 63 +- ...mit_obvious_local_variable_types_test.dart | 135 +- .../omit_obvious_property_types_test.dart | 234 ++-- .../test/rules/one_member_abstracts_test.dart | 38 +- .../test/rules/only_throw_errors_test.dart | 27 +- .../test/rules/overridden_fields_test.dart | 151 +- pkg/linter/test/rules/package_names_test.dart | 33 +- .../package_prefixed_library_names_test.dart | 9 +- .../rules/parameter_assignments_test.dart | 251 ++-- ...er_adjacent_string_concatenation_test.dart | 18 +- ...fer_asserts_in_initializer_lists_test.dart | 113 +- .../prefer_asserts_with_message_test.dart | 18 +- .../prefer_collection_literals_test.dart | 184 +-- .../prefer_conditional_assignment_test.dart | 45 +- ...const_constructors_in_immutables_test.dart | 162 ++- .../rules/prefer_const_constructors_test.dart | 113 +- .../rules/prefer_const_declarations_test.dart | 207 +-- ...st_literals_to_create_immutables_test.dart | 126 +- ...constructors_over_static_methods_test.dart | 36 +- .../test/rules/prefer_contains_test.dart | 365 ++--- .../test/rules/prefer_double_quotes_test.dart | 36 +- ...refer_expression_function_bodies_test.dart | 27 +- .../test/rules/prefer_final_fields_test.dart | 142 +- .../rules/prefer_final_in_for_each_test.dart | 54 +- .../test/rules/prefer_final_locals_test.dart | 241 ++-- .../rules/prefer_final_parameters_test.dart | 129 +- ...for_elements_to_map_fromIterable_test.dart | 27 +- .../test/rules/prefer_foreach_test.dart | 54 +- ...tion_declarations_over_variables_test.dart | 27 +- ...er_generic_function_type_aliases_test.dart | 31 +- ...ments_to_conditional_expressions_test.dart | 36 +- .../rules/prefer_if_null_operators_test.dart | 45 +- .../prefer_initializing_formals_test.dart | 65 +- .../test/rules/prefer_inlined_adds_test.dart | 27 +- .../test/rules/prefer_int_literals_test.dart | 152 +- ...interpolation_to_compose_strings_test.dart | 99 +- .../test/rules/prefer_is_empty_test.dart | 298 ++-- .../test/rules/prefer_is_not_empty_test.dart | 45 +- .../rules/prefer_is_not_operator_test.dart | 9 +- .../rules/prefer_iterable_whereType_test.dart | 27 +- pkg/linter/test/rules/prefer_mixin_test.dart | 18 +- .../prefer_null_aware_method_calls_test.dart | 45 +- .../prefer_null_aware_operators_test.dart | 117 +- .../rules/prefer_relative_imports_test.dart | 18 +- .../test/rules/prefer_single_quotes_test.dart | 45 +- .../rules/prefer_spread_collections_test.dart | 72 +- ...r_typing_uninitialized_variables_test.dart | 71 +- .../test/rules/prefer_void_to_null_test.dart | 180 +-- .../provide_deprecation_message_test.dart | 9 +- .../rules/public_member_api_docs_test.dart | 296 ++-- .../test/rules/recursive_getters_test.dart | 108 +- .../rules/require_trailing_commas_test.dart | 198 +-- .../test/rules/secure_pubspec_urls_test.dart | 81 +- .../rules/sized_box_for_whitespace_test.dart | 45 +- .../rules/sized_box_shrink_expand_test.dart | 18 +- .../rules/slash_for_doc_comments_test.dart | 144 +- .../sort_child_properties_last_test.dart | 28 +- .../rules/sort_constructors_first_test.dart | 55 +- .../rules/sort_pub_dependencies_test.dart | 27 +- .../sort_unnamed_constructors_first_test.dart | 40 +- ..._nonobvious_local_variable_types_test.dart | 73 +- ...pecify_nonobvious_property_types_test.dart | 138 +- .../strict_top_level_inference_test.dart | 553 +++++--- .../test/rules/test_types_in_equals_test.dart | 9 +- .../test/rules/throw_in_finally_test.dart | 9 +- ...ten_type_of_initializing_formals_test.dart | 44 +- .../rules/type_annotate_public_apis_test.dart | 221 +-- .../test/rules/type_init_formals_test.dart | 72 +- ...type_literal_in_constant_pattern_test.dart | 72 +- .../test/rules/unawaited_futures_test.dart | 49 +- .../unintended_html_in_doc_comment_test.dart | 133 +- .../test/rules/unnecessary_async_test.dart | 173 +-- .../unnecessary_await_in_return_test.dart | 63 +- ...ecessary_brace_in_string_interps_test.dart | 36 +- .../test/rules/unnecessary_breaks_test.dart | 50 +- .../test/rules/unnecessary_const_test.dart | 99 +- .../unnecessary_constructor_name_test.dart | 69 +- .../test/rules/unnecessary_final_test.dart | 154 ++- .../unnecessary_getters_setters_test.dart | 40 +- .../test/rules/unnecessary_lambdas_test.dart | 72 +- .../test/rules/unnecessary_late_test.dart | 27 +- .../unnecessary_library_directive_test.dart | 9 +- .../rules/unnecessary_library_name_test.dart | 9 +- .../test/rules/unnecessary_new_test.dart | 27 +- ...necessary_null_aware_assignments_test.dart | 9 +- ...perator_on_extension_on_nullable_test.dart | 93 +- .../rules/unnecessary_null_checks_test.dart | 251 ++-- ...essary_null_in_if_null_operators_test.dart | 112 +- ..._for_final_variable_declarations_test.dart | 60 +- .../rules/unnecessary_overrides_test.dart | 90 +- .../rules/unnecessary_parenthesis_test.dart | 412 +++--- .../rules/unnecessary_raw_strings_test.dart | 36 +- .../rules/unnecessary_statements_test.dart | 279 ++-- .../unnecessary_string_escapes_test.dart | 87 +- ...nnecessary_string_interpolations_test.dart | 36 +- .../test/rules/unnecessary_this_test.dart | 72 +- .../unnecessary_to_list_in_spreads_test.dart | 45 +- .../rules/unnecessary_underscores_test.dart | 128 +- .../rules/unreachable_from_main_test.dart | 443 +++--- .../unrelated_type_equality_checks_test.dart | 164 ++- .../test/rules/unsafe_variance_test.dart | 63 +- .../use_build_context_synchronously_test.dart | 930 ++++++++----- .../test/rules/use_colored_box_test.dart | 9 +- .../test/rules/use_decorated_box_test.dart | 18 +- pkg/linter/test/rules/use_enums_test.dart | 202 +-- ...ll_hex_values_for_flutter_colors_test.dart | 36 +- ...ction_type_syntax_for_parameters_test.dart | 9 +- ...f_null_to_convert_nulls_to_bools_test.dart | 18 +- .../use_is_even_rather_than_modulo_test.dart | 40 +- .../use_key_in_widget_constructors_test.dart | 63 +- ...for_private_fields_and_variables_test.dart | 167 ++- .../test/rules/use_named_constants_test.dart | 45 +- .../test/rules/use_raw_strings_test.dart | 54 +- .../rules/use_rethrow_when_possible_test.dart | 18 +- ...use_setters_to_change_properties_test.dart | 27 +- .../test/rules/use_string_buffers_test.dart | 90 +- ...use_string_in_part_of_directives_test.dart | 13 +- .../test/rules/use_super_parameters_test.dart | 120 +- .../rules/use_test_throws_matchers_test.dart | 14 +- .../use_to_and_as_if_applicable_test.dart | 54 +- .../rules/use_truncating_division_test.dart | 27 +- pkg/linter/test/rules/valid_regexps_test.dart | 9 +- pkg/linter/test/rules/void_checks_test.dart | 125 +- pkg/linter/test/scope_util_test.dart | 92 +- pkg/linter/test/utils_test.dart | 66 +- .../validate_incompatible_rules_test.dart | 22 +- ...e_no_rule_description_references_test.dart | 35 +- ...validate_rule_description_format_test.dart | 17 +- .../test/verify_generated_files_test.dart | 6 +- .../verify_reflective_test_suites_test.dart | 32 +- pkg/linter/tool/benchmark.dart | 97 +- pkg/linter/tool/checks/check_all_yaml.dart | 9 +- .../tool/checks/check_messages_yaml.dart | 6 +- pkg/linter/tool/checks/driver.dart | 15 +- .../tool/checks/rules/no_solo_tests.dart | 21 +- .../tool/checks/rules/no_trailing_spaces.dart | 19 +- .../checks/rules/visit_registered_nodes.dart | 27 +- pkg/linter/tool/generate_lints.dart | 12 +- pkg/linter/tool/lint_sets.dart | 3 +- pkg/linter/tool/machine.dart | 27 +- pkg/linter/tool/messages_info.dart | 164 ++- pkg/linter/tool/migrate.dart | 54 +- pkg/linter/tool/rule.dart | 98 +- pkg/linter/tool/scorecard.dart | 39 +- pkg/linter/tool/util/formatter.dart | 11 +- pkg/linter/tool/util/lint_driver.dart | 5 +- pkg/linter/tool/util/path_utils.dart | 6 +- 523 files changed, 16394 insertions(+), 12902 deletions(-) diff --git a/pkg/linter/lib/src/ast.dart b/pkg/linter/lib/src/ast.dart index bc956a1016e5..afd608a237e2 100644 --- a/pkg/linter/lib/src/ast.dart +++ b/pkg/linter/lib/src/ast.dart @@ -361,8 +361,11 @@ List _collectReservedWords() { return reserved; } -int? _getIntValue(Expression expression, LinterContext? context, - {bool negated = false}) { +int? _getIntValue( + Expression expression, + LinterContext? context, { + bool negated = false, +}) { int? value; if (expression is IntegerLiteral) { value = expression.value; diff --git a/pkg/linter/lib/src/extensions.dart b/pkg/linter/lib/src/extensions.dart index fe12b0351630..cb44badf426e 100644 --- a/pkg/linter/lib/src/extensions.dart +++ b/pkg/linter/lib/src/extensions.dart @@ -10,8 +10,7 @@ import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/file_system/physical_file_system.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; // ignore: implementation_imports import 'package:analyzer/src/dart/element/type.dart' // ignore: implementation_imports - show - InvalidTypeImpl; + show InvalidTypeImpl; import 'package:collection/collection.dart'; import 'analyzer.dart'; @@ -54,7 +53,7 @@ extension AstNodeExtension on AstNode { TopLevelVariableDeclaration() => self.augmentKeyword != null, VariableDeclaration(declaredFragment: var fragment?) => fragment is PropertyInducingFragment && fragment.isAugmentation, - _ => false + _ => false, }; } @@ -299,10 +298,11 @@ extension DartTypeExtension on DartType? { } static bool _extendsClass( - InterfaceType? type, - Set seenElements, - String? className, - String? library) => + InterfaceType? type, + Set seenElements, + String? className, + String? library, + ) => type != null && seenElements.add(type.element3) && (type.isSameAs(className, library) || @@ -311,9 +311,9 @@ extension DartTypeExtension on DartType? { extension ElementExtension on Element2? { Element2? get canonicalElement2 => switch (this) { - PropertyAccessorElement2(:var variable3?) => variable3, - _ => this, - }; + PropertyAccessorElement2(:var variable3?) => variable3, + _ => this, + }; bool get isDartCorePrint { var self = this; @@ -323,9 +323,9 @@ extension ElementExtension on Element2? { } bool get isMacro => switch (this) { - ClassElement2(:var isMacro) => isMacro, - _ => false, - }; + ClassElement2(:var isMacro) => isMacro, + _ => false, + }; } extension ExpressionExtension on Expression? { @@ -494,9 +494,10 @@ extension InterfaceTypeExtension on InterfaceType { /// including itself. Iterable get implementedInterfaces { void searchSupertypes( - InterfaceType? type, - Set alreadyVisited, - List interfaceTypes) { + InterfaceType? type, + Set alreadyVisited, + List interfaceTypes, + ) { if (type == null || !alreadyVisited.add(type.element3)) { return; } @@ -516,8 +517,9 @@ extension InterfaceTypeExtension on InterfaceType { } GetterElement? getGetter2(String name, {LibraryElement2? library}) => - getters.firstWhereOrNull((s) => - s.name3 == name && (library == null || (s.library2 == library))); + getters.firstWhereOrNull( + (s) => s.name3 == name && (library == null || (s.library2 == library)), + ); SetterElement? getSetter2(String name) => setters.firstWhereOrNull((s) => s.canonicalName == name); @@ -544,16 +546,19 @@ extension MethodDeclarationExtension on MethodDeclaration { if (isGetter) { // Search supertypes for a getter of the same name. - return parentElement.allSupertypes - .any((t) => t.lookUpGetter3(name, parentLibrary) != null); + return parentElement.allSupertypes.any( + (t) => t.lookUpGetter3(name, parentLibrary) != null, + ); } else if (isSetter) { // Search supertypes for a setter of the same name. - return parentElement.allSupertypes - .any((t) => t.lookUpSetter3(name, parentLibrary) != null); + return parentElement.allSupertypes.any( + (t) => t.lookUpSetter3(name, parentLibrary) != null, + ); } else { // Search supertypes for a method of the same name. - return parentElement.allSupertypes - .any((t) => t.lookUpMethod3(name, parentLibrary) != null); + return parentElement.allSupertypes.any( + (t) => t.lookUpMethod3(name, parentLibrary) != null, + ); } } @@ -561,7 +566,8 @@ extension MethodDeclarationExtension on MethodDeclaration { lookUpInheritedMethod(inheritanceManager) != null; MethodElement2? lookUpInheritedMethod( - InheritanceManager3 inheritanceManager) { + InheritanceManager3 inheritanceManager, + ) { var declaredElement = declaredFragment?.element; if (declaredElement != null) { var parent = declaredElement.enclosingElement2; @@ -605,10 +611,10 @@ extension TokenExtension on Token? { extension TokenTypeExtension on TokenType { TokenType get inverted => switch (this) { - TokenType.LT_EQ => TokenType.GT_EQ, - TokenType.LT => TokenType.GT, - TokenType.GT => TokenType.LT, - TokenType.GT_EQ => TokenType.LT_EQ, - _ => this - }; + TokenType.LT_EQ => TokenType.GT_EQ, + TokenType.LT => TokenType.GT, + TokenType.GT => TokenType.LT, + TokenType.GT_EQ => TokenType.LT_EQ, + _ => this, + }; } diff --git a/pkg/linter/lib/src/lint_codes.g.dart b/pkg/linter/lib/src/lint_codes.g.dart index 72762f5163d1..532f30109b64 100644 --- a/pkg/linter/lib/src/lint_codes.g.dart +++ b/pkg/linter/lib/src/lint_codes.g.dart @@ -22,12 +22,12 @@ import 'analyzer.dart'; class LinterLintCode extends LintCode { static const LintCode always_declare_return_types_of_functions = LinterLintCode( - LintNames.always_declare_return_types, - "The function '{0}' should have a return type but doesn't.", - correctionMessage: "Try adding a return type to the function.", - hasPublishedDocs: true, - uniqueName: 'always_declare_return_types_of_functions', - ); + LintNames.always_declare_return_types, + "The function '{0}' should have a return type but doesn't.", + correctionMessage: "Try adding a return type to the function.", + hasPublishedDocs: true, + uniqueName: 'always_declare_return_types_of_functions', + ); static const LintCode always_declare_return_types_of_methods = LinterLintCode( LintNames.always_declare_return_types, @@ -46,13 +46,13 @@ class LinterLintCode extends LintCode { static const LintCode always_put_required_named_parameters_first = LinterLintCode( - LintNames.always_put_required_named_parameters_first, - "Required named parameters should be before optional named parameters.", - correctionMessage: - "Try moving the required named parameter to be before any optional " - "named parameters.", - hasPublishedDocs: true, - ); + LintNames.always_put_required_named_parameters_first, + "Required named parameters should be before optional named parameters.", + correctionMessage: + "Try moving the required named parameter to be before any optional " + "named parameters.", + hasPublishedDocs: true, + ); static const LintCode always_specify_types_add_type = LinterLintCode( LintNames.always_specify_types, @@ -113,11 +113,11 @@ class LinterLintCode extends LintCode { static const LintCode avoid_bool_literals_in_conditional_expressions = LinterLintCode( - LintNames.avoid_bool_literals_in_conditional_expressions, - "Conditional expressions with a 'bool' literal can be simplified.", - correctionMessage: - "Try rewriting the expression to use either '&&' or '||'.", - ); + LintNames.avoid_bool_literals_in_conditional_expressions, + "Conditional expressions with a 'bool' literal can be simplified.", + correctionMessage: + "Try rewriting the expression to use either '&&' or '||'.", + ); static const LintCode avoid_catches_without_on_clauses = LinterLintCode( LintNames.avoid_catches_without_on_clauses, @@ -169,8 +169,8 @@ class LinterLintCode extends LintCode { hasPublishedDocs: true, ); - static const LintCode avoid_equals_and_hash_code_on_mutable_classes = - LinterLintCode( + static const LintCode + avoid_equals_and_hash_code_on_mutable_classes = LinterLintCode( LintNames.avoid_equals_and_hash_code_on_mutable_classes, "The method '{0}' should not be overridden in classes not annotated with " "'@immutable'.", @@ -184,8 +184,8 @@ class LinterLintCode extends LintCode { correctionMessage: "Try changing the outer quotes to '{1}'.", ); - static const LintCode avoid_field_initializers_in_const_classes = - LinterLintCode( + static const LintCode + avoid_field_initializers_in_const_classes = LinterLintCode( LintNames.avoid_field_initializers_in_const_classes, "Fields in 'const' classes should not have initializers.", correctionMessage: @@ -201,11 +201,11 @@ class LinterLintCode extends LintCode { static const LintCode avoid_function_literals_in_foreach_calls = LinterLintCode( - LintNames.avoid_function_literals_in_foreach_calls, - "Function literals shouldn't be passed to 'forEach'.", - correctionMessage: "Try using a 'for' loop.", - hasPublishedDocs: true, - ); + LintNames.avoid_function_literals_in_foreach_calls, + "Function literals shouldn't be passed to 'forEach'.", + correctionMessage: "Try using a 'for' loop.", + hasPublishedDocs: true, + ); static const LintCode avoid_futureor_void = LinterLintCode( LintNames.avoid_futureor_void, @@ -242,10 +242,10 @@ class LinterLintCode extends LintCode { static const LintCode avoid_null_checks_in_equality_operators = LinterLintCode( - LintNames.avoid_null_checks_in_equality_operators, - "Unnecessary null comparison in implementation of '=='.", - correctionMessage: "Try removing the comparison.", - ); + LintNames.avoid_null_checks_in_equality_operators, + "Unnecessary null comparison in implementation of '=='.", + correctionMessage: "Try removing the comparison.", + ); static const LintCode avoid_positional_boolean_parameters = LinterLintCode( LintNames.avoid_positional_boolean_parameters, @@ -299,21 +299,21 @@ class LinterLintCode extends LintCode { static const LintCode avoid_returning_null_for_void_from_function = LinterLintCode( - LintNames.avoid_returning_null_for_void, - "Don't return 'null' from a function with a return type of 'void'.", - correctionMessage: "Try removing the 'null'.", - hasPublishedDocs: true, - uniqueName: 'avoid_returning_null_for_void_from_function', - ); + LintNames.avoid_returning_null_for_void, + "Don't return 'null' from a function with a return type of 'void'.", + correctionMessage: "Try removing the 'null'.", + hasPublishedDocs: true, + uniqueName: 'avoid_returning_null_for_void_from_function', + ); static const LintCode avoid_returning_null_for_void_from_method = LinterLintCode( - LintNames.avoid_returning_null_for_void, - "Don't return 'null' from a method with a return type of 'void'.", - correctionMessage: "Try removing the 'null'.", - hasPublishedDocs: true, - uniqueName: 'avoid_returning_null_for_void_from_method', - ); + LintNames.avoid_returning_null_for_void, + "Don't return 'null' from a method with a return type of 'void'.", + correctionMessage: "Try removing the 'null'.", + hasPublishedDocs: true, + uniqueName: 'avoid_returning_null_for_void_from_method', + ); static const LintCode avoid_returning_this = LinterLintCode( LintNames.avoid_returning_this, @@ -338,11 +338,11 @@ class LinterLintCode extends LintCode { static const LintCode avoid_single_cascade_in_expression_statements = LinterLintCode( - LintNames.avoid_single_cascade_in_expression_statements, - "Unnecessary cascade expression.", - correctionMessage: "Try using the operator '{0}'.", - hasPublishedDocs: true, - ); + LintNames.avoid_single_cascade_in_expression_statements, + "Unnecessary cascade expression.", + correctionMessage: "Try using the operator '{0}'.", + hasPublishedDocs: true, + ); static const LintCode avoid_slow_async_io = LinterLintCode( LintNames.avoid_slow_async_io, @@ -429,7 +429,8 @@ class LinterLintCode extends LintCode { static const LintCode cancel_subscriptions = LinterLintCode( LintNames.cancel_subscriptions, "Uncancelled instance of 'StreamSubscription'.", - correctionMessage: "Try invoking 'cancel' in the function in which the " + correctionMessage: + "Try invoking 'cancel' in the function in which the " "'StreamSubscription' was created.", hasPublishedDocs: true, ); @@ -499,11 +500,11 @@ class LinterLintCode extends LintCode { static const LintCode curly_braces_in_flow_control_structures = LinterLintCode( - LintNames.curly_braces_in_flow_control_structures, - "Statements in {0} should be enclosed in a block.", - correctionMessage: "Try wrapping the statement in a block.", - hasPublishedDocs: true, - ); + LintNames.curly_braces_in_flow_control_structures, + "Statements in {0} should be enclosed in a block.", + correctionMessage: "Try wrapping the statement in a block.", + hasPublishedDocs: true, + ); static const LintCode dangling_library_doc_comments = LinterLintCode( LintNames.dangling_library_doc_comments, @@ -542,8 +543,8 @@ class LinterLintCode extends LintCode { uniqueName: 'deprecated_consistency_parameter', ); - static const LintCode deprecated_member_use_from_same_package_with_message = - LinterLintCode( + static const LintCode + deprecated_member_use_from_same_package_with_message = LinterLintCode( LintNames.deprecated_member_use_from_same_package, "'{0}' is deprecated and shouldn't be used. {1}", correctionMessage: @@ -553,7 +554,7 @@ class LinterLintCode extends LintCode { ); static const LintCode - deprecated_member_use_from_same_package_without_message = LinterLintCode( + deprecated_member_use_from_same_package_without_message = LinterLintCode( LintNames.deprecated_member_use_from_same_package, "'{0}' is deprecated and shouldn't be used.", correctionMessage: @@ -592,11 +593,11 @@ class LinterLintCode extends LintCode { static const LintCode directives_ordering_package_before_relative = LinterLintCode( - LintNames.directives_ordering, - "Place 'package:' {0}s before relative {0}s.", - correctionMessage: "Try sorting the directives.", - uniqueName: 'directives_ordering_package_before_relative', - ); + LintNames.directives_ordering, + "Place 'package:' {0}s before relative {0}s.", + correctionMessage: "Try sorting the directives.", + uniqueName: 'directives_ordering_package_before_relative', + ); static const LintCode discarded_futures = LinterLintCode( LintNames.discarded_futures, @@ -713,8 +714,8 @@ class LinterLintCode extends LintCode { correctionMessage: "Try refactoring the expression to be valid in 3.0.", ); - static const LintCode invalid_runtime_check_with_js_interop_types_dart_as_js = - LinterLintCode( + static const LintCode + invalid_runtime_check_with_js_interop_types_dart_as_js = LinterLintCode( LintNames.invalid_runtime_check_with_js_interop_types, "Cast from '{0}' to '{1}' casts a Dart value to a JS interop type, which " "might not be platform-consistent.", @@ -725,16 +726,16 @@ class LinterLintCode extends LintCode { uniqueName: 'invalid_runtime_check_with_js_interop_types_dart_as_js', ); - static const LintCode invalid_runtime_check_with_js_interop_types_dart_is_js = - LinterLintCode( + static const LintCode + invalid_runtime_check_with_js_interop_types_dart_is_js = LinterLintCode( LintNames.invalid_runtime_check_with_js_interop_types, "Runtime check between '{0}' and '{1}' checks whether a Dart value is a JS " "interop type, which might not be platform-consistent.", uniqueName: 'invalid_runtime_check_with_js_interop_types_dart_is_js', ); - static const LintCode invalid_runtime_check_with_js_interop_types_js_as_dart = - LinterLintCode( + static const LintCode + invalid_runtime_check_with_js_interop_types_js_as_dart = LinterLintCode( LintNames.invalid_runtime_check_with_js_interop_types, "Cast from '{0}' to '{1}' casts a JS interop value to a Dart type, which " "might not be platform-consistent.", @@ -745,17 +746,17 @@ class LinterLintCode extends LintCode { ); static const LintCode - invalid_runtime_check_with_js_interop_types_js_as_incompatible_js = + invalid_runtime_check_with_js_interop_types_js_as_incompatible_js = LinterLintCode( - LintNames.invalid_runtime_check_with_js_interop_types, - "Cast from '{0}' to '{1}' casts a JS interop value to an incompatible JS " - "interop type, which might not be platform-consistent.", - uniqueName: - 'invalid_runtime_check_with_js_interop_types_js_as_incompatible_js', - ); + LintNames.invalid_runtime_check_with_js_interop_types, + "Cast from '{0}' to '{1}' casts a JS interop value to an incompatible JS " + "interop type, which might not be platform-consistent.", + uniqueName: + 'invalid_runtime_check_with_js_interop_types_js_as_incompatible_js', + ); - static const LintCode invalid_runtime_check_with_js_interop_types_js_is_dart = - LinterLintCode( + static const LintCode + invalid_runtime_check_with_js_interop_types_js_is_dart = LinterLintCode( LintNames.invalid_runtime_check_with_js_interop_types, "Runtime check between '{0}' and '{1}' checks whether a JS interop value " "is a Dart type, which might not be platform-consistent.", @@ -763,22 +764,21 @@ class LinterLintCode extends LintCode { ); static const LintCode - invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js = + invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js = LinterLintCode( - LintNames.invalid_runtime_check_with_js_interop_types, - "Runtime check between '{0}' and '{1}' involves a non-trivial runtime " - "check between two JS interop types that might not be " - "platform-consistent.", - correctionMessage: - "Try using a JS interop member like 'isA' from 'dart:js_interop' to " - "check the underlying type of JS interop values.", - uniqueName: - 'invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js', - ); + LintNames.invalid_runtime_check_with_js_interop_types, + "Runtime check between '{0}' and '{1}' involves a non-trivial runtime " + "check between two JS interop types that might not be " + "platform-consistent.", + correctionMessage: + "Try using a JS interop member like 'isA' from 'dart:js_interop' to " + "check the underlying type of JS interop values.", + uniqueName: + 'invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js', + ); static const LintCode - invalid_runtime_check_with_js_interop_types_js_is_unrelated_js = - LinterLintCode( + invalid_runtime_check_with_js_interop_types_js_is_unrelated_js = LinterLintCode( LintNames.invalid_runtime_check_with_js_interop_types, "Runtime check between '{0}' and '{1}' involves a runtime check between a " "JS interop value and an unrelated JS interop type that will always be " @@ -862,17 +862,17 @@ class LinterLintCode extends LintCode { static const LintCode missing_code_block_language_in_doc_comment = LinterLintCode( - LintNames.missing_code_block_language_in_doc_comment, - "The code block is missing a specified language.", - correctionMessage: "Try adding a language to the code block.", - ); + LintNames.missing_code_block_language_in_doc_comment, + "The code block is missing a specified language.", + correctionMessage: "Try adding a language to the code block.", + ); static const LintCode missing_whitespace_between_adjacent_strings = LinterLintCode( - LintNames.missing_whitespace_between_adjacent_strings, - "Missing whitespace between adjacent strings.", - correctionMessage: "Try adding whitespace between the strings.", - ); + LintNames.missing_whitespace_between_adjacent_strings, + "Missing whitespace between adjacent strings.", + correctionMessage: "Try adding whitespace between the strings.", + ); static const LintCode no_adjacent_strings_in_list = LinterLintCode( LintNames.no_adjacent_strings_in_list, @@ -898,21 +898,21 @@ class LinterLintCode extends LintCode { static const LintCode no_leading_underscores_for_library_prefixes = LinterLintCode( - LintNames.no_leading_underscores_for_library_prefixes, - "The library prefix '{0}' starts with an underscore.", - correctionMessage: - "Try renaming the prefix to not start with an underscore.", - hasPublishedDocs: true, - ); + LintNames.no_leading_underscores_for_library_prefixes, + "The library prefix '{0}' starts with an underscore.", + correctionMessage: + "Try renaming the prefix to not start with an underscore.", + hasPublishedDocs: true, + ); static const LintCode no_leading_underscores_for_local_identifiers = LinterLintCode( - LintNames.no_leading_underscores_for_local_identifiers, - "The local variable '{0}' starts with an underscore.", - correctionMessage: - "Try renaming the variable to not start with an underscore.", - hasPublishedDocs: true, - ); + LintNames.no_leading_underscores_for_local_identifiers, + "The local variable '{0}' starts with an underscore.", + correctionMessage: + "Try renaming the variable to not start with an underscore.", + hasPublishedDocs: true, + ); static const LintCode no_literal_bool_comparisons = LinterLintCode( LintNames.no_literal_bool_comparisons, @@ -1084,11 +1084,11 @@ class LinterLintCode extends LintCode { static const LintCode prefer_const_constructors_in_immutables = LinterLintCode( - LintNames.prefer_const_constructors_in_immutables, - "Constructors in '@immutable' classes should be declared as 'const'.", - correctionMessage: "Try adding 'const' to the constructor declaration.", - hasPublishedDocs: true, - ); + LintNames.prefer_const_constructors_in_immutables, + "Constructors in '@immutable' classes should be declared as 'const'.", + correctionMessage: "Try adding 'const' to the constructor declaration.", + hasPublishedDocs: true, + ); static const LintCode prefer_const_declarations = LinterLintCode( LintNames.prefer_const_declarations, @@ -1099,19 +1099,19 @@ class LinterLintCode extends LintCode { static const LintCode prefer_const_literals_to_create_immutables = LinterLintCode( - LintNames.prefer_const_literals_to_create_immutables, - "Use 'const' literals as arguments to constructors of '@immutable' " - "classes.", - correctionMessage: "Try adding 'const' before the literal.", - hasPublishedDocs: true, - ); + LintNames.prefer_const_literals_to_create_immutables, + "Use 'const' literals as arguments to constructors of '@immutable' " + "classes.", + correctionMessage: "Try adding 'const' before the literal.", + hasPublishedDocs: true, + ); static const LintCode prefer_constructors_over_static_methods = LinterLintCode( - LintNames.prefer_constructors_over_static_methods, - "Static method should be a constructor.", - correctionMessage: "Try converting the method into a constructor.", - ); + LintNames.prefer_constructors_over_static_methods, + "Static method should be a constructor.", + correctionMessage: "Try converting the method into a constructor.", + ); static const LintCode prefer_contains_always_false = LinterLintCode( LintNames.prefer_contains, @@ -1182,11 +1182,12 @@ class LinterLintCode extends LintCode { static const LintCode prefer_for_elements_to_map_fromIterable = LinterLintCode( - LintNames.prefer_for_elements_to_map_fromIterable, - "Use 'for' elements when building maps from iterables.", - correctionMessage: "Try using a collection literal with a 'for' element.", - hasPublishedDocs: true, - ); + LintNames.prefer_for_elements_to_map_fromIterable, + "Use 'for' elements when building maps from iterables.", + correctionMessage: + "Try using a collection literal with a 'for' element.", + hasPublishedDocs: true, + ); static const LintCode prefer_foreach = LinterLintCode( LintNames.prefer_foreach, @@ -1195,8 +1196,8 @@ class LinterLintCode extends LintCode { correctionMessage: "Try using 'forEach' rather than a 'for' loop.", ); - static const LintCode prefer_function_declarations_over_variables = - LinterLintCode( + static const LintCode + prefer_function_declarations_over_variables = LinterLintCode( LintNames.prefer_function_declarations_over_variables, "Use a function declaration rather than a variable assignment to bind a " "function to a name.", @@ -1214,11 +1215,11 @@ class LinterLintCode extends LintCode { static const LintCode prefer_if_elements_to_conditional_expressions = LinterLintCode( - LintNames.prefer_if_elements_to_conditional_expressions, - "Use an 'if' element to conditionally add elements.", - correctionMessage: - "Try using an 'if' element rather than a conditional expression.", - ); + LintNames.prefer_if_elements_to_conditional_expressions, + "Use an 'if' element to conditionally add elements.", + correctionMessage: + "Try using an 'if' element rather than a conditional expression.", + ); static const LintCode prefer_if_null_operators = LinterLintCode( LintNames.prefer_if_null_operators, @@ -1259,12 +1260,12 @@ class LinterLintCode extends LintCode { static const LintCode prefer_interpolation_to_compose_strings = LinterLintCode( - LintNames.prefer_interpolation_to_compose_strings, - "Use interpolation to compose strings and values.", - correctionMessage: - "Try using string interpolation to build the composite string.", - hasPublishedDocs: true, - ); + LintNames.prefer_interpolation_to_compose_strings, + "Use interpolation to compose strings and values.", + correctionMessage: + "Try using string interpolation to build the composite string.", + hasPublishedDocs: true, + ); static const LintCode prefer_is_empty_always_false = LinterLintCode( LintNames.prefer_is_empty, @@ -1365,15 +1366,15 @@ class LinterLintCode extends LintCode { static const LintCode prefer_typing_uninitialized_variables_for_field = LinterLintCode( - LintNames.prefer_typing_uninitialized_variables, - "An uninitialized field should have an explicit type annotation.", - correctionMessage: "Try adding a type annotation.", - hasPublishedDocs: true, - uniqueName: 'prefer_typing_uninitialized_variables_for_field', - ); + LintNames.prefer_typing_uninitialized_variables, + "An uninitialized field should have an explicit type annotation.", + correctionMessage: "Try adding a type annotation.", + hasPublishedDocs: true, + uniqueName: 'prefer_typing_uninitialized_variables_for_field', + ); static const LintCode - prefer_typing_uninitialized_variables_for_local_variable = LinterLintCode( + prefer_typing_uninitialized_variables_for_local_variable = LinterLintCode( LintNames.prefer_typing_uninitialized_variables, "An uninitialized variable should have an explicit type annotation.", correctionMessage: "Try adding a type annotation.", @@ -1391,7 +1392,8 @@ class LinterLintCode extends LintCode { static const LintCode provide_deprecation_message = LinterLintCode( LintNames.provide_deprecation_message, "Missing a deprecation message.", - correctionMessage: "Try using the constructor to provide a message " + correctionMessage: + "Try using the constructor to provide a message " "('@Deprecated(\"message\")').", hasPublishedDocs: true, ); @@ -1478,10 +1480,10 @@ class LinterLintCode extends LintCode { static const LintCode specify_nonobvious_local_variable_types = LinterLintCode( - LintNames.specify_nonobvious_local_variable_types, - "Specify the type of a local variable when the type is non-obvious.", - correctionMessage: "Try adding a type annotation.", - ); + LintNames.specify_nonobvious_local_variable_types, + "Specify the type of a local variable when the type is non-obvious.", + correctionMessage: "Try adding a type annotation.", + ); static const LintCode specify_nonobvious_property_types = LinterLintCode( LintNames.specify_nonobvious_property_types, @@ -1498,21 +1500,21 @@ class LinterLintCode extends LintCode { static const LintCode strict_top_level_inference_replace_keyword = LinterLintCode( - LintNames.strict_top_level_inference, - "Missing type annotation.", - correctionMessage: "Try replacing '{0}' with a type annotation.", - uniqueName: 'strict_top_level_inference_replace_keyword', - ); + LintNames.strict_top_level_inference, + "Missing type annotation.", + correctionMessage: "Try replacing '{0}' with a type annotation.", + uniqueName: 'strict_top_level_inference_replace_keyword', + ); static const LintCode strict_top_level_inference_split_to_types = LinterLintCode( - LintNames.strict_top_level_inference, - "Missing type annotation.", - correctionMessage: - "Try splitting the declaration and specify the different type " - "annotations.", - uniqueName: 'strict_top_level_inference_split_to_types', - ); + LintNames.strict_top_level_inference, + "Missing type annotation.", + correctionMessage: + "Try splitting the declaration and specify the different type " + "annotations.", + uniqueName: 'strict_top_level_inference_split_to_types', + ); static const LintCode test_types_in_equals = LinterLintCode( LintNames.test_types_in_equals, @@ -1676,7 +1678,7 @@ class LinterLintCode extends LintCode { ); static const LintCode - unnecessary_null_aware_operator_on_extension_on_nullable = LinterLintCode( + unnecessary_null_aware_operator_on_extension_on_nullable = LinterLintCode( LintNames.unnecessary_null_aware_operator_on_extension_on_nullable, "Unnecessary use of a null-aware operator to invoke an extension method on " "a nullable type.", @@ -1698,11 +1700,11 @@ class LinterLintCode extends LintCode { static const LintCode unnecessary_nullable_for_final_variable_declarations = LinterLintCode( - LintNames.unnecessary_nullable_for_final_variable_declarations, - "Type could be non-nullable.", - correctionMessage: "Try changing the type to be non-nullable.", - hasPublishedDocs: true, - ); + LintNames.unnecessary_nullable_for_final_variable_declarations, + "Type could be non-nullable.", + correctionMessage: "Try changing the type to be non-nullable.", + hasPublishedDocs: true, + ); static const LintCode unnecessary_overrides = LinterLintCode( LintNames.unnecessary_overrides, @@ -1776,8 +1778,8 @@ class LinterLintCode extends LintCode { correctionMessage: "Try referencing the member or removing it.", ); - static const LintCode unrelated_type_equality_checks_in_expression = - LinterLintCode( + static const LintCode + unrelated_type_equality_checks_in_expression = LinterLintCode( LintNames.unrelated_type_equality_checks, "The type of the right operand ('{0}') isn't a subtype or a supertype of " "the left operand ('{1}').", @@ -1788,13 +1790,13 @@ class LinterLintCode extends LintCode { static const LintCode unrelated_type_equality_checks_in_pattern = LinterLintCode( - LintNames.unrelated_type_equality_checks, - "The type of the operand ('{0}') isn't a subtype or a supertype of the " - "value being matched ('{1}').", - correctionMessage: "Try changing one or both of the operands.", - hasPublishedDocs: true, - uniqueName: 'unrelated_type_equality_checks_in_pattern', - ); + LintNames.unrelated_type_equality_checks, + "The type of the operand ('{0}') isn't a subtype or a supertype of the " + "value being matched ('{1}').", + correctionMessage: "Try changing one or both of the operands.", + hasPublishedDocs: true, + uniqueName: 'unrelated_type_equality_checks_in_pattern', + ); static const LintCode unsafe_variance = LinterLintCode( LintNames.unsafe_variance, @@ -1805,8 +1807,8 @@ class LinterLintCode extends LintCode { hasPublishedDocs: true, ); - static const LintCode use_build_context_synchronously_async_use = - LinterLintCode( + static const LintCode + use_build_context_synchronously_async_use = LinterLintCode( LintNames.use_build_context_synchronously, "Don't use 'BuildContext's across async gaps.", correctionMessage: @@ -1816,8 +1818,8 @@ class LinterLintCode extends LintCode { uniqueName: 'use_build_context_synchronously_async_use', ); - static const LintCode use_build_context_synchronously_wrong_mounted = - LinterLintCode( + static const LintCode + use_build_context_synchronously_wrong_mounted = LinterLintCode( LintNames.use_build_context_synchronously, "Don't use 'BuildContext's across async gaps, guarded by an unrelated " "'mounted' check.", @@ -1857,11 +1859,11 @@ class LinterLintCode extends LintCode { static const LintCode use_function_type_syntax_for_parameters = LinterLintCode( - LintNames.use_function_type_syntax_for_parameters, - "Use the generic function type syntax to declare the parameter '{0}'.", - correctionMessage: "Try using the generic function type syntax.", - hasPublishedDocs: true, - ); + LintNames.use_function_type_syntax_for_parameters, + "Use the generic function type syntax to declare the parameter '{0}'.", + correctionMessage: "Try using the generic function type syntax.", + hasPublishedDocs: true, + ); static const LintCode use_if_null_to_convert_nulls_to_bools = LinterLintCode( LintNames.use_if_null_to_convert_nulls_to_bools, @@ -1885,11 +1887,11 @@ class LinterLintCode extends LintCode { static const LintCode use_late_for_private_fields_and_variables = LinterLintCode( - LintNames.use_late_for_private_fields_and_variables, - "Use 'late' for private members with a non-nullable type.", - correctionMessage: "Try making adding the modifier 'late'.", - hasPublishedDocs: true, - ); + LintNames.use_late_for_private_fields_and_variables, + "Use 'late' for private members with a non-nullable type.", + correctionMessage: "Try making adding the modifier 'late'.", + hasPublishedDocs: true, + ); static const LintCode use_named_constants = LinterLintCode( LintNames.use_named_constants, diff --git a/pkg/linter/lib/src/rules/always_declare_return_types.dart b/pkg/linter/lib/src/rules/always_declare_return_types.dart index b3d4f57c87f4..dbb1cc0721a3 100644 --- a/pkg/linter/lib/src/rules/always_declare_return_types.dart +++ b/pkg/linter/lib/src/rules/always_declare_return_types.dart @@ -13,20 +13,19 @@ const _desc = r'Declare method return types.'; class AlwaysDeclareReturnTypes extends LintRule { AlwaysDeclareReturnTypes() - : super( - name: LintNames.always_declare_return_types, - description: _desc, - ); + : super(name: LintNames.always_declare_return_types, description: _desc); @override List get lintCodes => [ - LinterLintCode.always_declare_return_types_of_functions, - LinterLintCode.always_declare_return_types_of_methods - ]; + LinterLintCode.always_declare_return_types_of_functions, + LinterLintCode.always_declare_return_types_of_methods, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFunctionDeclaration(this, visitor); registry.addFunctionTypeAlias(this, visitor); @@ -43,18 +42,22 @@ class _Visitor extends SimpleAstVisitor { @override void visitFunctionDeclaration(FunctionDeclaration node) { if (!node.isSetter && node.returnType == null && !node.isAugmentation) { - rule.reportLintForToken(node.name, - arguments: [node.name.lexeme], - errorCode: LinterLintCode.always_declare_return_types_of_functions); + rule.reportLintForToken( + node.name, + arguments: [node.name.lexeme], + errorCode: LinterLintCode.always_declare_return_types_of_functions, + ); } } @override void visitFunctionTypeAlias(FunctionTypeAlias node) { if (node.returnType == null) { - rule.reportLintForToken(node.name, - arguments: [node.name.lexeme], - errorCode: LinterLintCode.always_declare_return_types_of_functions); + rule.reportLintForToken( + node.name, + arguments: [node.name.lexeme], + errorCode: LinterLintCode.always_declare_return_types_of_functions, + ); } } diff --git a/pkg/linter/lib/src/rules/always_put_control_body_on_new_line.dart b/pkg/linter/lib/src/rules/always_put_control_body_on_new_line.dart index 77645bc53033..48c3facf017b 100644 --- a/pkg/linter/lib/src/rules/always_put_control_body_on_new_line.dart +++ b/pkg/linter/lib/src/rules/always_put_control_body_on_new_line.dart @@ -11,17 +11,19 @@ const _desc = r'Separate the control structure expression from its statement.'; class AlwaysPutControlBodyOnNewLine extends LintRule { AlwaysPutControlBodyOnNewLine() - : super( - name: LintNames.always_put_control_body_on_new_line, - description: _desc, - ); + : super( + name: LintNames.always_put_control_body_on_new_line, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.always_put_control_body_on_new_line; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDoStatement(this, visitor); registry.addForStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/always_put_required_named_parameters_first.dart b/pkg/linter/lib/src/rules/always_put_required_named_parameters_first.dart index 59c7da21530f..3dc10409987b 100644 --- a/pkg/linter/lib/src/rules/always_put_required_named_parameters_first.dart +++ b/pkg/linter/lib/src/rules/always_put_required_named_parameters_first.dart @@ -11,10 +11,10 @@ const _desc = r'Put required named parameters first.'; class AlwaysPutRequiredNamedParametersFirst extends LintRule { AlwaysPutRequiredNamedParametersFirst() - : super( - name: LintNames.always_put_required_named_parameters_first, - description: _desc, - ); + : super( + name: LintNames.always_put_required_named_parameters_first, + description: _desc, + ); @override LintCode get lintCode => @@ -22,7 +22,9 @@ class AlwaysPutRequiredNamedParametersFirst extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFormalParameterList(this, visitor); } diff --git a/pkg/linter/lib/src/rules/always_require_non_null_named_parameters.dart b/pkg/linter/lib/src/rules/always_require_non_null_named_parameters.dart index 1fbaf618923c..f037e5653409 100644 --- a/pkg/linter/lib/src/rules/always_require_non_null_named_parameters.dart +++ b/pkg/linter/lib/src/rules/always_require_non_null_named_parameters.dart @@ -8,11 +8,11 @@ const _desc = r'Specify `@required` on named parameters without defaults.'; class AlwaysRequireNonNullNamedParameters extends LintRule { AlwaysRequireNonNullNamedParameters() - : super( - name: LintNames.always_require_non_null_named_parameters, - description: _desc, - state: State.removed(since: dart3_3), - ); + : super( + name: LintNames.always_require_non_null_named_parameters, + description: _desc, + state: State.removed(since: dart3_3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/always_specify_types.dart b/pkg/linter/lib/src/rules/always_specify_types.dart index 63846ddb435f..61a568932270 100644 --- a/pkg/linter/lib/src/rules/always_specify_types.dart +++ b/pkg/linter/lib/src/rules/always_specify_types.dart @@ -16,30 +16,29 @@ const _desc = r'Specify type annotations.'; class AlwaysSpecifyTypes extends LintRule { AlwaysSpecifyTypes() - : super( - name: LintNames.always_specify_types, - description: _desc, - ); + : super(name: LintNames.always_specify_types, description: _desc); @override List get incompatibleRules => const [ - LintNames.avoid_types_on_closure_parameters, - LintNames.omit_local_variable_types, - LintNames.omit_obvious_local_variable_types, - LintNames.omit_obvious_property_types, - ]; + LintNames.avoid_types_on_closure_parameters, + LintNames.omit_local_variable_types, + LintNames.omit_obvious_local_variable_types, + LintNames.omit_obvious_property_types, + ]; @override List get lintCodes => [ - LinterLintCode.always_specify_types_add_type, - LinterLintCode.always_specify_types_replace_keyword, - LinterLintCode.always_specify_types_specify_type, - LinterLintCode.always_specify_types_split_to_types - ]; + LinterLintCode.always_specify_types_add_type, + LinterLintCode.always_specify_types_replace_keyword, + LinterLintCode.always_specify_types_specify_type, + LinterLintCode.always_specify_types_split_to_types, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDeclaredIdentifier(this, visitor); registry.addListLiteral(this, visitor); @@ -58,8 +57,10 @@ class _Visitor extends SimpleAstVisitor { void checkLiteral(TypedLiteral literal) { if (literal.typeArguments == null) { - rule.reportLintForToken(literal.beginToken, - errorCode: LinterLintCode.always_specify_types_add_type); + rule.reportLintForToken( + literal.beginToken, + errorCode: LinterLintCode.always_specify_types_add_type, + ); } } @@ -70,13 +71,17 @@ class _Visitor extends SimpleAstVisitor { var element = node.declaredElement2; if (element is VariableElement2) { if (keyword.keyword == Keyword.VAR) { - rule.reportLintForToken(keyword, - arguments: [keyword.lexeme, element!.type], - errorCode: LinterLintCode.always_specify_types_replace_keyword); + rule.reportLintForToken( + keyword, + arguments: [keyword.lexeme, element!.type], + errorCode: LinterLintCode.always_specify_types_replace_keyword, + ); } else { - rule.reportLintForToken(keyword, - arguments: [element!.type], - errorCode: LinterLintCode.always_specify_types_specify_type); + rule.reportLintForToken( + keyword, + arguments: [element!.type], + errorCode: LinterLintCode.always_specify_types_specify_type, + ); } } } @@ -89,13 +94,17 @@ class _Visitor extends SimpleAstVisitor { var keyword = node.keyword; var tokenToLint = keyword ?? node.name; if (keyword != null && keyword.keyword == Keyword.VAR) { - rule.reportLintForToken(tokenToLint, - arguments: [keyword.lexeme, type], - errorCode: LinterLintCode.always_specify_types_replace_keyword); + rule.reportLintForToken( + tokenToLint, + arguments: [keyword.lexeme, type], + errorCode: LinterLintCode.always_specify_types_replace_keyword, + ); } else { - rule.reportLintForToken(tokenToLint, - arguments: [type], - errorCode: LinterLintCode.always_specify_types_specify_type); + rule.reportLintForToken( + tokenToLint, + arguments: [type], + errorCode: LinterLintCode.always_specify_types_specify_type, + ); } } } @@ -115,8 +124,10 @@ class _Visitor extends SimpleAstVisitor { namedType.typeArguments == null && namedType.parent is! IsExpression && !element.metadata2.hasOptionalTypeArgs) { - rule.reportLint(namedType, - errorCode: LinterLintCode.always_specify_types_add_type); + rule.reportLint( + namedType, + errorCode: LinterLintCode.always_specify_types_add_type, + ); } } } @@ -136,21 +147,29 @@ class _Visitor extends SimpleAstVisitor { if (keyword.type == Keyword.VAR && type != null && type is! DynamicType) { - rule.reportLintForToken(keyword, - arguments: [keyword.lexeme, type], - errorCode: LinterLintCode.always_specify_types_replace_keyword); + rule.reportLintForToken( + keyword, + arguments: [keyword.lexeme, type], + errorCode: LinterLintCode.always_specify_types_replace_keyword, + ); } else { - rule.reportLintForToken(keyword, - errorCode: LinterLintCode.always_specify_types_add_type); + rule.reportLintForToken( + keyword, + errorCode: LinterLintCode.always_specify_types_add_type, + ); } } else if (type != null) { if (type is DynamicType) { - rule.reportLint(param, - errorCode: LinterLintCode.always_specify_types_add_type); + rule.reportLint( + param, + errorCode: LinterLintCode.always_specify_types_add_type, + ); } else { - rule.reportLint(param, - arguments: [type], - errorCode: LinterLintCode.always_specify_types_specify_type); + rule.reportLint( + param, + arguments: [type], + errorCode: LinterLintCode.always_specify_types_specify_type, + ); } } } @@ -198,8 +217,11 @@ class _Visitor extends SimpleAstVisitor { errorCode = LinterLintCode.always_specify_types_add_type; } } - rule.reportLintForToken(keyword, - arguments: arguments, errorCode: errorCode); + rule.reportLintForToken( + keyword, + arguments: arguments, + errorCode: errorCode, + ); } } diff --git a/pkg/linter/lib/src/rules/always_use_package_imports.dart b/pkg/linter/lib/src/rules/always_use_package_imports.dart index 7e87fd76c0a8..8733096a15a2 100644 --- a/pkg/linter/lib/src/rules/always_use_package_imports.dart +++ b/pkg/linter/lib/src/rules/always_use_package_imports.dart @@ -11,21 +11,21 @@ const _desc = r'Avoid relative imports for files in `lib/`.'; class AlwaysUsePackageImports extends LintRule { AlwaysUsePackageImports() - : super( - name: LintNames.always_use_package_imports, - description: _desc, - ); + : super(name: LintNames.always_use_package_imports, description: _desc); @override - List get incompatibleRules => - const [LintNames.prefer_relative_imports]; + List get incompatibleRules => const [ + LintNames.prefer_relative_imports, + ]; @override LintCode get lintCode => LinterLintCode.always_use_package_imports; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { // Relative paths from outside of the lib folder are handled by the // `avoid_relative_lib_imports` lint rule. if (!context.isInLibDir) return; diff --git a/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart b/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart index 4a7e0381a0a2..6fd5ba280436 100644 --- a/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart +++ b/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart @@ -61,9 +61,11 @@ bool _isOldModelElement(Element2? element) { bool _isOldModelType(DartType? type) { if (type is InterfaceType) { if (type.element3.isExactly( - 'FlowAnalysis', - Uri.parse( - 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart'))) { + 'FlowAnalysis', + Uri.parse( + 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart', + ), + )) { return false; } } @@ -83,20 +85,17 @@ class AnalyzerUseNewElements extends LintRule { /// Whether to use or bypass the opt-in file. bool useOptInFile; - AnalyzerUseNewElements({ - this.useOptInFile = true, - }) : super( - name: code.name, - description: _desc, - state: const State.internal(), - ); + AnalyzerUseNewElements({this.useOptInFile = true}) + : super(name: code.name, description: _desc, state: const State.internal()); @override LintCode get lintCode => code; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); registry.addNamedType(this, visitor); diff --git a/pkg/linter/lib/src/rules/annotate_overrides.dart b/pkg/linter/lib/src/rules/annotate_overrides.dart index 6224703cc7e0..b8cef7f5ea0f 100644 --- a/pkg/linter/lib/src/rules/annotate_overrides.dart +++ b/pkg/linter/lib/src/rules/annotate_overrides.dart @@ -14,17 +14,16 @@ const _desc = r'Annotate overridden members.'; class AnnotateOverrides extends LintRule { AnnotateOverrides() - : super( - name: LintNames.annotate_overrides, - description: _desc, - ); + : super(name: LintNames.annotate_overrides, description: _desc); @override LintCode get lintCode => LinterLintCode.annotate_overrides; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFieldDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/annotate_redeclares.dart b/pkg/linter/lib/src/rules/annotate_redeclares.dart index 9f196f8fe590..0d77dec65e6f 100644 --- a/pkg/linter/lib/src/rules/annotate_redeclares.dart +++ b/pkg/linter/lib/src/rules/annotate_redeclares.dart @@ -12,18 +12,20 @@ const _desc = r'Annotate redeclared members.'; class AnnotateRedeclares extends LintRule { AnnotateRedeclares() - : super( - name: LintNames.annotate_redeclares, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.annotate_redeclares, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.annotate_redeclares; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addExtensionTypeDeclaration(this, visitor); } @@ -60,12 +62,15 @@ class _Visitor extends SimpleAstVisitor { /// Return `true` if the [member] redeclares a member from a superinterface. bool _redeclaresMember( - ExecutableElement2 member, InterfaceElement2 extensionType) { + ExecutableElement2 member, + InterfaceElement2 extensionType, + ) { // TODO(pq): unify with similar logic in `redeclare_verifier` and move to inheritanceManager var interface = context.inheritanceManager.getInterface2(extensionType); var memberName = member.name3; return memberName != null && - interface.redeclared2 - .containsKey(Name.forLibrary(member.library2, memberName)); + interface.redeclared2.containsKey( + Name.forLibrary(member.library2, memberName), + ); } } diff --git a/pkg/linter/lib/src/rules/avoid_annotating_with_dynamic.dart b/pkg/linter/lib/src/rules/avoid_annotating_with_dynamic.dart index ab96c443ee98..a7882e36184a 100644 --- a/pkg/linter/lib/src/rules/avoid_annotating_with_dynamic.dart +++ b/pkg/linter/lib/src/rules/avoid_annotating_with_dynamic.dart @@ -13,17 +13,16 @@ const _desc = r'Avoid annotating with `dynamic` when not required.'; class AvoidAnnotatingWithDynamic extends LintRule { AvoidAnnotatingWithDynamic() - : super( - name: LintNames.avoid_annotating_with_dynamic, - description: _desc, - ); + : super(name: LintNames.avoid_annotating_with_dynamic, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_annotating_with_dynamic; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldFormalParameter(this, visitor); registry.addSimpleFormalParameter(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_as.dart b/pkg/linter/lib/src/rules/avoid_as.dart index a3eff8775a0e..46d6627bbe92 100644 --- a/pkg/linter/lib/src/rules/avoid_as.dart +++ b/pkg/linter/lib/src/rules/avoid_as.dart @@ -8,11 +8,11 @@ const _desc = r'Avoid using `as`.'; class AvoidAs extends LintRule { AvoidAs() - : super( - name: LintNames.avoid_as, - description: _desc, - state: State.removed(since: dart2_12), - ); + : super( + name: LintNames.avoid_as, + description: _desc, + state: State.removed(since: dart2_12), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/avoid_bool_literals_in_conditional_expressions.dart b/pkg/linter/lib/src/rules/avoid_bool_literals_in_conditional_expressions.dart index 12933d6a7f67..16afdc3bbd8c 100644 --- a/pkg/linter/lib/src/rules/avoid_bool_literals_in_conditional_expressions.dart +++ b/pkg/linter/lib/src/rules/avoid_bool_literals_in_conditional_expressions.dart @@ -11,10 +11,10 @@ const _desc = r'Avoid `bool` literals in conditional expressions.'; class AvoidBoolLiteralsInConditionalExpressions extends LintRule { AvoidBoolLiteralsInConditionalExpressions() - : super( - name: LintNames.avoid_bool_literals_in_conditional_expressions, - description: _desc, - ); + : super( + name: LintNames.avoid_bool_literals_in_conditional_expressions, + description: _desc, + ); @override LintCode get lintCode => @@ -22,7 +22,9 @@ class AvoidBoolLiteralsInConditionalExpressions extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConditionalExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_catches_without_on_clauses.dart b/pkg/linter/lib/src/rules/avoid_catches_without_on_clauses.dart index 427b915bd12b..cba089457a98 100644 --- a/pkg/linter/lib/src/rules/avoid_catches_without_on_clauses.dart +++ b/pkg/linter/lib/src/rules/avoid_catches_without_on_clauses.dart @@ -14,17 +14,19 @@ const _desc = r'Avoid catches without on clauses.'; class AvoidCatchesWithoutOnClauses extends LintRule { AvoidCatchesWithoutOnClauses() - : super( - name: LintNames.avoid_catches_without_on_clauses, - description: _desc, - ); + : super( + name: LintNames.avoid_catches_without_on_clauses, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_catches_without_on_clauses; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_catching_errors.dart b/pkg/linter/lib/src/rules/avoid_catching_errors.dart index 659ede83b61e..d83a63833fd5 100644 --- a/pkg/linter/lib/src/rules/avoid_catching_errors.dart +++ b/pkg/linter/lib/src/rules/avoid_catching_errors.dart @@ -12,20 +12,19 @@ const _desc = r"Don't explicitly catch `Error` or types that implement it."; class AvoidCatchingErrors extends LintRule { AvoidCatchingErrors() - : super( - name: LintNames.avoid_catching_errors, - description: _desc, - ); + : super(name: LintNames.avoid_catching_errors, description: _desc); @override List get lintCodes => [ - LinterLintCode.avoid_catching_errors_class, - LinterLintCode.avoid_catching_errors_subclass - ]; + LinterLintCode.avoid_catching_errors_class, + LinterLintCode.avoid_catching_errors_subclass, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); } @@ -41,12 +40,16 @@ class _Visitor extends SimpleAstVisitor { var exceptionType = node.exceptionType?.type; if (exceptionType.implementsInterface('Error', 'dart.core')) { if (exceptionType.isSameAs('Error', 'dart.core')) { - rule.reportLint(node, - errorCode: LinterLintCode.avoid_catching_errors_class); + rule.reportLint( + node, + errorCode: LinterLintCode.avoid_catching_errors_class, + ); } else { - rule.reportLint(node, - errorCode: LinterLintCode.avoid_catching_errors_subclass, - arguments: [exceptionType!.getDisplayString()]); + rule.reportLint( + node, + errorCode: LinterLintCode.avoid_catching_errors_subclass, + arguments: [exceptionType!.getDisplayString()], + ); } } } diff --git a/pkg/linter/lib/src/rules/avoid_classes_with_only_static_members.dart b/pkg/linter/lib/src/rules/avoid_classes_with_only_static_members.dart index 3db1dcaef9c5..51b08d4aa95a 100644 --- a/pkg/linter/lib/src/rules/avoid_classes_with_only_static_members.dart +++ b/pkg/linter/lib/src/rules/avoid_classes_with_only_static_members.dart @@ -12,10 +12,10 @@ const _desc = r'Avoid defining a class that contains only static members.'; class AvoidClassesWithOnlyStaticMembers extends LintRule { AvoidClassesWithOnlyStaticMembers() - : super( - name: LintNames.avoid_classes_with_only_static_members, - description: _desc, - ); + : super( + name: LintNames.avoid_classes_with_only_static_members, + description: _desc, + ); @override LintCode get lintCode => @@ -23,7 +23,9 @@ class AvoidClassesWithOnlyStaticMembers extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addClassDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_double_and_int_checks.dart b/pkg/linter/lib/src/rules/avoid_double_and_int_checks.dart index 10e58cdfc5c4..c176546f078b 100644 --- a/pkg/linter/lib/src/rules/avoid_double_and_int_checks.dart +++ b/pkg/linter/lib/src/rules/avoid_double_and_int_checks.dart @@ -12,17 +12,16 @@ const _desc = r'Avoid `double` and `int` checks.'; class AvoidDoubleAndIntChecks extends LintRule { AvoidDoubleAndIntChecks() - : super( - name: LintNames.avoid_double_and_int_checks, - description: _desc, - ); + : super(name: LintNames.avoid_double_and_int_checks, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_double_and_int_checks; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addIfStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_dynamic_calls.dart b/pkg/linter/lib/src/rules/avoid_dynamic_calls.dart index 02c804ca3b3a..609b56e01cca 100644 --- a/pkg/linter/lib/src/rules/avoid_dynamic_calls.dart +++ b/pkg/linter/lib/src/rules/avoid_dynamic_calls.dart @@ -13,10 +13,7 @@ const _desc = r'Avoid method calls or property accesses on a `dynamic` target.'; class AvoidDynamicCalls extends LintRule { AvoidDynamicCalls() - : super( - name: LintNames.avoid_dynamic_calls, - description: _desc, - ); + : super(name: LintNames.avoid_dynamic_calls, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_dynamic_calls; diff --git a/pkg/linter/lib/src/rules/avoid_empty_else.dart b/pkg/linter/lib/src/rules/avoid_empty_else.dart index c72328e62c84..dd9a7eb33afe 100644 --- a/pkg/linter/lib/src/rules/avoid_empty_else.dart +++ b/pkg/linter/lib/src/rules/avoid_empty_else.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid empty statements in else clauses.'; class AvoidEmptyElse extends LintRule { AvoidEmptyElse() - : super( - name: LintNames.avoid_empty_else, - description: _desc, - ); + : super(name: LintNames.avoid_empty_else, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_empty_else; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addIfStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_equals_and_hash_code_on_mutable_classes.dart b/pkg/linter/lib/src/rules/avoid_equals_and_hash_code_on_mutable_classes.dart index 3cba8a7047a0..653bd9977f3b 100644 --- a/pkg/linter/lib/src/rules/avoid_equals_and_hash_code_on_mutable_classes.dart +++ b/pkg/linter/lib/src/rules/avoid_equals_and_hash_code_on_mutable_classes.dart @@ -16,10 +16,10 @@ const _desc = class AvoidEqualsAndHashCodeOnMutableClasses extends LintRule { AvoidEqualsAndHashCodeOnMutableClasses() - : super( - name: LintNames.avoid_equals_and_hash_code_on_mutable_classes, - description: _desc, - ); + : super( + name: LintNames.avoid_equals_and_hash_code_on_mutable_classes, + description: _desc, + ); @override LintCode get lintCode => @@ -27,7 +27,9 @@ class AvoidEqualsAndHashCodeOnMutableClasses extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } @@ -45,8 +47,10 @@ class _Visitor extends SimpleAstVisitor { if (node.name.type == TokenType.EQ_EQ || isHashCode(node)) { var classElement = node.classElement; if (classElement != null && !classElement.hasImmutableAnnotation) { - rule.reportLintForToken(node.firstTokenAfterCommentAndMetadata, - arguments: [node.name.lexeme]); + rule.reportLintForToken( + node.firstTokenAfterCommentAndMetadata, + arguments: [node.name.lexeme], + ); } } } diff --git a/pkg/linter/lib/src/rules/avoid_escaping_inner_quotes.dart b/pkg/linter/lib/src/rules/avoid_escaping_inner_quotes.dart index e5fca77486c1..65d3c0074165 100644 --- a/pkg/linter/lib/src/rules/avoid_escaping_inner_quotes.dart +++ b/pkg/linter/lib/src/rules/avoid_escaping_inner_quotes.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid escaping inner quotes by converting surrounding quotes.'; class AvoidEscapingInnerQuotes extends LintRule { AvoidEscapingInnerQuotes() - : super( - name: LintNames.avoid_escaping_inner_quotes, - description: _desc, - ); + : super(name: LintNames.avoid_escaping_inner_quotes, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_escaping_inner_quotes; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSimpleStringLiteral(this, visitor); registry.addStringInterpolation(this, visitor); @@ -54,8 +53,10 @@ class _Visitor extends SimpleAstVisitor { void _check(AstNode node, String text, bool isSingleQuoted) { if (_isChangeable(text, isSingleQuoted: isSingleQuoted)) { - rule.reportLint(node, - arguments: [isSingleQuoted ? "'" : '"', isSingleQuoted ? '"' : "'"]); + rule.reportLint( + node, + arguments: [isSingleQuoted ? "'" : '"', isSingleQuoted ? '"' : "'"], + ); } } diff --git a/pkg/linter/lib/src/rules/avoid_field_initializers_in_const_classes.dart b/pkg/linter/lib/src/rules/avoid_field_initializers_in_const_classes.dart index 6cd4a6eb9a53..ad4b61e3bb8d 100644 --- a/pkg/linter/lib/src/rules/avoid_field_initializers_in_const_classes.dart +++ b/pkg/linter/lib/src/rules/avoid_field_initializers_in_const_classes.dart @@ -13,10 +13,10 @@ const _desc = r'Avoid field initializers in const classes.'; class AvoidFieldInitializersInConstClasses extends LintRule { AvoidFieldInitializersInConstClasses() - : super( - name: LintNames.avoid_field_initializers_in_const_classes, - description: _desc, - ); + : super( + name: LintNames.avoid_field_initializers_in_const_classes, + description: _desc, + ); @override LintCode get lintCode => @@ -24,7 +24,9 @@ class AvoidFieldInitializersInConstClasses extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addConstructorFieldInitializer(this, visitor); @@ -37,8 +39,8 @@ class HasParameterReferenceVisitor extends RecursiveAstVisitor { bool useParameter = false; HasParameterReferenceVisitor( - Iterable fragmentParameters) - : parameters = fragmentParameters.map((p) => p?.element); + Iterable fragmentParameters, + ) : parameters = fragmentParameters.map((p) => p?.element); @override void visitSimpleIdentifier(SimpleIdentifier node) { @@ -70,7 +72,8 @@ class _Visitor extends SimpleAstVisitor { if (element.constructors2.length > 1) return; var visitor = HasParameterReferenceVisitor( - declaration.parameters.parameterFragments); + declaration.parameters.parameterFragments, + ); node.expression.accept(visitor); if (!visitor.useParameter) { rule.reportLint(node); diff --git a/pkg/linter/lib/src/rules/avoid_final_parameters.dart b/pkg/linter/lib/src/rules/avoid_final_parameters.dart index f8029d564ea3..796264015751 100644 --- a/pkg/linter/lib/src/rules/avoid_final_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_final_parameters.dart @@ -11,21 +11,21 @@ const _desc = r'Avoid `final` for parameter declarations.'; class AvoidFinalParameters extends LintRule { AvoidFinalParameters() - : super( - name: LintNames.avoid_final_parameters, - description: _desc, - ); + : super(name: LintNames.avoid_final_parameters, description: _desc); @override - List get incompatibleRules => - const [LintNames.prefer_final_parameters]; + List get incompatibleRules => const [ + LintNames.prefer_final_parameters, + ]; @override LintCode get lintCode => LinterLintCode.avoid_final_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addFunctionExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_function_literals_in_foreach_calls.dart b/pkg/linter/lib/src/rules/avoid_function_literals_in_foreach_calls.dart index 70fffd7859b9..4fcd20e93f4d 100644 --- a/pkg/linter/lib/src/rules/avoid_function_literals_in_foreach_calls.dart +++ b/pkg/linter/lib/src/rules/avoid_function_literals_in_foreach_calls.dart @@ -36,10 +36,10 @@ bool _isIterable(DartType? type) => class AvoidFunctionLiteralsInForeachCalls extends LintRule { AvoidFunctionLiteralsInForeachCalls() - : super( - name: LintNames.avoid_function_literals_in_foreach_calls, - description: _desc, - ); + : super( + name: LintNames.avoid_function_literals_in_foreach_calls, + description: _desc, + ); @override LintCode get lintCode => @@ -47,7 +47,9 @@ class AvoidFunctionLiteralsInForeachCalls extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_futureor_void.dart b/pkg/linter/lib/src/rules/avoid_futureor_void.dart index dd1e898e93b8..cd7133720529 100644 --- a/pkg/linter/lib/src/rules/avoid_futureor_void.dart +++ b/pkg/linter/lib/src/rules/avoid_futureor_void.dart @@ -13,17 +13,20 @@ const _desc = r"Avoid using 'FutureOr' as the type of a result."; class AvoidFutureOrVoid extends LintRule { AvoidFutureOrVoid() - : super( - name: LintNames.avoid_futureor_void, - description: _desc, - state: const State.experimental()); + : super( + name: LintNames.avoid_futureor_void, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.avoid_futureor_void; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addAsExpression(this, visitor); registry.addCastPattern(this, visitor); @@ -89,10 +92,12 @@ class _Visitor extends SimpleAstVisitor { void visitFunctionDeclaration(FunctionDeclaration node) { checker.checkOut(node.returnType); var functionExpression = node.functionExpression; - functionExpression.typeParameters?.typeParameters - .forEach(checker.checkBound); - functionExpression.parameters?.parameters - .forEach(checker.checkFormalParameterIn); + functionExpression.typeParameters?.typeParameters.forEach( + checker.checkBound, + ); + functionExpression.parameters?.parameters.forEach( + checker.checkFormalParameterIn, + ); } @override diff --git a/pkg/linter/lib/src/rules/avoid_implementing_value_types.dart b/pkg/linter/lib/src/rules/avoid_implementing_value_types.dart index bdb6a4c723d9..1bfc6373cfcc 100644 --- a/pkg/linter/lib/src/rules/avoid_implementing_value_types.dart +++ b/pkg/linter/lib/src/rules/avoid_implementing_value_types.dart @@ -13,17 +13,16 @@ const _desc = r"Don't implement classes that override `==`."; class AvoidImplementingValueTypes extends LintRule { AvoidImplementingValueTypes() - : super( - name: LintNames.avoid_implementing_value_types, - description: _desc, - ); + : super(name: LintNames.avoid_implementing_value_types, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_implementing_value_types; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addClassDeclaration(this, visitor); } @@ -54,8 +53,11 @@ class _Visitor extends SimpleAstVisitor { } bool _overridesEquals(InterfaceElement2 element) { - var member = - inheritanceManager.getMember4(element, equalsName, concrete: true); + var member = inheritanceManager.getMember4( + element, + equalsName, + concrete: true, + ); var definingLibrary = member?.enclosingElement2?.library2; return definingLibrary != null && !definingLibrary.isDartCore; } diff --git a/pkg/linter/lib/src/rules/avoid_init_to_null.dart b/pkg/linter/lib/src/rules/avoid_init_to_null.dart index 1a700a3ac57f..ffd8eb4006ca 100644 --- a/pkg/linter/lib/src/rules/avoid_init_to_null.dart +++ b/pkg/linter/lib/src/rules/avoid_init_to_null.dart @@ -14,17 +14,16 @@ const _desc = r"Don't explicitly initialize variables to `null`."; class AvoidInitToNull extends LintRule { AvoidInitToNull() - : super( - name: LintNames.avoid_init_to_null, - description: _desc, - ); + : super(name: LintNames.avoid_init_to_null, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_init_to_null; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addVariableDeclaration(this, visitor); registry.addDefaultFormalParameter(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_js_rounded_ints.dart b/pkg/linter/lib/src/rules/avoid_js_rounded_ints.dart index 34da8a565371..871783dd5bdc 100644 --- a/pkg/linter/lib/src/rules/avoid_js_rounded_ints.dart +++ b/pkg/linter/lib/src/rules/avoid_js_rounded_ints.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid JavaScript rounded ints.'; class AvoidJsRoundedInts extends LintRule { AvoidJsRoundedInts() - : super( - name: LintNames.avoid_js_rounded_ints, - description: _desc, - ); + : super(name: LintNames.avoid_js_rounded_ints, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_js_rounded_ints; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addIntegerLiteral(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_multiple_declarations_per_line.dart b/pkg/linter/lib/src/rules/avoid_multiple_declarations_per_line.dart index 7b3ade10fe70..8b98c768082f 100644 --- a/pkg/linter/lib/src/rules/avoid_multiple_declarations_per_line.dart +++ b/pkg/linter/lib/src/rules/avoid_multiple_declarations_per_line.dart @@ -11,17 +11,19 @@ const _desc = r"Don't declare multiple variables on a single line."; class AvoidMultipleDeclarationsPerLine extends LintRule { AvoidMultipleDeclarationsPerLine() - : super( - name: LintNames.avoid_multiple_declarations_per_line, - description: _desc, - ); + : super( + name: LintNames.avoid_multiple_declarations_per_line, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_multiple_declarations_per_line; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addVariableDeclarationList(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart b/pkg/linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart index 33897c44a706..312c8e7d2901 100644 --- a/pkg/linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart +++ b/pkg/linter/lib/src/rules/avoid_null_checks_in_equality_operators.dart @@ -17,7 +17,9 @@ bool _isComparingEquality(TokenType tokenType) => tokenType == TokenType.BANG_EQ || tokenType == TokenType.EQ_EQ; bool _isComparingParameterWithNull( - BinaryExpression node, Element2? parameter) => + BinaryExpression node, + Element2? parameter, +) => _isComparingEquality(node.operator.type) && ((node.leftOperand.isNullLiteral && _isParameter(node.rightOperand, parameter)) || @@ -28,16 +30,18 @@ bool _isParameter(Expression expression, Element2? parameter) => expression.canonicalElement == parameter; bool _isParameterWithQuestionQuestion( - BinaryExpression node, Element2? parameter) => + BinaryExpression node, + Element2? parameter, +) => node.operator.type == TokenType.QUESTION_QUESTION && _isParameter(node.leftOperand, parameter); class AvoidNullChecksInEqualityOperators extends LintRule { AvoidNullChecksInEqualityOperators() - : super( - name: LintNames.avoid_null_checks_in_equality_operators, - description: _desc, - ); + : super( + name: LintNames.avoid_null_checks_in_equality_operators, + description: _desc, + ); @override LintCode get lintCode => @@ -45,7 +49,9 @@ class AvoidNullChecksInEqualityOperators extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_positional_boolean_parameters.dart b/pkg/linter/lib/src/rules/avoid_positional_boolean_parameters.dart index aaf9fee4641b..b43d0ac8a7f7 100644 --- a/pkg/linter/lib/src/rules/avoid_positional_boolean_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_positional_boolean_parameters.dart @@ -15,17 +15,19 @@ const _desc = r'Avoid positional boolean parameters.'; class AvoidPositionalBooleanParameters extends LintRule { AvoidPositionalBooleanParameters() - : super( - name: LintNames.avoid_positional_boolean_parameters, - description: _desc, - ); + : super( + name: LintNames.avoid_positional_boolean_parameters, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_positional_boolean_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConstructorDeclaration(this, visitor); registry.addFunctionDeclaration(this, visitor); @@ -98,8 +100,10 @@ class _Visitor extends SimpleAstVisitor { if (name == null) return false; var libraryUri = classElement.library2.uri; - return context.inheritanceManager - .getInherited3(classElement.thisType, Name(libraryUri, name)) != + return context.inheritanceManager.getInherited3( + classElement.thisType, + Name(libraryUri, name), + ) != null; } diff --git a/pkg/linter/lib/src/rules/avoid_print.dart b/pkg/linter/lib/src/rules/avoid_print.dart index 9e53a1056ee7..c39e15e577a3 100644 --- a/pkg/linter/lib/src/rules/avoid_print.dart +++ b/pkg/linter/lib/src/rules/avoid_print.dart @@ -12,18 +12,16 @@ import '../util/flutter_utils.dart'; const _desc = r'Avoid `print` calls in production code.'; class AvoidPrint extends LintRule { - AvoidPrint() - : super( - name: LintNames.avoid_print, - description: _desc, - ); + AvoidPrint() : super(name: LintNames.avoid_print, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_print; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_private_typedef_functions.dart b/pkg/linter/lib/src/rules/avoid_private_typedef_functions.dart index 163bfaba5fe5..a27f37dbc5a8 100644 --- a/pkg/linter/lib/src/rules/avoid_private_typedef_functions.dart +++ b/pkg/linter/lib/src/rules/avoid_private_typedef_functions.dart @@ -12,17 +12,19 @@ const _desc = r'Avoid private typedef functions.'; class AvoidPrivateTypedefFunctions extends LintRule { AvoidPrivateTypedefFunctions() - : super( - name: LintNames.avoid_private_typedef_functions, - description: _desc, - ); + : super( + name: LintNames.avoid_private_typedef_functions, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_private_typedef_functions; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFunctionTypeAlias(this, visitor); registry.addGenericTypeAlias(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_redundant_argument_values.dart b/pkg/linter/lib/src/rules/avoid_redundant_argument_values.dart index 23949a53aada..57b20a577707 100644 --- a/pkg/linter/lib/src/rules/avoid_redundant_argument_values.dart +++ b/pkg/linter/lib/src/rules/avoid_redundant_argument_values.dart @@ -14,17 +14,19 @@ const _desc = r'Avoid redundant argument values.'; class AvoidRedundantArgumentValues extends LintRule { AvoidRedundantArgumentValues() - : super( - name: LintNames.avoid_redundant_argument_values, - description: _desc, - ); + : super( + name: LintNames.avoid_redundant_argument_values, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_redundant_argument_values; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addEnumConstantArguments(this, visitor); registry.addInstanceCreationExpression(this, visitor); @@ -133,7 +135,8 @@ class _Visitor extends SimpleAstVisitor { FormalParameterElement? param; if (arg is NamedExpression) { param = parameters.firstWhereOrNull( - (p) => p.isNamed && p.name3 == arg.name.label.name); + (p) => p.isNamed && p.name3 == arg.name.label.name, + ); } else { // Count which positional argument we're at. var positionalCount = diff --git a/pkg/linter/lib/src/rules/avoid_relative_lib_imports.dart b/pkg/linter/lib/src/rules/avoid_relative_lib_imports.dart index 479b778ee75c..3ab248bad2e6 100644 --- a/pkg/linter/lib/src/rules/avoid_relative_lib_imports.dart +++ b/pkg/linter/lib/src/rules/avoid_relative_lib_imports.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid relative imports for files in `lib/`.'; class AvoidRelativeLibImports extends LintRule { AvoidRelativeLibImports() - : super( - name: LintNames.avoid_relative_lib_imports, - description: _desc, - ); + : super(name: LintNames.avoid_relative_lib_imports, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_relative_lib_imports; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addImportDirective(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_renaming_method_parameters.dart b/pkg/linter/lib/src/rules/avoid_renaming_method_parameters.dart index a08dcfa94c85..f9a586262cdd 100644 --- a/pkg/linter/lib/src/rules/avoid_renaming_method_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_renaming_method_parameters.dart @@ -17,17 +17,19 @@ const _desc = r"Don't rename parameters of overridden methods."; class AvoidRenamingMethodParameters extends LintRule { AvoidRenamingMethodParameters() - : super( - name: LintNames.avoid_renaming_method_parameters, - description: _desc, - ); + : super( + name: LintNames.avoid_renaming_method_parameters, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_renaming_method_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isInLibDir) return; var visitor = _Visitor(this, context); @@ -44,9 +46,8 @@ class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule, LinterContext context) - : _wildCardVariablesEnabled = - context.isEnabled(Feature.wildcard_variables), - inheritanceManager = context.inheritanceManager; + : _wildCardVariablesEnabled = context.isEnabled(Feature.wildcard_variables), + inheritanceManager = context.inheritanceManager; bool isWildcardIdentifier(String lexeme) => _wildCardVariablesEnabled && lexeme == '_'; @@ -74,8 +75,10 @@ class _Visitor extends SimpleAstVisitor { if (parentElement.isPrivate) return; var parentMethod = inheritanceManager.getMember4( - parentElement, Name(parentElement.library2.uri, node.name.lexeme), - forSuper: true); + parentElement, + Name(parentElement.library2.uri, node.name.lexeme), + forSuper: true, + ); if (parentMethod == null) return; parentParameters = parentMethod.formalParameters.positional; @@ -105,8 +108,10 @@ class _Visitor extends SimpleAstVisitor { if (isWildcardIdentifier(paramLexeme)) continue; if (paramLexeme != parentParameterName) { - rule.reportLintForToken(parameterName, - arguments: [paramLexeme, parentParameterName]); + rule.reportLintForToken( + parameterName, + arguments: [paramLexeme, parentParameterName], + ); } } } diff --git a/pkg/linter/lib/src/rules/avoid_return_types_on_setters.dart b/pkg/linter/lib/src/rules/avoid_return_types_on_setters.dart index 990752dc781a..c5899cdbfa50 100644 --- a/pkg/linter/lib/src/rules/avoid_return_types_on_setters.dart +++ b/pkg/linter/lib/src/rules/avoid_return_types_on_setters.dart @@ -11,10 +11,7 @@ const _desc = r'Avoid return types on setters.'; class AvoidReturnTypesOnSetters extends LintRule { AvoidReturnTypesOnSetters() - : super( - name: LintNames.avoid_return_types_on_setters, - description: _desc, - ); + : super(name: LintNames.avoid_return_types_on_setters, description: _desc); @override bool get canUseParsedResult => true; @@ -24,7 +21,9 @@ class AvoidReturnTypesOnSetters extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_returning_null.dart b/pkg/linter/lib/src/rules/avoid_returning_null.dart index 0f4a6acd2711..93f9d53279df 100644 --- a/pkg/linter/lib/src/rules/avoid_returning_null.dart +++ b/pkg/linter/lib/src/rules/avoid_returning_null.dart @@ -10,11 +10,11 @@ const _desc = class AvoidReturningNull extends LintRule { AvoidReturningNull() - : super( - name: LintNames.avoid_returning_null, - description: _desc, - state: State.removed(since: dart3_3), - ); + : super( + name: LintNames.avoid_returning_null, + description: _desc, + state: State.removed(since: dart3_3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/avoid_returning_null_for_future.dart b/pkg/linter/lib/src/rules/avoid_returning_null_for_future.dart index e4865999500f..b75176744039 100644 --- a/pkg/linter/lib/src/rules/avoid_returning_null_for_future.dart +++ b/pkg/linter/lib/src/rules/avoid_returning_null_for_future.dart @@ -8,10 +8,11 @@ const _desc = r'Avoid returning null for Future.'; class AvoidReturningNullForFuture extends LintRule { AvoidReturningNullForFuture() - : super( - name: LintNames.avoid_returning_null_for_future, - description: _desc, - state: State.removed(since: dart3_3)); + : super( + name: LintNames.avoid_returning_null_for_future, + description: _desc, + state: State.removed(since: dart3_3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/avoid_returning_null_for_void.dart b/pkg/linter/lib/src/rules/avoid_returning_null_for_void.dart index 5aee257b515f..17e8b5087110 100644 --- a/pkg/linter/lib/src/rules/avoid_returning_null_for_void.dart +++ b/pkg/linter/lib/src/rules/avoid_returning_null_for_void.dart @@ -12,20 +12,19 @@ const _desc = r'Avoid returning `null` for `void`.'; class AvoidReturningNullForVoid extends LintRule { AvoidReturningNullForVoid() - : super( - name: LintNames.avoid_returning_null_for_void, - description: _desc, - ); + : super(name: LintNames.avoid_returning_null_for_void, description: _desc); @override List get lintCodes => [ - LinterLintCode.avoid_returning_null_for_void_from_function, - LinterLintCode.avoid_returning_null_for_void_from_method - ]; + LinterLintCode.avoid_returning_null_for_void_from_function, + LinterLintCode.avoid_returning_null_for_void_from_method, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addExpressionFunctionBody(this, visitor); registry.addReturnStatement(this, visitor); @@ -53,20 +52,21 @@ class _Visitor extends SimpleAstVisitor { if (expression is! NullLiteral) return; var parent = node.thisOrAncestorMatching( - (e) => e is FunctionExpression || e is MethodDeclaration); + (e) => e is FunctionExpression || e is MethodDeclaration, + ); if (parent == null) return; var (type, isAsync, code) = switch (parent) { FunctionExpression() => ( - parent.declaredFragment?.element.returnType, - parent.body.isAsynchronous, - LinterLintCode.avoid_returning_null_for_void_from_function, - ), + parent.declaredFragment?.element.returnType, + parent.body.isAsynchronous, + LinterLintCode.avoid_returning_null_for_void_from_function, + ), MethodDeclaration() => ( - parent.declaredFragment?.element.returnType, - parent.body.isAsynchronous, - LinterLintCode.avoid_returning_null_for_void_from_method, - ), + parent.declaredFragment?.element.returnType, + parent.body.isAsynchronous, + LinterLintCode.avoid_returning_null_for_void_from_method, + ), _ => throw StateError('Unexpected type'), }; if (type == null) return; diff --git a/pkg/linter/lib/src/rules/avoid_returning_this.dart b/pkg/linter/lib/src/rules/avoid_returning_this.dart index 830112ba0974..ecc0d9e7d217 100644 --- a/pkg/linter/lib/src/rules/avoid_returning_this.dart +++ b/pkg/linter/lib/src/rules/avoid_returning_this.dart @@ -16,17 +16,16 @@ bool _returnsThis(ReturnStatement node) => node.expression is ThisExpression; class AvoidReturningThis extends LintRule { AvoidReturningThis() - : super( - name: LintNames.avoid_returning_this, - description: _desc, - ); + : super(name: LintNames.avoid_returning_this, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_returning_this; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_setters_without_getters.dart b/pkg/linter/lib/src/rules/avoid_setters_without_getters.dart index b7d39efb40c0..4aa6cf65a80f 100644 --- a/pkg/linter/lib/src/rules/avoid_setters_without_getters.dart +++ b/pkg/linter/lib/src/rules/avoid_setters_without_getters.dart @@ -12,17 +12,16 @@ const _desc = r'Avoid setters without getters.'; class AvoidSettersWithoutGetters extends LintRule { AvoidSettersWithoutGetters() - : super( - name: LintNames.avoid_setters_without_getters, - description: _desc, - ); + : super(name: LintNames.avoid_setters_without_getters, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_setters_without_getters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addClassDeclaration(this, visitor); registry.addEnumDeclaration(this, visitor); @@ -73,8 +72,11 @@ class _Visitor extends SimpleAstVisitor { // Check for a declared (static) getter. ExecutableElement2? getter = interface.getGetter2(getterName); // Then look up for an inherited one. - getter ??= inheritanceManager.getMember4(interface, name.forGetter, - concrete: true); + getter ??= inheritanceManager.getMember4( + interface, + name.forGetter, + concrete: true, + ); if (getter == null) { rule.reportLintForToken(member.name); diff --git a/pkg/linter/lib/src/rules/avoid_shadowing_type_parameters.dart b/pkg/linter/lib/src/rules/avoid_shadowing_type_parameters.dart index 8da3238b0c36..9941daeb3257 100644 --- a/pkg/linter/lib/src/rules/avoid_shadowing_type_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_shadowing_type_parameters.dart @@ -13,17 +13,19 @@ const _desc = r'Avoid shadowing type parameters.'; class AvoidShadowingTypeParameters extends LintRule { AvoidShadowingTypeParameters() - : super( - name: LintNames.avoid_shadowing_type_parameters, - description: _desc, - ); + : super( + name: LintNames.avoid_shadowing_type_parameters, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_shadowing_type_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFunctionDeclarationStatement(this, visitor); registry.addGenericTypeAlias(this, visitor); @@ -38,8 +40,7 @@ class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule, LinterContext context) - : _wildCardVariablesEnabled = - context.isEnabled(Feature.wildcard_variables); + : _wildCardVariablesEnabled = context.isEnabled(Feature.wildcard_variables); @override void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) { @@ -71,7 +72,9 @@ class _Visitor extends SimpleAstVisitor { // Check the ancestors of [node] for type parameter shadowing. void _checkAncestorParameters( - TypeParameterList? typeParameters, AstNode node) { + TypeParameterList? typeParameters, + AstNode node, + ) { var parent = node.parent; while (parent != null) { @@ -83,36 +86,48 @@ class _Visitor extends SimpleAstVisitor { _checkForShadowing(typeParameters, parent.typeParameters, 'extension'); } else if (parent is ExtensionTypeDeclaration) { _checkForShadowing( - typeParameters, parent.typeParameters, 'extension type'); + typeParameters, + parent.typeParameters, + 'extension type', + ); } else if (parent is MethodDeclaration) { _checkForShadowing(typeParameters, parent.typeParameters, 'method'); } else if (parent is MixinDeclaration) { _checkForShadowing(typeParameters, parent.typeParameters, 'mixin'); } else if (parent is FunctionDeclaration) { - _checkForShadowing(typeParameters, - parent.functionExpression.typeParameters, 'function'); + _checkForShadowing( + typeParameters, + parent.functionExpression.typeParameters, + 'function', + ); } parent = parent.parent; } } // Check whether any of [typeParameters] shadow [ancestorTypeParameters]. - void _checkForShadowing(TypeParameterList? typeParameters, - TypeParameterList? ancestorTypeParameters, String ancestorKind) { + void _checkForShadowing( + TypeParameterList? typeParameters, + TypeParameterList? ancestorTypeParameters, + String ancestorKind, + ) { if (typeParameters == null || ancestorTypeParameters == null) { return; } - var ancestorTypeParameterNames = ancestorTypeParameters.typeParameters - .map((tp) => tp.name.lexeme) - .toSet(); + var ancestorTypeParameterNames = + ancestorTypeParameters.typeParameters + .map((tp) => tp.name.lexeme) + .toSet(); for (var parameter in typeParameters.typeParameters) { var lexeme = parameter.name.lexeme; if (_wildCardVariablesEnabled && lexeme == '_') continue; if (ancestorTypeParameterNames.contains(lexeme)) { - rule.reportLint(parameter, - arguments: [parameter.name.lexeme, ancestorKind]); + rule.reportLint( + parameter, + arguments: [parameter.name.lexeme, ancestorKind], + ); } } } diff --git a/pkg/linter/lib/src/rules/avoid_single_cascade_in_expression_statements.dart b/pkg/linter/lib/src/rules/avoid_single_cascade_in_expression_statements.dart index 304acc86f6ee..91353e9e1504 100644 --- a/pkg/linter/lib/src/rules/avoid_single_cascade_in_expression_statements.dart +++ b/pkg/linter/lib/src/rules/avoid_single_cascade_in_expression_statements.dart @@ -12,10 +12,10 @@ const _desc = r'Avoid single cascade in expression statements.'; class AvoidSingleCascadeInExpressionStatements extends LintRule { AvoidSingleCascadeInExpressionStatements() - : super( - name: LintNames.avoid_single_cascade_in_expression_statements, - description: _desc, - ); + : super( + name: LintNames.avoid_single_cascade_in_expression_statements, + description: _desc, + ); @override LintCode get lintCode => @@ -23,7 +23,9 @@ class AvoidSingleCascadeInExpressionStatements extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCascadeExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_slow_async_io.dart b/pkg/linter/lib/src/rules/avoid_slow_async_io.dart index 43c37f2c1114..e2a533863417 100644 --- a/pkg/linter/lib/src/rules/avoid_slow_async_io.dart +++ b/pkg/linter/lib/src/rules/avoid_slow_async_io.dart @@ -12,10 +12,7 @@ import '../extensions.dart'; const _desc = r'Avoid slow asynchronous `dart:io` methods.'; -const List _dirMethodNames = [ - 'exists', - 'stat', -]; +const List _dirMethodNames = ['exists', 'stat']; const List _fileMethodNames = [ 'lastModified', @@ -32,17 +29,16 @@ const List _fileSystemEntityMethodNames = [ class AvoidSlowAsyncIo extends LintRule { AvoidSlowAsyncIo() - : super( - name: LintNames.avoid_slow_async_io, - description: _desc, - ); + : super(name: LintNames.avoid_slow_async_io, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_slow_async_io; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_type_to_string.dart b/pkg/linter/lib/src/rules/avoid_type_to_string.dart index cc935767458f..563c03f9ba17 100644 --- a/pkg/linter/lib/src/rules/avoid_type_to_string.dart +++ b/pkg/linter/lib/src/rules/avoid_type_to_string.dart @@ -14,19 +14,21 @@ const _desc = class AvoidTypeToString extends LintRule { AvoidTypeToString() - : super( - name: LintNames.avoid_type_to_string, - description: _desc, - ); + : super(name: LintNames.avoid_type_to_string, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_type_to_string; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { - var visitor = - _Visitor(this, context.typeSystem, context.typeProvider.typeType); + NodeLintRegistry registry, + LinterContext context, + ) { + var visitor = _Visitor( + this, + context.typeSystem, + context.typeProvider.typeType, + ); // Gathering meta information at these nodes. // Nodes visited in DFS, so this will be called before // each visitMethodInvocation. @@ -89,14 +91,18 @@ class _Visitor extends SimpleAstVisitor { } bool _isToStringOnCoreTypeClass( - DartType? targetType, SimpleIdentifier methodIdentifier) => + DartType? targetType, + SimpleIdentifier methodIdentifier, + ) => targetType != null && methodIdentifier.name == 'toString' && _isSimpleIdDeclByCoreObj(methodIdentifier) && typeSystem.isSubtypeOf(targetType, typeType); void _reportIfToStringOnCoreTypeClass( - DartType? targetType, SimpleIdentifier methodIdentifier) { + DartType? targetType, + SimpleIdentifier methodIdentifier, + ) { if (_isToStringOnCoreTypeClass(targetType, methodIdentifier)) { rule.reportLint(methodIdentifier); } diff --git a/pkg/linter/lib/src/rules/avoid_types_as_parameter_names.dart b/pkg/linter/lib/src/rules/avoid_types_as_parameter_names.dart index a30358f56705..0195c4016754 100644 --- a/pkg/linter/lib/src/rules/avoid_types_as_parameter_names.dart +++ b/pkg/linter/lib/src/rules/avoid_types_as_parameter_names.dart @@ -16,17 +16,16 @@ const _desc = r'Avoid types as parameter names.'; class AvoidTypesAsParameterNames extends LintRule { AvoidTypesAsParameterNames() - : super( - name: LintNames.avoid_types_as_parameter_names, - description: _desc, - ); + : super(name: LintNames.avoid_types_as_parameter_names, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_types_as_parameter_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFormalParameterList(this, visitor); registry.addCatchClause(this, visitor); @@ -63,8 +62,11 @@ class _Visitor extends SimpleAstVisitor { } bool _isTypeName(AstNode scope, Token name) { - var result = - resolveNameInScope(name.lexeme, scope, shouldResolveSetter: false); + var result = resolveNameInScope( + name.lexeme, + scope, + shouldResolveSetter: false, + ); if (result.isRequestedName) { var element = result.element; return element is ClassElement2 || diff --git a/pkg/linter/lib/src/rules/avoid_types_on_closure_parameters.dart b/pkg/linter/lib/src/rules/avoid_types_on_closure_parameters.dart index b8f6d075522b..ecb36f32c6e0 100644 --- a/pkg/linter/lib/src/rules/avoid_types_on_closure_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_types_on_closure_parameters.dart @@ -13,10 +13,10 @@ const _desc = r'Avoid annotating types for function expression parameters.'; class AvoidTypesOnClosureParameters extends LintRule { AvoidTypesOnClosureParameters() - : super( - name: LintNames.avoid_types_on_closure_parameters, - description: _desc, - ); + : super( + name: LintNames.avoid_types_on_closure_parameters, + description: _desc, + ); @override List get incompatibleRules => const [LintNames.always_specify_types]; @@ -26,7 +26,9 @@ class AvoidTypesOnClosureParameters extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/avoid_unnecessary_containers.dart b/pkg/linter/lib/src/rules/avoid_unnecessary_containers.dart index f1a10caa4c42..5fd4e2058a94 100644 --- a/pkg/linter/lib/src/rules/avoid_unnecessary_containers.dart +++ b/pkg/linter/lib/src/rules/avoid_unnecessary_containers.dart @@ -12,17 +12,16 @@ const _desc = r'Avoid unnecessary containers.'; class AvoidUnnecessaryContainers extends LintRule { AvoidUnnecessaryContainers() - : super( - name: LintNames.avoid_unnecessary_containers, - description: _desc, - ); + : super(name: LintNames.avoid_unnecessary_containers, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_unnecessary_containers; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/avoid_unstable_final_fields.dart b/pkg/linter/lib/src/rules/avoid_unstable_final_fields.dart index a084eb3d28aa..0e0b61ba3c36 100644 --- a/pkg/linter/lib/src/rules/avoid_unstable_final_fields.dart +++ b/pkg/linter/lib/src/rules/avoid_unstable_final_fields.dart @@ -4,15 +4,17 @@ import '../analyzer.dart'; -const _desc = r'Avoid overriding a final field to return ' +const _desc = + r'Avoid overriding a final field to return ' 'different values if called multiple times.'; class AvoidUnstableFinalFields extends LintRule { AvoidUnstableFinalFields() - : super( - name: LintNames.avoid_unstable_final_fields, - description: _desc, - state: const State.removed()); + : super( + name: LintNames.avoid_unstable_final_fields, + description: _desc, + state: const State.removed(), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/avoid_unused_constructor_parameters.dart b/pkg/linter/lib/src/rules/avoid_unused_constructor_parameters.dart index 8700100616ca..b90b0a55d516 100644 --- a/pkg/linter/lib/src/rules/avoid_unused_constructor_parameters.dart +++ b/pkg/linter/lib/src/rules/avoid_unused_constructor_parameters.dart @@ -14,17 +14,19 @@ const _desc = r'Avoid defining unused parameters in constructors.'; class AvoidUnusedConstructorParameters extends LintRule { AvoidUnusedConstructorParameters() - : super( - name: LintNames.avoid_unused_constructor_parameters, - description: _desc, - ); + : super( + name: LintNames.avoid_unused_constructor_parameters, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.avoid_unused_constructor_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); } @@ -35,19 +37,21 @@ class _ConstructorVisitor extends RecursiveAstVisitor { final Set unusedParameters; _ConstructorVisitor(this.element) - : unusedParameters = element.parameters.parameters.where((p) { - var element = p.declaredFragment?.element; - return element != null && - element is! FieldFormalParameterElement2 && - element is! SuperFormalParameterElement2 && - !element.metadata2.hasDeprecated && - !(element.name3 ?? '').isJustUnderscores; - }).toSet(); + : unusedParameters = + element.parameters.parameters.where((p) { + var element = p.declaredFragment?.element; + return element != null && + element is! FieldFormalParameterElement2 && + element is! SuperFormalParameterElement2 && + !element.metadata2.hasDeprecated && + !(element.name3 ?? '').isJustUnderscores; + }).toSet(); @override void visitSimpleIdentifier(SimpleIdentifier node) { - unusedParameters - .removeWhere((p) => node.element == p.declaredFragment?.element); + unusedParameters.removeWhere( + (p) => node.element == p.declaredFragment?.element, + ); } } diff --git a/pkg/linter/lib/src/rules/avoid_void_async.dart b/pkg/linter/lib/src/rules/avoid_void_async.dart index 7bf911d27575..b418c4dccd02 100644 --- a/pkg/linter/lib/src/rules/avoid_void_async.dart +++ b/pkg/linter/lib/src/rules/avoid_void_async.dart @@ -14,17 +14,16 @@ const _desc = r'Avoid `async` functions that return `void`.'; class AvoidVoidAsync extends LintRule { AvoidVoidAsync() - : super( - name: LintNames.avoid_void_async, - description: _desc, - ); + : super(name: LintNames.avoid_void_async, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_void_async; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); @@ -39,18 +38,12 @@ class _Visitor extends SimpleAstVisitor { @override void visitFunctionDeclaration(FunctionDeclaration node) { if (node.name.lexeme == 'main' && node.parent is CompilationUnit) return; - _check( - fragment: node.declaredFragment, - errorNode: node.name, - ); + _check(fragment: node.declaredFragment, errorNode: node.name); } @override void visitMethodDeclaration(MethodDeclaration node) { - _check( - fragment: node.declaredFragment, - errorNode: node.name, - ); + _check(fragment: node.declaredFragment, errorNode: node.name); } void _check({ diff --git a/pkg/linter/lib/src/rules/avoid_web_libraries_in_flutter.dart b/pkg/linter/lib/src/rules/avoid_web_libraries_in_flutter.dart index 9b7a149d23dd..eea5907651bc 100644 --- a/pkg/linter/lib/src/rules/avoid_web_libraries_in_flutter.dart +++ b/pkg/linter/lib/src/rules/avoid_web_libraries_in_flutter.dart @@ -33,10 +33,7 @@ class AvoidWebLibrariesInFlutter extends LintRule { static final Map _rootHasFlutterCache = {}; AvoidWebLibrariesInFlutter() - : super( - name: LintNames.avoid_web_libraries_in_flutter, - description: _desc, - ); + : super(name: LintNames.avoid_web_libraries_in_flutter, description: _desc); @override LintCode get lintCode => LinterLintCode.avoid_web_libraries_in_flutter; @@ -57,8 +54,9 @@ class AvoidWebLibrariesInFlutter extends LintRule { // If it has Flutter as a dependency, continue checking. if (parsedPubspec['dependencies'] case {'flutter': var _?}) { - if (parsedPubspec['flutter'] - case {'plugin': {'platforms': {'web': _?}}}) { + if (parsedPubspec['flutter'] case { + 'plugin': {'platforms': {'web': _?}}, + }) { // Is a Flutter web plugin; allow web libraries. return false; } else { @@ -73,7 +71,9 @@ class AvoidWebLibrariesInFlutter extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { bool hasFlutter(String root) { var hasFlutter = _rootHasFlutterCache[root]; if (hasFlutter == null) { diff --git a/pkg/linter/lib/src/rules/await_only_futures.dart b/pkg/linter/lib/src/rules/await_only_futures.dart index da86014e06db..5d1e72182f04 100644 --- a/pkg/linter/lib/src/rules/await_only_futures.dart +++ b/pkg/linter/lib/src/rules/await_only_futures.dart @@ -14,17 +14,16 @@ const _desc = r'Await only futures.'; class AwaitOnlyFutures extends LintRule { AwaitOnlyFutures() - : super( - name: LintNames.await_only_futures, - description: _desc, - ); + : super(name: LintNames.await_only_futures, description: _desc); @override LintCode get lintCode => LinterLintCode.await_only_futures; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAwaitExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/camel_case_extensions.dart b/pkg/linter/lib/src/rules/camel_case_extensions.dart index 138147c574ba..a1dc89317ca2 100644 --- a/pkg/linter/lib/src/rules/camel_case_extensions.dart +++ b/pkg/linter/lib/src/rules/camel_case_extensions.dart @@ -12,17 +12,16 @@ const _desc = r'Name extensions using UpperCamelCase.'; class CamelCaseExtensions extends LintRule { CamelCaseExtensions() - : super( - name: LintNames.camel_case_extensions, - description: _desc, - ); + : super(name: LintNames.camel_case_extensions, description: _desc); @override LintCode get lintCode => LinterLintCode.camel_case_extensions; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addExtensionDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/camel_case_types.dart b/pkg/linter/lib/src/rules/camel_case_types.dart index 94801a1d5840..272fc4312513 100644 --- a/pkg/linter/lib/src/rules/camel_case_types.dart +++ b/pkg/linter/lib/src/rules/camel_case_types.dart @@ -14,17 +14,16 @@ const _desc = r'Name types using UpperCamelCase.'; class CamelCaseTypes extends LintRule { CamelCaseTypes() - : super( - name: LintNames.camel_case_types, - description: _desc, - ); + : super(name: LintNames.camel_case_types, description: _desc); @override LintCode get lintCode => LinterLintCode.camel_case_types; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addGenericTypeAlias(this, visitor); registry.addClassDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/cancel_subscriptions.dart b/pkg/linter/lib/src/rules/cancel_subscriptions.dart index 3eaf55419f0f..7c4c29036d30 100644 --- a/pkg/linter/lib/src/rules/cancel_subscriptions.dart +++ b/pkg/linter/lib/src/rules/cancel_subscriptions.dart @@ -12,17 +12,16 @@ const _desc = r'Cancel instances of `dart:async` `StreamSubscription`.'; class CancelSubscriptions extends LintRule { CancelSubscriptions() - : super( - name: LintNames.cancel_subscriptions, - description: _desc, - ); + : super(name: LintNames.cancel_subscriptions, description: _desc); @override LintCode get lintCode => LinterLintCode.cancel_subscriptions; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addVariableDeclarationStatement(this, visitor); @@ -30,9 +29,7 @@ class CancelSubscriptions extends LintRule { } class _Visitor extends LeakDetectorProcessors { - static final _predicates = { - _isSubscription: 'cancel', - }; + static final _predicates = {_isSubscription: 'cancel'}; _Visitor(super.rule); diff --git a/pkg/linter/lib/src/rules/cascade_invocations.dart b/pkg/linter/lib/src/rules/cascade_invocations.dart index 3bba80604da7..728f4091044c 100644 --- a/pkg/linter/lib/src/rules/cascade_invocations.dart +++ b/pkg/linter/lib/src/rules/cascade_invocations.dart @@ -13,7 +13,8 @@ import '../extensions.dart'; const _desc = r'Cascade consecutive method invocations on the same reference.'; Element2? _getElementFromVariableDeclarationStatement( - VariableDeclarationStatement statement) { + VariableDeclarationStatement statement, +) { var variables = statement.variables.variables; if (variables.length == 1) { var variable = variables.single; @@ -31,7 +32,8 @@ Element2? _getElementFromVariableDeclarationStatement( } ExecutableElement2? _getExecutableElementFromMethodInvocation( - MethodInvocation node) { + MethodInvocation node, +) { if (_isInvokedWithoutNullAwareOperator(node.operator)) { var executableElement = node.methodName.canonicalElement; if (executableElement is ExecutableElement2) { @@ -67,17 +69,16 @@ bool _isInvokedWithoutNullAwareOperator(Token? token) => class CascadeInvocations extends LintRule { /// Default constructor. CascadeInvocations() - : super( - name: LintNames.cascade_invocations, - description: _desc, - ); + : super(name: LintNames.cascade_invocations, description: _desc); @override LintCode get lintCode => LinterLintCode.cascade_invocations; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBlock(this, visitor); } @@ -86,8 +87,10 @@ class CascadeInvocations extends LintRule { /// A CascadableExpression is an object that is built from an expression and /// knows if it is able to join to another CascadableExpression. class _CascadableExpression { - static final nullCascadableExpression = - _CascadableExpression._internal(null, []); + static final nullCascadableExpression = _CascadableExpression._internal( + null, + [], + ); /// Whether this expression can be joined with a previous expression via a /// cascade operation. @@ -130,7 +133,8 @@ class _CascadableExpression { final List criticalNodes; factory _CascadableExpression.fromExpressionStatement( - ExpressionStatement statement) { + ExpressionStatement statement, + ) { var expression = statement.expression.unParenthesized; if (expression is AssignmentExpression) { return _CascadableExpression._fromAssignmentExpression(expression); @@ -152,37 +156,53 @@ class _CascadableExpression { } factory _CascadableExpression.fromVariableDeclarationStatement( - VariableDeclarationStatement node) { + VariableDeclarationStatement node, + ) { var element = _getElementFromVariableDeclarationStatement(node); - return _CascadableExpression._internal(element, [], - canReceive: true, isCritical: true); + return _CascadableExpression._internal( + element, + [], + canReceive: true, + isCritical: true, + ); } factory _CascadableExpression._fromAssignmentExpression( - AssignmentExpression node) { + AssignmentExpression node, + ) { var leftExpression = node.leftHandSide.unParenthesized; if (leftExpression is SimpleIdentifier) { return _CascadableExpression._internal( - leftExpression.element, [node.rightHandSide], - canReceive: node.operator.type != TokenType.QUESTION_QUESTION_EQ, - isCritical: true); + leftExpression.element, + [node.rightHandSide], + canReceive: node.operator.type != TokenType.QUESTION_QUESTION_EQ, + isCritical: true, + ); } // setters var variable = _getPrefixElementFromExpression(leftExpression); - var canReceive = node.operator.type != TokenType.QUESTION_QUESTION_EQ && + var canReceive = + node.operator.type != TokenType.QUESTION_QUESTION_EQ && variable is VariableElement2 && !variable.isStatic; - return _CascadableExpression._internal(variable, [node.rightHandSide], - canJoin: true, canReceive: canReceive, canBeCascaded: true); + return _CascadableExpression._internal( + variable, + [node.rightHandSide], + canJoin: true, + canReceive: canReceive, + canBeCascaded: true, + ); } factory _CascadableExpression._fromCascadeExpression(CascadeExpression node) { var targetIsSimple = node.target is SimpleIdentifier; return _CascadableExpression._internal( - _getTargetElementFromCascadeExpression(node), node.cascadeSections, - canJoin: targetIsSimple, - canReceive: targetIsSimple, - canBeCascaded: true); + _getTargetElementFromCascadeExpression(node), + node.cascadeSections, + canJoin: targetIsSimple, + canReceive: targetIsSimple, + canBeCascaded: true, + ); } factory _CascadableExpression._fromMethodInvocation(MethodInvocation node) { @@ -191,32 +211,45 @@ class _CascadableExpression { if (isNonStatic) { var targetIsSimple = node.target is SimpleIdentifier; return _CascadableExpression._internal( - _getTargetElementFromMethodInvocation(node), [node.argumentList], - canJoin: targetIsSimple, - canReceive: targetIsSimple, - canBeCascaded: true); + _getTargetElementFromMethodInvocation(node), + [node.argumentList], + canJoin: targetIsSimple, + canReceive: targetIsSimple, + canBeCascaded: true, + ); } return nullCascadableExpression; } factory _CascadableExpression._fromPrefixedIdentifier( - PrefixedIdentifier node) => - _CascadableExpression._internal(node.prefix.canonicalElement, [], - canJoin: true, canReceive: true, canBeCascaded: true); + PrefixedIdentifier node, + ) => _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.canonicalElement, [], - canJoin: targetIsSimple, - canReceive: targetIsSimple, - canBeCascaded: true); + return _CascadableExpression._internal( + node.target.canonicalElement, + [], + canJoin: targetIsSimple, + canReceive: targetIsSimple, + canBeCascaded: true, + ); } - _CascadableExpression._internal(this.element, this.criticalNodes, - {this.canJoin = false, - this.canReceive = false, - this.canBeCascaded = false, - this.isCritical = false}); + _CascadableExpression._internal( + this.element, + this.criticalNodes, { + this.canJoin = false, + this.canReceive = false, + this.canBeCascaded = false, + this.isCritical = false, + }); /// Whether `this` is compatible to be joined with [expressionBox] with a /// cascade operation. @@ -284,8 +317,9 @@ class _Visitor extends SimpleAstVisitor { _CascadableExpression.fromVariableDeclarationStatement(statement); } if (statement is ExpressionStatement) { - currentExpressionBox = - _CascadableExpression.fromExpressionStatement(statement); + currentExpressionBox = _CascadableExpression.fromExpressionStatement( + statement, + ); } if (currentExpressionBox.compatibleWith(previousExpressionBox)) { rule.reportLint(statement); diff --git a/pkg/linter/lib/src/rules/cast_nullable_to_non_nullable.dart b/pkg/linter/lib/src/rules/cast_nullable_to_non_nullable.dart index 6678cc45095d..5379173a4821 100644 --- a/pkg/linter/lib/src/rules/cast_nullable_to_non_nullable.dart +++ b/pkg/linter/lib/src/rules/cast_nullable_to_non_nullable.dart @@ -12,17 +12,16 @@ const _desc = r"Don't cast a nullable value to a non nullable type."; class CastNullableToNonNullable extends LintRule { CastNullableToNonNullable() - : super( - name: LintNames.cast_nullable_to_non_nullable, - description: _desc, - ); + : super(name: LintNames.cast_nullable_to_non_nullable, description: _desc); @override LintCode get lintCode => LinterLintCode.cast_nullable_to_non_nullable; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addAsExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/close_sinks.dart b/pkg/linter/lib/src/rules/close_sinks.dart index f93a3a0f28ac..00d967b61d23 100644 --- a/pkg/linter/lib/src/rules/close_sinks.dart +++ b/pkg/linter/lib/src/rules/close_sinks.dart @@ -11,18 +11,16 @@ import '../util/leak_detector_visitor.dart'; const _desc = r'Close instances of `dart:core` `Sink`.'; class CloseSinks extends LintRule { - CloseSinks() - : super( - name: LintNames.close_sinks, - description: _desc, - ); + CloseSinks() : super(name: LintNames.close_sinks, description: _desc); @override LintCode get lintCode => LinterLintCode.close_sinks; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addVariableDeclarationStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/collection_methods_unrelated_type.dart b/pkg/linter/lib/src/rules/collection_methods_unrelated_type.dart index 003817af0e8f..87f9ccf000ff 100644 --- a/pkg/linter/lib/src/rules/collection_methods_unrelated_type.dart +++ b/pkg/linter/lib/src/rules/collection_methods_unrelated_type.dart @@ -11,22 +11,25 @@ import 'package:analyzer/dart/element/type_provider.dart'; import '../analyzer.dart'; import '../util/dart_type_utilities.dart'; -const _desc = 'Invocation of various collection methods with arguments of ' +const _desc = + 'Invocation of various collection methods with arguments of ' 'unrelated types.'; class CollectionMethodsUnrelatedType extends LintRule { CollectionMethodsUnrelatedType() - : super( - name: LintNames.collection_methods_unrelated_type, - description: _desc, - ); + : super( + name: LintNames.collection_methods_unrelated_type, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.collection_methods_unrelated_type; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeSystem, context.typeProvider); registry.addIndexExpression(this, visitor); registry.addMethodInvocation(this, visitor); @@ -87,8 +90,12 @@ class _MethodDefinitionForName extends _MethodDefinition { final String interfaceName; - _MethodDefinitionForName(this.libraryName, this.interfaceName, - super.methodName, super.expectedArgumentKind); + _MethodDefinitionForName( + this.libraryName, + this.interfaceName, + super.methodName, + super.expectedArgumentKind, + ); @override InterfaceType? collectionTypeFor(InterfaceType targetType) { @@ -111,71 +118,72 @@ class _Visitor extends SimpleAstVisitor { _Visitor(this.rule, this.typeSystem, this.typeProvider); List<_MethodDefinition> get indexOperators => [ - // Argument to `Map.[]` should be assignable to `K`. - _MethodDefinitionForElement( - typeProvider.mapElement2, - '[]', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - ]; + // Argument to `Map.[]` should be assignable to `K`. + _MethodDefinitionForElement( + typeProvider.mapElement2, + '[]', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + ]; List<_MethodDefinition> get methods => [ - // Argument to `Iterable.contains` should be assignable to `E`. - _MethodDefinitionForElement( - typeProvider.iterableElement2, - 'contains', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `List.remove` should be assignable to `E`. - _MethodDefinitionForElement( - typeProvider.listElement2, - 'remove', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `Map.containsKey` should be assignable to `K`. - _MethodDefinitionForElement( - typeProvider.mapElement2, - 'containsKey', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `Map.containsValue` should be assignable to `V`. - _MethodDefinitionForElement( - typeProvider.mapElement2, - 'containsValue', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - typeArgumentIndex: 1, - ), - // Argument to `Map.remove` should be assignable to `K`. - _MethodDefinitionForElement( - typeProvider.mapElement2, - 'remove', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `Queue.remove` should be assignable to `E`. - _MethodDefinitionForName( - 'dart.collection', - 'Queue', - 'remove', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `Set.lookup` should be assignable to `E`. - _MethodDefinitionForElement( - typeProvider.setElement2, - 'lookup', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - // Argument to `Set.remove` should be assignable to `E`. - _MethodDefinitionForElement( - typeProvider.setElement2, - 'remove', - _ExpectedArgumentKind.assignableToCollectionTypeArgument, - ), - ]; + // Argument to `Iterable.contains` should be assignable to `E`. + _MethodDefinitionForElement( + typeProvider.iterableElement2, + 'contains', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `List.remove` should be assignable to `E`. + _MethodDefinitionForElement( + typeProvider.listElement2, + 'remove', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `Map.containsKey` should be assignable to `K`. + _MethodDefinitionForElement( + typeProvider.mapElement2, + 'containsKey', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `Map.containsValue` should be assignable to `V`. + _MethodDefinitionForElement( + typeProvider.mapElement2, + 'containsValue', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + typeArgumentIndex: 1, + ), + // Argument to `Map.remove` should be assignable to `K`. + _MethodDefinitionForElement( + typeProvider.mapElement2, + 'remove', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `Queue.remove` should be assignable to `E`. + _MethodDefinitionForName( + 'dart.collection', + 'Queue', + 'remove', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `Set.lookup` should be assignable to `E`. + _MethodDefinitionForElement( + typeProvider.setElement2, + 'lookup', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + // Argument to `Set.remove` should be assignable to `E`. + _MethodDefinitionForElement( + typeProvider.setElement2, + 'remove', + _ExpectedArgumentKind.assignableToCollectionTypeArgument, + ), + ]; @override void visitIndexExpression(IndexExpression node) { - var matchingMethods = - indexOperators.where((method) => '[]' == method.methodName); + var matchingMethods = indexOperators.where( + (method) => '[]' == method.methodName, + ); if (matchingMethods.isEmpty) { return; } @@ -200,8 +208,9 @@ class _Visitor extends SimpleAstVisitor { return; } - var matchingMethods = - methods.where((method) => node.methodName.name == method.methodName); + var matchingMethods = methods.where( + (method) => node.methodName.name == method.methodName, + ); if (matchingMethods.isEmpty) { return; } @@ -221,8 +230,11 @@ class _Visitor extends SimpleAstVisitor { for (var methodDefinition in matchingMethods) { var collectionType = methodDefinition.collectionTypeFor(targetType); if (collectionType != null) { - _checkMethod(node.argumentList.arguments.first, methodDefinition, - collectionType); + _checkMethod( + node.argumentList.arguments.first, + methodDefinition, + collectionType, + ); return; } } @@ -231,8 +243,11 @@ class _Visitor extends SimpleAstVisitor { /// Checks a [MethodInvocation] or [IndexExpression] which has a singular /// [argument] and matches [methodDefinition], with a target with a static /// type of [collectionType]. - void _checkMethod(Expression argument, _MethodDefinition methodDefinition, - InterfaceType collectionType) { + void _checkMethod( + Expression argument, + _MethodDefinition methodDefinition, + InterfaceType collectionType, + ) { // Finally, determine whether the type of the argument is related to the // type of the method target. var argumentType = argument.staticType; @@ -243,29 +258,39 @@ class _Visitor extends SimpleAstVisitor { var typeArgument = collectionType.typeArguments[methodDefinition.typeArgumentIndex]; if (typesAreUnrelated(typeSystem, argumentType, typeArgument)) { - rule.reportLint(argument, arguments: [ - argumentType.getDisplayString(), - typeArgument.getDisplayString(), - ]); + rule.reportLint( + argument, + arguments: [ + argumentType.getDisplayString(), + typeArgument.getDisplayString(), + ], + ); } case _ExpectedArgumentKind.assignableToCollection: if (!typeSystem.isAssignableTo(argumentType, collectionType)) { - rule.reportLint(argument, arguments: [ - argumentType.getDisplayString(), - collectionType.getDisplayString(), - ]); + rule.reportLint( + argument, + arguments: [ + argumentType.getDisplayString(), + collectionType.getDisplayString(), + ], + ); } case _ExpectedArgumentKind.assignableToIterableOfTypeArgument: - var iterableType = - collectionType.asInstanceOf2(typeProvider.iterableElement2); + var iterableType = collectionType.asInstanceOf2( + typeProvider.iterableElement2, + ); if (iterableType != null && !typeSystem.isAssignableTo(argumentType, iterableType)) { - rule.reportLint(argument, arguments: [ - argumentType.getDisplayString(), - iterableType.getDisplayString(), - ]); + rule.reportLint( + argument, + arguments: [ + argumentType.getDisplayString(), + iterableType.getDisplayString(), + ], + ); } } } @@ -276,9 +301,11 @@ class _Visitor extends SimpleAstVisitor { } // Look for an implicit receiver, starting with [node]'s parent's parent. - for (AstNode? parent = node.parent?.parent; - parent != null; - parent = parent.parent) { + for ( + AstNode? parent = node.parent?.parent; + parent != null; + parent = parent.parent + ) { if (parent is ClassDeclaration) { return parent.declaredFragment?.element.thisType; } else if (parent is MixinDeclaration) { diff --git a/pkg/linter/lib/src/rules/combinators_ordering.dart b/pkg/linter/lib/src/rules/combinators_ordering.dart index 3a8f49fbb1e5..42ebaff2c0e9 100644 --- a/pkg/linter/lib/src/rules/combinators_ordering.dart +++ b/pkg/linter/lib/src/rules/combinators_ordering.dart @@ -12,10 +12,7 @@ const _desc = r'Sort combinator names alphabetically.'; class CombinatorsOrdering extends LintRule { CombinatorsOrdering() - : super( - name: LintNames.combinators_ordering, - description: _desc, - ); + : super(name: LintNames.combinators_ordering, description: _desc); @override LintCode get lintCode => LinterLintCode.combinators_ordering; diff --git a/pkg/linter/lib/src/rules/comment_references.dart b/pkg/linter/lib/src/rules/comment_references.dart index b3c93db2febf..0d4dbdccf17e 100644 --- a/pkg/linter/lib/src/rules/comment_references.dart +++ b/pkg/linter/lib/src/rules/comment_references.dart @@ -11,17 +11,16 @@ const _desc = r'Only reference in-scope identifiers in doc comments.'; class CommentReferences extends LintRule { CommentReferences() - : super( - name: LintNames.comment_references, - description: _desc, - ); + : super(name: LintNames.comment_references, description: _desc); @override LintCode get lintCode => LinterLintCode.comment_references; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addComment(this, visitor); registry.addCommentReference(this, visitor); diff --git a/pkg/linter/lib/src/rules/conditional_uri_does_not_exist.dart b/pkg/linter/lib/src/rules/conditional_uri_does_not_exist.dart index 9f985a5f9b03..00b3abbfa37f 100644 --- a/pkg/linter/lib/src/rules/conditional_uri_does_not_exist.dart +++ b/pkg/linter/lib/src/rules/conditional_uri_does_not_exist.dart @@ -12,17 +12,16 @@ const _desc = r'Missing conditional import.'; class ConditionalUriDoesNotExist extends LintRule { ConditionalUriDoesNotExist() - : super( - name: LintNames.conditional_uri_does_not_exist, - description: _desc, - ); + : super(name: LintNames.conditional_uri_does_not_exist, description: _desc); @override LintCode get lintCode => LinterLintCode.conditional_uri_does_not_exist; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConfiguration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/constant_identifier_names.dart b/pkg/linter/lib/src/rules/constant_identifier_names.dart index d423f091940b..75dde9f3f683 100644 --- a/pkg/linter/lib/src/rules/constant_identifier_names.dart +++ b/pkg/linter/lib/src/rules/constant_identifier_names.dart @@ -14,17 +14,16 @@ const _desc = r'Prefer using lowerCamelCase for constant names.'; class ConstantIdentifierNames extends LintRule { ConstantIdentifierNames() - : super( - name: LintNames.constant_identifier_names, - description: _desc, - ); + : super(name: LintNames.constant_identifier_names, description: _desc); @override LintCode get lintCode => LinterLintCode.constant_identifier_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDeclaredVariablePattern(this, visitor); registry.addEnumConstantDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/control_flow_in_finally.dart b/pkg/linter/lib/src/rules/control_flow_in_finally.dart index eb358d7bdebc..e49224d570d9 100644 --- a/pkg/linter/lib/src/rules/control_flow_in_finally.dart +++ b/pkg/linter/lib/src/rules/control_flow_in_finally.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid control flow in `finally` blocks.'; class ControlFlowInFinally extends LintRule { ControlFlowInFinally() - : super( - name: LintNames.control_flow_in_finally, - description: _desc, - ); + : super(name: LintNames.control_flow_in_finally, description: _desc); @override LintCode get lintCode => LinterLintCode.control_flow_in_finally; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBreakStatement(this, visitor); registry.addContinueStatement(this, visitor); @@ -36,8 +35,11 @@ class ControlFlowInFinally extends LintRule { mixin ControlFlowInFinallyBlockReporter { LintRule get rule; - void reportIfFinallyAncestorExists(AstNode node, - {required String kind, AstNode? ancestor}) { + void reportIfFinallyAncestorExists( + AstNode node, { + required String kind, + AstNode? ancestor, + }) { var tryStatement = node.thisOrAncestorOfType(); var finallyBlock = tryStatement?.finallyBlock; bool finallyBlockAncestorPredicate(AstNode n) => n == finallyBlock; @@ -48,17 +50,22 @@ mixin ControlFlowInFinallyBlockReporter { } var enablerNode = _findEnablerNode( - ancestor, finallyBlockAncestorPredicate, node, tryStatement); + ancestor, + finallyBlockAncestorPredicate, + node, + tryStatement, + ); if (enablerNode == null) { rule.reportLint(node, arguments: [kind]); } } AstNode? _findEnablerNode( - AstNode? ancestor, - bool Function(AstNode n) finallyBlockAncestorPredicate, - AstNode node, - TryStatement tryStatement) { + AstNode? ancestor, + bool Function(AstNode n) finallyBlockAncestorPredicate, + AstNode node, + TryStatement tryStatement, + ) { AstNode? enablerNode; if (ancestor == null) { bool functionBlockPredicate(AstNode n) => @@ -87,8 +94,11 @@ class _Visitor extends SimpleAstVisitor @override void visitContinueStatement(ContinueStatement node) { - reportIfFinallyAncestorExists(node, - ancestor: node.target, kind: 'continue'); + reportIfFinallyAncestorExists( + node, + ancestor: node.target, + kind: 'continue', + ); } @override diff --git a/pkg/linter/lib/src/rules/curly_braces_in_flow_control_structures.dart b/pkg/linter/lib/src/rules/curly_braces_in_flow_control_structures.dart index c3d74dfd0e62..a961e29c3be7 100644 --- a/pkg/linter/lib/src/rules/curly_braces_in_flow_control_structures.dart +++ b/pkg/linter/lib/src/rules/curly_braces_in_flow_control_structures.dart @@ -11,10 +11,10 @@ const _desc = r'DO use curly braces for all flow control structures.'; class CurlyBracesInFlowControlStructures extends LintRule { CurlyBracesInFlowControlStructures() - : super( - name: LintNames.curly_braces_in_flow_control_structures, - description: _desc, - ); + : super( + name: LintNames.curly_braces_in_flow_control_structures, + description: _desc, + ); @override bool get canUseParsedResult => true; @@ -25,7 +25,9 @@ class CurlyBracesInFlowControlStructures extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDoStatement(this, visitor); registry.addForStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/dangling_library_doc_comments.dart b/pkg/linter/lib/src/rules/dangling_library_doc_comments.dart index 65385db2043a..265eed28c385 100644 --- a/pkg/linter/lib/src/rules/dangling_library_doc_comments.dart +++ b/pkg/linter/lib/src/rules/dangling_library_doc_comments.dart @@ -12,17 +12,16 @@ const _desc = r'Attach library doc comments to library directives.'; class DanglingLibraryDocComments extends LintRule { DanglingLibraryDocComments() - : super( - name: LintNames.dangling_library_doc_comments, - description: _desc, - ); + : super(name: LintNames.dangling_library_doc_comments, description: _desc); @override LintCode get lintCode => LinterLintCode.dangling_library_doc_comments; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } diff --git a/pkg/linter/lib/src/rules/deprecated_consistency.dart b/pkg/linter/lib/src/rules/deprecated_consistency.dart index 172fa9a437b2..3ac56ecd9165 100644 --- a/pkg/linter/lib/src/rules/deprecated_consistency.dart +++ b/pkg/linter/lib/src/rules/deprecated_consistency.dart @@ -12,21 +12,20 @@ const _desc = r'Missing deprecated annotation.'; class DeprecatedConsistency extends LintRule { DeprecatedConsistency() - : super( - name: LintNames.deprecated_consistency, - description: _desc, - ); + : super(name: LintNames.deprecated_consistency, description: _desc); @override List get lintCodes => [ - LinterLintCode.deprecated_consistency_constructor, - LinterLintCode.deprecated_consistency_field, - LinterLintCode.deprecated_consistency_parameter - ]; + LinterLintCode.deprecated_consistency_constructor, + LinterLintCode.deprecated_consistency_field, + LinterLintCode.deprecated_consistency_parameter, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addFieldFormalParameter(this, visitor); @@ -45,8 +44,11 @@ class _Visitor extends SimpleAstVisitor { constructorElement.enclosingElement2.hasDeprecated && !constructorElement.hasDeprecated) { var nodeToAnnotate = node.name ?? node.returnType; - rule.reportLintForOffset(nodeToAnnotate.offset, nodeToAnnotate.length, - errorCode: LinterLintCode.deprecated_consistency_constructor); + rule.reportLintForOffset( + nodeToAnnotate.offset, + nodeToAnnotate.length, + errorCode: LinterLintCode.deprecated_consistency_constructor, + ); } } @@ -59,8 +61,10 @@ class _Visitor extends SimpleAstVisitor { if (field == null) return; if (field.hasDeprecated && !declaredElement.hasDeprecated) { - rule.reportLint(node, - errorCode: LinterLintCode.deprecated_consistency_field); + rule.reportLint( + node, + errorCode: LinterLintCode.deprecated_consistency_field, + ); } if (!field.hasDeprecated && declaredElement.hasDeprecated) { var fieldFragment = field.firstFragment; @@ -68,8 +72,11 @@ class _Visitor extends SimpleAstVisitor { if (nameOffset == null) return; var nameLength = fieldFragment.name2?.length; if (nameLength == null) return; - rule.reportLintForOffset(nameOffset, nameLength, - errorCode: LinterLintCode.deprecated_consistency_parameter); + rule.reportLintForOffset( + nameOffset, + nameLength, + errorCode: LinterLintCode.deprecated_consistency_parameter, + ); } } } diff --git a/pkg/linter/lib/src/rules/deprecated_member_use_from_same_package.dart b/pkg/linter/lib/src/rules/deprecated_member_use_from_same_package.dart index 47ec8e3f2d37..bf05c54f9d15 100644 --- a/pkg/linter/lib/src/rules/deprecated_member_use_from_same_package.dart +++ b/pkg/linter/lib/src/rules/deprecated_member_use_from_same_package.dart @@ -19,20 +19,22 @@ const _desc = class DeprecatedMemberUseFromSamePackage extends LintRule { DeprecatedMemberUseFromSamePackage() - : super( - name: LintNames.deprecated_member_use_from_same_package, - description: _desc, - ); + : super( + name: LintNames.deprecated_member_use_from_same_package, + description: _desc, + ); @override List get lintCodes => [ - LinterLintCode.deprecated_member_use_from_same_package_with_message, - LinterLintCode.deprecated_member_use_from_same_package_without_message - ]; + LinterLintCode.deprecated_member_use_from_same_package_with_message, + LinterLintCode.deprecated_member_use_from_same_package_without_message, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); } @@ -45,8 +47,12 @@ class _DeprecatedMemberUseVerifier extends BaseDeprecatedMemberUseVerifier { _DeprecatedMemberUseVerifier(this._rule, this._workspacePackage); @override - void reportError2(SyntacticEntity errorEntity, Element2 element, - String displayName, String? message) { + void reportError2( + SyntacticEntity errorEntity, + Element2 element, + String displayName, + String? message, + ) { var library = element is LibraryElement2 ? element : element.library2; if (library == null || !_workspacePackage.contains(library.firstFragment.source)) { @@ -62,8 +68,9 @@ class _DeprecatedMemberUseVerifier extends BaseDeprecatedMemberUseVerifier { errorEntity.offset, errorEntity.length, arguments: [displayName], - errorCode: LinterLintCode - .deprecated_member_use_from_same_package_without_message, + errorCode: + LinterLintCode + .deprecated_member_use_from_same_package_without_message, ); } else { if (!normalizedMessage.endsWith('.') && @@ -88,10 +95,8 @@ class _DeprecatedMemberUseVerifier extends BaseDeprecatedMemberUseVerifier { class _RecursiveVisitor extends RecursiveAstVisitor { final _DeprecatedMemberUseVerifier _deprecatedVerifier; - _RecursiveVisitor( - LintRule rule, - WorkspacePackage package, - ) : _deprecatedVerifier = _DeprecatedMemberUseVerifier(rule, package); + _RecursiveVisitor(LintRule rule, WorkspacePackage package) + : _deprecatedVerifier = _DeprecatedMemberUseVerifier(rule, package); @override void visitAssignmentExpression(AssignmentExpression node) { @@ -286,7 +291,8 @@ class _RecursiveVisitor extends RecursiveAstVisitor { @override void visitRedirectingConstructorInvocation( - RedirectingConstructorInvocation node) { + RedirectingConstructorInvocation node, + ) { _deprecatedVerifier.redirectingConstructorInvocation(node); super.visitRedirectingConstructorInvocation(node); } @@ -335,10 +341,7 @@ class _RecursiveVisitor extends RecursiveAstVisitor { _withDeprecatedFragment(node.declaredFragment, recurse); } - void _withDeprecatedFragment( - Fragment? fragment, - void Function() recurse, - ) { + void _withDeprecatedFragment(Fragment? fragment, void Function() recurse) { var isDeprecated = false; if (fragment?.element case Annotatable annotatable) { isDeprecated = annotatable.metadata2.hasDeprecated; diff --git a/pkg/linter/lib/src/rules/diagnostic_describe_all_properties.dart b/pkg/linter/lib/src/rules/diagnostic_describe_all_properties.dart index b9d64d1c29c8..549765e7edd6 100644 --- a/pkg/linter/lib/src/rules/diagnostic_describe_all_properties.dart +++ b/pkg/linter/lib/src/rules/diagnostic_describe_all_properties.dart @@ -16,17 +16,19 @@ const _desc = r'DO reference all public properties in debug methods.'; class DiagnosticDescribeAllProperties extends LintRule { DiagnosticDescribeAllProperties() - : super( - name: LintNames.diagnostic_describe_all_properties, - description: _desc, - ); + : super( + name: LintNames.diagnostic_describe_all_properties, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.diagnostic_describe_all_properties; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addClassDeclaration(this, visitor); } @@ -44,7 +46,8 @@ class _IdentifierVisitor extends RecursiveAstVisitor { if (node.name.startsWith(debugPrefix) && node.name.length > debugPrefix.length) { debugName = node.name; - name = '${node.name[debugPrefix.length].toLowerCase()}' + name = + '${node.name[debugPrefix.length].toLowerCase()}' '${node.name.substring(debugPrefix.length + 1)}'; } else { name = node.name; @@ -52,7 +55,8 @@ class _IdentifierVisitor extends RecursiveAstVisitor { '$debugPrefix${node.name[0].toUpperCase()}${node.name.substring(1)}'; } properties.removeWhere( - (property) => property.lexeme == debugName || property.lexeme == name); + (property) => property.lexeme == debugName || property.lexeme == name, + ); super.visitSimpleIdentifier(node); } diff --git a/pkg/linter/lib/src/rules/directives_ordering.dart b/pkg/linter/lib/src/rules/directives_ordering.dart index 1840ccdeaa7b..8e62315e5190 100644 --- a/pkg/linter/lib/src/rules/directives_ordering.dart +++ b/pkg/linter/lib/src/rules/directives_ordering.dart @@ -61,34 +61,39 @@ class DirectivesOrdering extends LintRule { LinterLintCode.directives_ordering_alphabetical, LinterLintCode.directives_ordering_dart, LinterLintCode.directives_ordering_exports, - LinterLintCode.directives_ordering_package_before_relative + LinterLintCode.directives_ordering_package_before_relative, ]; DirectivesOrdering() - : super( - name: LintNames.directives_ordering, - description: _desc, - ); + : super(name: LintNames.directives_ordering, description: _desc); @override List get lintCodes => allCodes; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } void _reportLintWithDartDirectiveGoFirstMessage(AstNode node, String type) { - reportLint(node, - errorCode: LinterLintCode.directives_ordering_dart, arguments: [type]); + reportLint( + node, + errorCode: LinterLintCode.directives_ordering_dart, + arguments: [type], + ); } void _reportLintWithDirectiveSectionOrderedAlphabeticallyMessage( - AstNode node) { - reportLint(node, - errorCode: LinterLintCode.directives_ordering_alphabetical); + AstNode node, + ) { + reportLint( + node, + errorCode: LinterLintCode.directives_ordering_alphabetical, + ); } void _reportLintWithExportDirectiveAfterImportDirectiveMessage(AstNode node) { @@ -96,10 +101,14 @@ class DirectivesOrdering extends LintRule { } void _reportLintWithPackageDirectiveBeforeRelativeMessage( - AstNode node, String type) { - reportLint(node, - errorCode: LinterLintCode.directives_ordering_package_before_relative, - arguments: [type]); + AstNode node, + String type, + ) { + reportLint( + node, + errorCode: LinterLintCode.directives_ordering_package_before_relative, + arguments: [type], + ); } } @@ -118,7 +127,9 @@ class _Visitor extends SimpleAstVisitor { } void _checkDartDirectiveGoFirst( - Set lintedNodes, CompilationUnit node) { + Set lintedNodes, + CompilationUnit node, + ) { for (var import in node.importDirectives.withDartUrisSkippingTheFirstSet) { if (lintedNodes.add(import)) { rule._reportLintWithDartDirectiveGoFirstMessage(import, _importKeyword); @@ -135,13 +146,17 @@ class _Visitor extends SimpleAstVisitor { in node.docImportDirectives.withDartUrisSkippingTheFirstSet) { if (lintedNodes.add(import)) { rule._reportLintWithDartDirectiveGoFirstMessage( - import, _docImportKeyword); + import, + _docImportKeyword, + ); } } } void _checkDirectiveSectionOrderedAlphabetically( - Set lintedNodes, CompilationUnit node) { + Set lintedNodes, + CompilationUnit node, + ) { var dartImports = node.importDirectives.where(_isDartDirective); var dartExports = node.exportDirectives.where(_isDartDirective); var dartDocImports = node.docImportDirectives.where(_isDartDirective); @@ -152,8 +167,9 @@ class _Visitor extends SimpleAstVisitor { var relativeImports = node.importDirectives.where(_isRelativeDirective); var relativeExports = node.exportDirectives.where(_isRelativeDirective); - var relativeDocImports = - node.docImportDirectives.where(_isRelativeDirective); + var relativeDocImports = node.docImportDirectives.where( + _isRelativeDirective, + ); _checkSectionInOrder(lintedNodes, relativeImports); _checkSectionInOrder(lintedNodes, relativeExports); @@ -198,25 +214,32 @@ class _Visitor extends SimpleAstVisitor { } void _checkExportDirectiveAfterImportDirective( - Set lintedNodes, CompilationUnit node) { + Set lintedNodes, + CompilationUnit node, + ) { for (var directive in node.directives.reversed .skipWhile(_isPartDirective) .skipWhile(_isExportDirective) .where(_isExportDirective)) { if (lintedNodes.add(directive)) { rule._reportLintWithExportDirectiveAfterImportDirectiveMessage( - directive); + directive, + ); } } } void _checkPackageDirectiveBeforeRelative( - Set lintedNodes, CompilationUnit node) { + Set lintedNodes, + CompilationUnit node, + ) { for (var import in node.importDirectives.withPackageUrisSkippingAbsoluteUris) { if (lintedNodes.add(import)) { rule._reportLintWithPackageDirectiveBeforeRelativeMessage( - import, _importKeyword); + import, + _importKeyword, + ); } } @@ -224,7 +247,9 @@ class _Visitor extends SimpleAstVisitor { in node.exportDirectives.withPackageUrisSkippingAbsoluteUris) { if (lintedNodes.add(export)) { rule._reportLintWithPackageDirectiveBeforeRelativeMessage( - export, _exportKeyword); + export, + _exportKeyword, + ); } } @@ -232,13 +257,17 @@ class _Visitor extends SimpleAstVisitor { in node.docImportDirectives.withPackageUrisSkippingAbsoluteUris) { if (lintedNodes.add(import)) { rule._reportLintWithPackageDirectiveBeforeRelativeMessage( - import, _docImportKeyword); + import, + _docImportKeyword, + ); } } } void _checkSectionInOrder( - Set lintedNodes, Iterable nodes) { + Set lintedNodes, + Iterable nodes, + ) { if (nodes.isEmpty) return; var previousUri = nodes.first.uri.stringValue; @@ -249,7 +278,8 @@ class _Visitor extends SimpleAstVisitor { compareDirectives(previousUri, directiveUri) > 0) { if (lintedNodes.add(directive)) { rule._reportLintWithDirectiveSectionOrderedAlphabeticallyMessage( - directive); + directive, + ); } } previousUri = directive.uri.stringValue; @@ -281,8 +311,7 @@ extension on Iterable { /// The directives with 'package:' URIs, after the first set of directives /// with absolute URIs. - Iterable get withPackageUrisSkippingAbsoluteUris => - where(_isNotDartDirective) - .skipWhile(_isAbsoluteDirective) - .where(_isPackageDirective); + Iterable get withPackageUrisSkippingAbsoluteUris => where( + _isNotDartDirective, + ).skipWhile(_isAbsoluteDirective).where(_isPackageDirective); } diff --git a/pkg/linter/lib/src/rules/discarded_futures.dart b/pkg/linter/lib/src/rules/discarded_futures.dart index 0d5faf87354c..08f4cc2d81bc 100644 --- a/pkg/linter/lib/src/rules/discarded_futures.dart +++ b/pkg/linter/lib/src/rules/discarded_futures.dart @@ -13,17 +13,16 @@ const _desc = r"Don't invoke asynchronous functions in non-`async` blocks."; class DiscardedFutures extends LintRule { DiscardedFutures() - : super( - name: LintNames.discarded_futures, - description: _desc, - ); + : super(name: LintNames.discarded_futures, description: _desc); @override LintCode get lintCode => LinterLintCode.discarded_futures; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addFieldDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/do_not_use_environment.dart b/pkg/linter/lib/src/rules/do_not_use_environment.dart index 5dbebd0e88cb..3859f070be75 100644 --- a/pkg/linter/lib/src/rules/do_not_use_environment.dart +++ b/pkg/linter/lib/src/rules/do_not_use_environment.dart @@ -11,17 +11,16 @@ const _desc = r'Do not use environment declared variables.'; class DoNotUseEnvironment extends LintRule { DoNotUseEnvironment() - : super( - name: LintNames.do_not_use_environment, - description: _desc, - ); + : super(name: LintNames.do_not_use_environment, description: _desc); @override LintCode get lintCode => LinterLintCode.do_not_use_environment; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/document_ignores.dart b/pkg/linter/lib/src/rules/document_ignores.dart index 6c6690448cc2..580deea3f7a1 100644 --- a/pkg/linter/lib/src/rules/document_ignores.dart +++ b/pkg/linter/lib/src/rules/document_ignores.dart @@ -15,17 +15,16 @@ const _desc = r'Document ignore comments.'; class DocumentIgnores extends LintRule { DocumentIgnores() - : super( - name: LintNames.document_ignores, - description: _desc, - ); + : super(name: LintNames.document_ignores, description: _desc); @override LintCode get lintCode => LinterLintCode.document_ignores; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } @@ -54,8 +53,9 @@ class _Visitor extends SimpleAstVisitor { if (ignoreCommentLine > 1) { // Only look at the line above if the ignore comment line is not the // first line. - var previousLineOffset = - node.lineInfo.getOffsetOfLine(ignoreCommentLine - 2); + var previousLineOffset = node.lineInfo.getOffsetOfLine( + ignoreCommentLine - 2, + ); if (content != null && _startsWithEndOfLineComment(content, previousLineOffset)) { // A preceding comment, which may be attached to a different token, diff --git a/pkg/linter/lib/src/rules/empty_catches.dart b/pkg/linter/lib/src/rules/empty_catches.dart index 4a8ec86dc863..4c0ae253735a 100644 --- a/pkg/linter/lib/src/rules/empty_catches.dart +++ b/pkg/linter/lib/src/rules/empty_catches.dart @@ -11,18 +11,16 @@ import '../util/ascii_utils.dart'; const _desc = r'Avoid empty catch blocks.'; class EmptyCatches extends LintRule { - EmptyCatches() - : super( - name: LintNames.empty_catches, - description: _desc, - ); + EmptyCatches() : super(name: LintNames.empty_catches, description: _desc); @override LintCode get lintCode => LinterLintCode.empty_catches; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); } diff --git a/pkg/linter/lib/src/rules/empty_constructor_bodies.dart b/pkg/linter/lib/src/rules/empty_constructor_bodies.dart index 7c3030bf14cd..42d6f4015ab0 100644 --- a/pkg/linter/lib/src/rules/empty_constructor_bodies.dart +++ b/pkg/linter/lib/src/rules/empty_constructor_bodies.dart @@ -11,17 +11,16 @@ const _desc = r'Use `;` instead of `{}` for empty constructor bodies.'; class EmptyConstructorBodies extends LintRule { EmptyConstructorBodies() - : super( - name: LintNames.empty_constructor_bodies, - description: _desc, - ); + : super(name: LintNames.empty_constructor_bodies, description: _desc); @override LintCode get lintCode => LinterLintCode.empty_constructor_bodies; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/empty_statements.dart b/pkg/linter/lib/src/rules/empty_statements.dart index 34e1cab5a321..1f3c3bd2df01 100644 --- a/pkg/linter/lib/src/rules/empty_statements.dart +++ b/pkg/linter/lib/src/rules/empty_statements.dart @@ -11,17 +11,16 @@ const _desc = r'Avoid empty statements.'; class EmptyStatements extends LintRule { EmptyStatements() - : super( - name: LintNames.empty_statements, - description: _desc, - ); + : super(name: LintNames.empty_statements, description: _desc); @override LintCode get lintCode => LinterLintCode.empty_statements; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addEmptyStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/enable_null_safety.dart b/pkg/linter/lib/src/rules/enable_null_safety.dart index 151853f5b845..0cffd6f0284e 100644 --- a/pkg/linter/lib/src/rules/enable_null_safety.dart +++ b/pkg/linter/lib/src/rules/enable_null_safety.dart @@ -8,11 +8,11 @@ const _desc = r'Do use sound null safety.'; class EnableNullSafety extends LintRule { EnableNullSafety() - : super( - name: LintNames.enable_null_safety, - description: _desc, - state: State.removed(since: dart3), - ); + : super( + name: LintNames.enable_null_safety, + description: _desc, + state: State.removed(since: dart3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/eol_at_end_of_file.dart b/pkg/linter/lib/src/rules/eol_at_end_of_file.dart index a40d4f82d36e..70844c3d0ed2 100644 --- a/pkg/linter/lib/src/rules/eol_at_end_of_file.dart +++ b/pkg/linter/lib/src/rules/eol_at_end_of_file.dart @@ -11,17 +11,16 @@ const _desc = r'Put a single newline at end of file.'; class EolAtEndOfFile extends LintRule { EolAtEndOfFile() - : super( - name: LintNames.eol_at_end_of_file, - description: _desc, - ); + : super(name: LintNames.eol_at_end_of_file, description: _desc); @override LintCode get lintCode => LinterLintCode.eol_at_end_of_file; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); } diff --git a/pkg/linter/lib/src/rules/erase_dart_type_extension_types.dart b/pkg/linter/lib/src/rules/erase_dart_type_extension_types.dart index cfcfb59e9551..f90fa0c9ab3d 100644 --- a/pkg/linter/lib/src/rules/erase_dart_type_extension_types.dart +++ b/pkg/linter/lib/src/rules/erase_dart_type_extension_types.dart @@ -13,18 +13,20 @@ const _desc = r"Don't do 'is' checks on DartTypes."; class EraseDartTypeExtensionTypes extends LintRule { EraseDartTypeExtensionTypes() - : super( - name: LintNames.erase_dart_type_extension_types, - description: _desc, - state: const State.internal(), - ); + : super( + name: LintNames.erase_dart_type_extension_types, + description: _desc, + state: const State.internal(), + ); @override LintCode get lintCode => LinterLintCode.erase_dart_type_extension_types; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addIsExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/exhaustive_cases.dart b/pkg/linter/lib/src/rules/exhaustive_cases.dart index 30860265d158..db273a25d877 100644 --- a/pkg/linter/lib/src/rules/exhaustive_cases.dart +++ b/pkg/linter/lib/src/rules/exhaustive_cases.dart @@ -14,17 +14,16 @@ const _desc = r'Define case clauses for all constants in enum-like classes.'; class ExhaustiveCases extends LintRule { ExhaustiveCases() - : super( - name: LintNames.exhaustive_cases, - description: _desc, - ); + : super(name: LintNames.exhaustive_cases, description: _desc); @override LintCode get lintCode => LinterLintCode.exhaustive_cases; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSwitchStatement(this, visitor); } @@ -82,14 +81,11 @@ class _Visitor extends SimpleAstVisitor { var end = statement.rightParenthesis.end; var elements = enumConstants[constant]!; var preferredElement = elements.firstWhere( - (element) => !element.metadata2.hasDeprecated, - orElse: () => elements.first); + (element) => !element.metadata2.hasDeprecated, + orElse: () => elements.first, + ); if (preferredElement.name3 case var name?) { - rule.reportLintForOffset( - offset, - end - offset, - arguments: [name], - ); + rule.reportLintForOffset(offset, end - offset, arguments: [name]); } } } diff --git a/pkg/linter/lib/src/rules/file_names.dart b/pkg/linter/lib/src/rules/file_names.dart index c1d789d481d4..63409a8d06d2 100644 --- a/pkg/linter/lib/src/rules/file_names.dart +++ b/pkg/linter/lib/src/rules/file_names.dart @@ -11,18 +11,16 @@ import '../util/ascii_utils.dart'; const _desc = r'Name source files using `lowercase_with_underscores`.'; class FileNames extends LintRule { - FileNames() - : super( - name: LintNames.file_names, - description: _desc, - ); + FileNames() : super(name: LintNames.file_names, description: _desc); @override LintCode get lintCode => LinterLintCode.file_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } diff --git a/pkg/linter/lib/src/rules/flutter_style_todos.dart b/pkg/linter/lib/src/rules/flutter_style_todos.dart index 33cb230d4467..0c884d180c79 100644 --- a/pkg/linter/lib/src/rules/flutter_style_todos.dart +++ b/pkg/linter/lib/src/rules/flutter_style_todos.dart @@ -8,27 +8,28 @@ import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; -const _desc = r'Use Flutter TODO format: ' +const _desc = + r'Use Flutter TODO format: ' '// TODO(username): message, https://URL-to-issue.'; class FlutterStyleTodos extends LintRule { static final _todoRegExp = RegExp(r'//+\s*TODO\b', caseSensitive: false); - static final RegExp _todoExpectedRegExp = - RegExp(r'// TODO\([a-zA-Z0-9][-a-zA-Z0-9\.]*\): '); + static final RegExp _todoExpectedRegExp = RegExp( + r'// TODO\([a-zA-Z0-9][-a-zA-Z0-9\.]*\): ', + ); FlutterStyleTodos() - : super( - name: LintNames.flutter_style_todos, - description: _desc, - ); + : super(name: LintNames.flutter_style_todos, description: _desc); @override LintCode get lintCode => LinterLintCode.flutter_style_todos; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } diff --git a/pkg/linter/lib/src/rules/hash_and_equals.dart b/pkg/linter/lib/src/rules/hash_and_equals.dart index 4a60756caf0a..bf8d55599357 100644 --- a/pkg/linter/lib/src/rules/hash_and_equals.dart +++ b/pkg/linter/lib/src/rules/hash_and_equals.dart @@ -13,18 +13,16 @@ import '../ast.dart'; const _desc = r'Always override `hashCode` if overriding `==`.'; class HashAndEquals extends LintRule { - HashAndEquals() - : super( - name: LintNames.hash_and_equals, - description: _desc, - ); + HashAndEquals() : super(name: LintNames.hash_and_equals, description: _desc); @override LintCode get lintCode => LinterLintCode.hash_and_equals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); } @@ -53,8 +51,10 @@ class _Visitor extends SimpleAstVisitor { if (hash is MethodDeclaration) { rule.reportLintForToken(hash.name, arguments: ['==', 'hashCode']); } else if (hash is FieldDeclaration) { - rule.reportLintForToken(getFieldName(hash, 'hashCode'), - arguments: ['==', 'hashCode']); + rule.reportLintForToken( + getFieldName(hash, 'hashCode'), + arguments: ['==', 'hashCode'], + ); } } } diff --git a/pkg/linter/lib/src/rules/implementation_imports.dart b/pkg/linter/lib/src/rules/implementation_imports.dart index 6781411d1a1e..b70e010c6635 100644 --- a/pkg/linter/lib/src/rules/implementation_imports.dart +++ b/pkg/linter/lib/src/rules/implementation_imports.dart @@ -36,17 +36,16 @@ bool samePackage(Uri? uri1, Uri? uri2) { class ImplementationImports extends LintRule { ImplementationImports() - : super( - name: LintNames.implementation_imports, - description: _desc, - ); + : super(name: LintNames.implementation_imports, description: _desc); @override LintCode get lintCode => LinterLintCode.implementation_imports; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var libraryUri = context.libraryElement2?.uri; if (libraryUri == null) return; diff --git a/pkg/linter/lib/src/rules/implicit_call_tearoffs.dart b/pkg/linter/lib/src/rules/implicit_call_tearoffs.dart index 8dd0fbbb22b8..127ff99bde79 100644 --- a/pkg/linter/lib/src/rules/implicit_call_tearoffs.dart +++ b/pkg/linter/lib/src/rules/implicit_call_tearoffs.dart @@ -12,17 +12,16 @@ const _desc = class ImplicitCallTearoffs extends LintRule { ImplicitCallTearoffs() - : super( - name: LintNames.implicit_call_tearoffs, - description: _desc, - ); + : super(name: LintNames.implicit_call_tearoffs, description: _desc); @override LintCode get lintCode => LinterLintCode.implicit_call_tearoffs; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addImplicitCallReference(this, visitor); } diff --git a/pkg/linter/lib/src/rules/implicit_reopen.dart b/pkg/linter/lib/src/rules/implicit_reopen.dart index 8ff86a48c234..b94349ba3506 100644 --- a/pkg/linter/lib/src/rules/implicit_reopen.dart +++ b/pkg/linter/lib/src/rules/implicit_reopen.dart @@ -12,18 +12,20 @@ const _desc = r"Don't implicitly reopen classes."; class ImplicitReopen extends LintRule { ImplicitReopen() - : super( - name: LintNames.implicit_reopen, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.implicit_reopen, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.implicit_reopen; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addClassTypeAlias(this, visitor); @@ -35,8 +37,11 @@ class _Visitor extends SimpleAstVisitor { _Visitor(this.rule); - void checkElement(InterfaceElement2? element, NamedCompilationUnitMember node, - {required String type}) { + void checkElement( + InterfaceElement2? element, + NamedCompilationUnitMember node, { + required String type, + }) { if (element is! ClassElement2) return; if (element.metadata2.hasReopen) return; if (element.isSealed) return; @@ -49,18 +54,33 @@ class _Visitor extends SimpleAstVisitor { if (element.isBase) { if (supertype.isFinal) { - reportLint(node, - target: element, other: supertype, reason: 'final', type: type); + reportLint( + node, + target: element, + other: supertype, + reason: 'final', + type: type, + ); return; } else if (supertype.isInterface) { - reportLint(node, - target: element, other: supertype, reason: 'interface', type: type); + reportLint( + node, + target: element, + other: supertype, + reason: 'interface', + type: type, + ); return; } } else if (element.hasNoModifiers) { if (supertype.isInterface) { - reportLint(node, - target: element, other: supertype, reason: 'interface', type: type); + reportLint( + node, + target: element, + other: supertype, + reason: 'interface', + type: type, + ); return; } } diff --git a/pkg/linter/lib/src/rules/invalid_case_patterns.dart b/pkg/linter/lib/src/rules/invalid_case_patterns.dart index fcf1b0d7a6c7..c3db81ef7cdd 100644 --- a/pkg/linter/lib/src/rules/invalid_case_patterns.dart +++ b/pkg/linter/lib/src/rules/invalid_case_patterns.dart @@ -14,11 +14,11 @@ const _desc = r'Use case expressions that are valid in Dart 3.0.'; class InvalidCasePatterns extends LintRule { InvalidCasePatterns() - : super( - name: LintNames.invalid_case_patterns, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.invalid_case_patterns, + description: _desc, + state: const State.experimental(), + ); // TODO(pq): update to add specific messages w/ specific corrections // https://github.com/dart-lang/linter/issues/4172 @@ -27,7 +27,9 @@ class InvalidCasePatterns extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { // This lint rule is only meant for code which does not have 'patterns' // enabled. if (context.isEnabled(Feature.patterns)) return; diff --git a/pkg/linter/lib/src/rules/invalid_runtime_check_with_js_interop_types.dart b/pkg/linter/lib/src/rules/invalid_runtime_check_with_js_interop_types.dart index 134b58695f24..3db8fdfd0db2 100644 --- a/pkg/linter/lib/src/rules/invalid_runtime_check_with_js_interop_types.dart +++ b/pkg/linter/lib/src/rules/invalid_runtime_check_with_js_interop_types.dart @@ -39,9 +39,11 @@ bool _isJsInteropType(DartType type, _InteropTypeKind kind) { if (type is TypeParameterType) return _isJsInteropType(type.bound, kind); if (type is InterfaceType) { var element = type.element3; - var dartJsInteropTypeKind = kind == _InteropTypeKind.dartJsInteropType || + var dartJsInteropTypeKind = + kind == _InteropTypeKind.dartJsInteropType || kind == _InteropTypeKind.any; - var userJsInteropTypeKind = kind == _InteropTypeKind.userJsInteropType || + var userJsInteropTypeKind = + kind == _InteropTypeKind.userJsInteropType || kind == _InteropTypeKind.any; if (element is ExtensionTypeElement2) { if (dartJsInteropTypeKind && element.isFromLibrary(_dartJsInteropUri)) { @@ -49,9 +51,13 @@ bool _isJsInteropType(DartType type, _InteropTypeKind kind) { } else if (userJsInteropTypeKind) { var representationType = element.representation2.type; return _isJsInteropType( - representationType, _InteropTypeKind.dartJsInteropType) || + representationType, + _InteropTypeKind.dartJsInteropType, + ) || _isJsInteropType( - representationType, _InteropTypeKind.userJsInteropType); + representationType, + _InteropTypeKind.userJsInteropType, + ); } } else if (userJsInteropTypeKind && _jsTypeForStaticInterop(type) != null) { return true; @@ -195,28 +201,30 @@ class InteropTypeChecker extends RecursiveTypeVisitor { class InvalidRuntimeCheckWithJSInteropTypes extends LintRule { InvalidRuntimeCheckWithJSInteropTypes() - : super( - name: LintNames.invalid_runtime_check_with_js_interop_types, - description: _desc, - ); + : super( + name: LintNames.invalid_runtime_check_with_js_interop_types, + description: _desc, + ); @override List get lintCodes => [ - LinterLintCode.invalid_runtime_check_with_js_interop_types_dart_as_js, - LinterLintCode.invalid_runtime_check_with_js_interop_types_dart_is_js, - LinterLintCode.invalid_runtime_check_with_js_interop_types_js_as_dart, - LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_as_incompatible_js, - LinterLintCode.invalid_runtime_check_with_js_interop_types_js_is_dart, - LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js, - LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_is_unrelated_js - ]; + LinterLintCode.invalid_runtime_check_with_js_interop_types_dart_as_js, + LinterLintCode.invalid_runtime_check_with_js_interop_types_dart_is_js, + LinterLintCode.invalid_runtime_check_with_js_interop_types_js_as_dart, + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_as_incompatible_js, + LinterLintCode.invalid_runtime_check_with_js_interop_types_js_is_dart, + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js, + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_is_unrelated_js, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeSystem); registry.addIsExpression(this, visitor); registry.addAsExpression(this, visitor); @@ -231,11 +239,7 @@ class InvalidRuntimeCheckWithJSInteropTypes extends LintRule { /// representation type is a JS interop type, an `@staticInterop` type, or a /// type parameter that is bound to either. /// [any] corresponds to either a [dartJsInteropType] or [userJsInteropType]. -enum _InteropTypeKind { - dartJsInteropType, - userJsInteropType, - any, -} +enum _InteropTypeKind { dartJsInteropType, userJsInteropType, any } class _Visitor extends SimpleAstVisitor { final LintRule rule; @@ -245,7 +249,7 @@ class _Visitor extends SimpleAstVisitor { final InteropTypeChecker interopTypeChecker = InteropTypeChecker(); _Visitor(this.rule, TypeSystem typeSystem) - : typeSystem = typeSystem as TypeSystemImpl; + : typeSystem = typeSystem as TypeSystemImpl; /// Determines if a type test from [leftType] to [rightType] is a valid test /// for JS interop, and if not, returns the [LintCode] associated with the @@ -285,18 +289,27 @@ class _Visitor extends SimpleAstVisitor { /// Types that belong to JS interop libraries that are not available when /// compiling to Wasm are ignored. Nullability is also ignored for the purpose /// of this test. - LintCode? getInvalidJsInteropTypeTest(DartType leftType, DartType rightType, - {required bool check}) { + LintCode? getInvalidJsInteropTypeTest( + DartType leftType, + DartType rightType, { + required bool check, + }) { LintCode? lintCode; (DartType, DartType) eraseTypes(DartType left, DartType right) { - var erasedLeft = - typeSystem.promoteToNonNull(eraseNonJsInteropTypes.perform(left)); - var erasedRight = - typeSystem.promoteToNonNull(eraseNonJsInteropTypes.perform(right)); - var leftIsInteropType = - _isJsInteropType(erasedLeft, _InteropTypeKind.dartJsInteropType); - var rightIsInteropType = - _isJsInteropType(erasedRight, _InteropTypeKind.dartJsInteropType); + var erasedLeft = typeSystem.promoteToNonNull( + eraseNonJsInteropTypes.perform(left), + ); + var erasedRight = typeSystem.promoteToNonNull( + eraseNonJsInteropTypes.perform(right), + ); + var leftIsInteropType = _isJsInteropType( + erasedLeft, + _InteropTypeKind.dartJsInteropType, + ); + var rightIsInteropType = _isJsInteropType( + erasedRight, + _InteropTypeKind.dartJsInteropType, + ); // If there's already an invalid check in this `canBeSubtypeOf` check, we // are already going to lint, so only continue checking if we haven't // found an issue. @@ -304,23 +317,30 @@ class _Visitor extends SimpleAstVisitor { if (lintCode == null && leftIsInteropType || rightIsInteropType) { if (!_isWasmIncompatibleJsInterop(erasedLeft) && !_isWasmIncompatibleJsInterop(erasedRight)) { - var erasedLeftIsSubtype = - typeSystem.isSubtypeOf(erasedLeft, erasedRight); - var erasedRightIsSubtype = - typeSystem.isSubtypeOf(erasedRight, erasedLeft); + var erasedLeftIsSubtype = typeSystem.isSubtypeOf( + erasedLeft, + erasedRight, + ); + var erasedRightIsSubtype = typeSystem.isSubtypeOf( + erasedRight, + erasedLeft, + ); var erasedLeftIsDynamic = erasedLeft is DynamicType; var erasedRightIsDynamic = erasedRight is DynamicType; if (check) { if (!erasedLeftIsSubtype && !erasedRightIsDynamic) { if (leftIsInteropType && rightIsInteropType) { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_is_inconsistent_js; } else if (leftIsInteropType) { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_is_dart; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_is_dart; } else { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_dart_is_js; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_dart_is_js; } } else if (erasedLeftIsSubtype && leftIsInteropType && @@ -330,12 +350,18 @@ class _Visitor extends SimpleAstVisitor { // linting. if (_isJsInteropType(right, _InteropTypeKind.userJsInteropType) && !typeSystem.isSubtypeOf( - eraseNonJsInteropTypes.perform(left, - keepUserInteropTypes: true), - eraseNonJsInteropTypes.perform(right, - keepUserInteropTypes: true))) { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_is_unrelated_js; + eraseNonJsInteropTypes.perform( + left, + keepUserInteropTypes: true, + ), + eraseNonJsInteropTypes.perform( + right, + keepUserInteropTypes: true, + ), + )) { + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_is_unrelated_js; } } } else { @@ -344,14 +370,17 @@ class _Visitor extends SimpleAstVisitor { !erasedLeftIsDynamic && !erasedRightIsDynamic) { if (leftIsInteropType && rightIsInteropType) { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_as_incompatible_js; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_as_incompatible_js; } else if (leftIsInteropType) { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_js_as_dart; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_js_as_dart; } else { - lintCode = LinterLintCode - .invalid_runtime_check_with_js_interop_types_dart_as_js; + lintCode = + LinterLintCode + .invalid_runtime_check_with_js_interop_types_dart_as_js; } } } diff --git a/pkg/linter/lib/src/rules/invariant_booleans.dart b/pkg/linter/lib/src/rules/invariant_booleans.dart index 8e8371b79562..23ab09156f53 100644 --- a/pkg/linter/lib/src/rules/invariant_booleans.dart +++ b/pkg/linter/lib/src/rules/invariant_booleans.dart @@ -9,11 +9,11 @@ const _desc = class InvariantBooleans extends LintRule { InvariantBooleans() - : super( - name: LintNames.invariant_booleans, - description: _desc, - state: State.removed(since: dart3), - ); + : super( + name: LintNames.invariant_booleans, + description: _desc, + state: State.removed(since: dart3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/iterable_contains_unrelated_type.dart b/pkg/linter/lib/src/rules/iterable_contains_unrelated_type.dart index 7c18cdac6e1f..3986e3d93627 100644 --- a/pkg/linter/lib/src/rules/iterable_contains_unrelated_type.dart +++ b/pkg/linter/lib/src/rules/iterable_contains_unrelated_type.dart @@ -4,16 +4,17 @@ import '../analyzer.dart'; -const _desc = r'Invocation of `Iterable.contains` with references of' +const _desc = + r'Invocation of `Iterable.contains` with references of' r' unrelated types.'; class IterableContainsUnrelatedType extends LintRule { IterableContainsUnrelatedType() - : super( - name: LintNames.iterable_contains_unrelated_type, - description: _desc, - state: State.removed(since: dart3_3), - ); + : super( + name: LintNames.iterable_contains_unrelated_type, + description: _desc, + state: State.removed(since: dart3_3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/join_return_with_assignment.dart b/pkg/linter/lib/src/rules/join_return_with_assignment.dart index 6836be810893..d282b90c9a8b 100644 --- a/pkg/linter/lib/src/rules/join_return_with_assignment.dart +++ b/pkg/linter/lib/src/rules/join_return_with_assignment.dart @@ -29,17 +29,16 @@ Expression? _getExpressionFromReturnStatement(Statement node) => class JoinReturnWithAssignment extends LintRule { JoinReturnWithAssignment() - : super( - name: LintNames.join_return_with_assignment, - description: _desc, - ); + : super(name: LintNames.join_return_with_assignment, description: _desc); @override LintCode get lintCode => LinterLintCode.join_return_with_assignment; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBlock(this, visitor); } @@ -66,8 +65,9 @@ class _Visitor extends SimpleAstVisitor { } var secondLastStatement = statements[length - 2]; - var secondLastExpression = - _getExpressionFromAssignmentStatement(secondLastStatement); + var secondLastExpression = _getExpressionFromAssignmentStatement( + secondLastStatement, + ); // Return if the second-to-last statement was not an assignment. if (secondLastExpression == null) { return; @@ -76,13 +76,18 @@ class _Visitor extends SimpleAstVisitor { Expression? thirdLastExpression; if (length >= 3) { var thirdLastStatement = statements[length - 3]; - thirdLastExpression = - _getExpressionFromAssignmentStatement(thirdLastStatement); + thirdLastExpression = _getExpressionFromAssignmentStatement( + thirdLastStatement, + ); } if (!type_utils.canonicalElementsFromIdentifiersAreEqual( - secondLastExpression, thirdLastExpression) && + secondLastExpression, + thirdLastExpression, + ) && type_utils.canonicalElementsFromIdentifiersAreEqual( - lastExpression, secondLastExpression)) { + lastExpression, + secondLastExpression, + )) { rule.reportLint(secondLastStatement); } } diff --git a/pkg/linter/lib/src/rules/leading_newlines_in_multiline_strings.dart b/pkg/linter/lib/src/rules/leading_newlines_in_multiline_strings.dart index 2f8b3d0be3bd..45b175aad73d 100644 --- a/pkg/linter/lib/src/rules/leading_newlines_in_multiline_strings.dart +++ b/pkg/linter/lib/src/rules/leading_newlines_in_multiline_strings.dart @@ -11,17 +11,19 @@ const _desc = r'Start multiline strings with a newline.'; class LeadingNewlinesInMultilineStrings extends LintRule { LeadingNewlinesInMultilineStrings() - : super( - name: LintNames.leading_newlines_in_multiline_strings, - description: _desc, - ); + : super( + name: LintNames.leading_newlines_in_multiline_strings, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.leading_newlines_in_multiline_strings; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); registry.addSimpleStringLiteral(this, visitor); @@ -49,7 +51,9 @@ class _Visitor extends SimpleAstVisitor { @override void visitStringInterpolation(StringInterpolation node) { _visitSingleStringLiteral( - node, (node.elements.first as InterpolationString).contents.lexeme); + node, + (node.elements.first as InterpolationString).contents.lexeme, + ); } void _visitSingleStringLiteral(SingleStringLiteral node, String lexeme) { diff --git a/pkg/linter/lib/src/rules/library_annotations.dart b/pkg/linter/lib/src/rules/library_annotations.dart index 0b04a5c6d487..6a794cd290c6 100644 --- a/pkg/linter/lib/src/rules/library_annotations.dart +++ b/pkg/linter/lib/src/rules/library_annotations.dart @@ -15,17 +15,16 @@ const _desc = r'Attach library annotations to library directives.'; class LibraryAnnotations extends LintRule { LibraryAnnotations() - : super( - name: LintNames.library_annotations, - description: _desc, - ); + : super(name: LintNames.library_annotations, description: _desc); @override LintCode get lintCode => LinterLintCode.library_annotations; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); } diff --git a/pkg/linter/lib/src/rules/library_names.dart b/pkg/linter/lib/src/rules/library_names.dart index c02b9a1d5929..8fb4787d1345 100644 --- a/pkg/linter/lib/src/rules/library_names.dart +++ b/pkg/linter/lib/src/rules/library_names.dart @@ -11,18 +11,16 @@ import '../utils.dart'; const _desc = r'Name libraries using `lowercase_with_underscores`.'; class LibraryNames extends LintRule { - LibraryNames() - : super( - name: LintNames.library_names, - description: _desc, - ); + LibraryNames() : super(name: LintNames.library_names, description: _desc); @override LintCode get lintCode => LinterLintCode.library_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addLibraryDirective(this, visitor); } diff --git a/pkg/linter/lib/src/rules/library_prefixes.dart b/pkg/linter/lib/src/rules/library_prefixes.dart index eae988b91212..84a8a82a9b10 100644 --- a/pkg/linter/lib/src/rules/library_prefixes.dart +++ b/pkg/linter/lib/src/rules/library_prefixes.dart @@ -15,17 +15,16 @@ const _desc = class LibraryPrefixes extends LintRule { LibraryPrefixes() - : super( - name: LintNames.library_prefixes, - description: _desc, - ); + : super(name: LintNames.library_prefixes, description: _desc); @override LintCode get lintCode => LinterLintCode.library_prefixes; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addImportDirective(this, visitor); } @@ -38,8 +37,7 @@ class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule, LinterContext context) - : _wildCardVariablesEnabled = - context.isEnabled(Feature.wildcard_variables); + : _wildCardVariablesEnabled = context.isEnabled(Feature.wildcard_variables); @override void visitImportDirective(ImportDirective node) { diff --git a/pkg/linter/lib/src/rules/library_private_types_in_public_api.dart b/pkg/linter/lib/src/rules/library_private_types_in_public_api.dart index 522a93596dda..d27278f80f33 100644 --- a/pkg/linter/lib/src/rules/library_private_types_in_public_api.dart +++ b/pkg/linter/lib/src/rules/library_private_types_in_public_api.dart @@ -14,17 +14,19 @@ const _desc = r'Avoid using private types in public APIs.'; class LibraryPrivateTypesInPublicApi extends LintRule { LibraryPrivateTypesInPublicApi() - : super( - name: LintNames.library_private_types_in_public_api, - description: _desc, - ); + : super( + name: LintNames.library_private_types_in_public_api, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.library_private_types_in_public_api; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = Visitor(this); registry.addCompilationUnit(this, visitor); } @@ -110,8 +112,9 @@ class Validator extends SimpleAstVisitor { @override void visitFieldDeclaration(FieldDeclaration node) { if (node.isInvalidExtensionTypeField) return; - if (node.fields.variables - .any((field) => !Identifier.isPrivateName(field.name.lexeme))) { + if (node.fields.variables.any( + (field) => !Identifier.isPrivateName(field.name.lexeme), + )) { node.fields.type?.accept(this); } } @@ -252,8 +255,9 @@ class Validator extends SimpleAstVisitor { @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { - if (node.variables.variables - .any((field) => !Identifier.isPrivateName(field.name.lexeme))) { + if (node.variables.variables.any( + (field) => !Identifier.isPrivateName(field.name.lexeme), + )) { node.variables.type?.accept(this); } } diff --git a/pkg/linter/lib/src/rules/lines_longer_than_80_chars.dart b/pkg/linter/lib/src/rules/lines_longer_than_80_chars.dart index c7223d7470d8..7bd8e96d7534 100644 --- a/pkg/linter/lib/src/rules/lines_longer_than_80_chars.dart +++ b/pkg/linter/lib/src/rules/lines_longer_than_80_chars.dart @@ -20,17 +20,16 @@ bool _looksLikeUriOrPath(String value) => _uriRegExp.hasMatch(value); class LinesLongerThan80Chars extends LintRule { LinesLongerThan80Chars() - : super( - name: LintNames.lines_longer_than_80_chars, - description: _desc, - ); + : super(name: LintNames.lines_longer_than_80_chars, description: _desc); @override LintCode get lintCode => LinterLintCode.lines_longer_than_80_chars; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); } @@ -76,11 +75,13 @@ class _AllowedCommentVisitor extends SimpleAstVisitor { } } else if (content.startsWith('/*')) { // remove last slash before finding slash - lines.addAll(content - .substring(2, content.length - 2) - .split('$_cr$_lf') - .expand((e) => e.split(_cr)) - .expand((e) => e.split(_lf))); + lines.addAll( + content + .substring(2, content.length - 2) + .split('$_cr$_lf') + .expand((e) => e.split(_cr)) + .expand((e) => e.split(_lf)), + ); } for (var i = 0; i < lines.length; i++) { var value = lines[i]; @@ -112,12 +113,14 @@ class _AllowedLongLineVisitor extends RecursiveAstVisitor { if (node.isMultiline) { _handleMultilines(node); } else { - var value = node.elements.map((e) { - if (e is InterpolationString) return e.value; - if (e is InterpolationExpression) return ' ' * e.length; - throw ArgumentError( - 'Unhandled string interpolation element: ${node.runtimeType}'); - }).join(); + var value = + node.elements.map((e) { + if (e is InterpolationString) return e.value; + if (e is InterpolationExpression) return ' ' * e.length; + throw ArgumentError( + 'Unhandled string interpolation element: ${node.runtimeType}', + ); + }).join(); _handleSingleLine(node, value); } } @@ -194,7 +197,7 @@ class _Visitor extends SimpleAstVisitor { var allowedLines = [ ...allowedLineVisitor.allowedLines, - ...allowedCommentVisitor.allowedLines + ...allowedCommentVisitor.allowedLines, ]; for (var line in longLines) { diff --git a/pkg/linter/lib/src/rules/list_remove_unrelated_type.dart b/pkg/linter/lib/src/rules/list_remove_unrelated_type.dart index d7d320004a4e..82d1212d0488 100644 --- a/pkg/linter/lib/src/rules/list_remove_unrelated_type.dart +++ b/pkg/linter/lib/src/rules/list_remove_unrelated_type.dart @@ -8,11 +8,11 @@ const _desc = r'Invocation of `remove` with references of unrelated types.'; class ListRemoveUnrelatedType extends LintRule { ListRemoveUnrelatedType() - : super( - name: LintNames.list_remove_unrelated_type, - description: _desc, - state: State.removed(since: dart3_3), - ); + : super( + name: LintNames.list_remove_unrelated_type, + description: _desc, + state: State.removed(since: dart3_3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/literal_only_boolean_expressions.dart b/pkg/linter/lib/src/rules/literal_only_boolean_expressions.dart index 8efb50c62c42..3f97786d5c32 100644 --- a/pkg/linter/lib/src/rules/literal_only_boolean_expressions.dart +++ b/pkg/linter/lib/src/rules/literal_only_boolean_expressions.dart @@ -30,17 +30,19 @@ bool _onlyLiterals(Expression? rawExpression) { class LiteralOnlyBooleanExpressions extends LintRule { LiteralOnlyBooleanExpressions() - : super( - name: LintNames.literal_only_boolean_expressions, - description: _desc, - ); + : super( + name: LintNames.literal_only_boolean_expressions, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.literal_only_boolean_expressions; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDoStatement(this, visitor); registry.addForStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/matching_super_parameters.dart b/pkg/linter/lib/src/rules/matching_super_parameters.dart index d9dbc7d88379..ef33bf9e814c 100644 --- a/pkg/linter/lib/src/rules/matching_super_parameters.dart +++ b/pkg/linter/lib/src/rules/matching_super_parameters.dart @@ -12,17 +12,16 @@ const _desc = r'Use matching super parameter names.'; class MatchingSuperParameters extends LintRule { MatchingSuperParameters() - : super( - name: LintNames.matching_super_parameters, - description: _desc, - ); + : super(name: LintNames.matching_super_parameters, description: _desc); @override LintCode get lintCode => LinterLintCode.matching_super_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); } @@ -51,8 +50,13 @@ class _Visitor extends SimpleAstVisitor { if (superConstructor == null) { var class_ = node.parent; if (class_ is ClassDeclaration) { - superConstructor = class_ - .declaredFragment?.element.supertype?.element3.unnamedConstructor2; + superConstructor = + class_ + .declaredFragment + ?.element + .supertype + ?.element3 + .unnamedConstructor2; } } if (superConstructor is! ConstructorElement2) return; @@ -70,8 +74,10 @@ class _Visitor extends SimpleAstVisitor { var parameterOfSuperName = positionalParametersOfSuper[i].name3; if (parameterOfSuperName != null && superParameterName != parameterOfSuperName) { - rule.reportLint(superParameter, - arguments: [superParameterName, parameterOfSuperName]); + rule.reportLint( + superParameter, + arguments: [superParameterName, parameterOfSuperName], + ); } } } diff --git a/pkg/linter/lib/src/rules/missing_code_block_language_in_doc_comment.dart b/pkg/linter/lib/src/rules/missing_code_block_language_in_doc_comment.dart index 33116bbd187e..5e4bc3ad11ed 100644 --- a/pkg/linter/lib/src/rules/missing_code_block_language_in_doc_comment.dart +++ b/pkg/linter/lib/src/rules/missing_code_block_language_in_doc_comment.dart @@ -12,10 +12,10 @@ const _desc = r'A code block is missing a specified language.'; class MissingCodeBlockLanguageInDocComment extends LintRule { MissingCodeBlockLanguageInDocComment() - : super( - name: LintNames.missing_code_block_language_in_doc_comment, - description: _desc, - ); + : super( + name: LintNames.missing_code_block_language_in_doc_comment, + description: _desc, + ); @override LintCode get lintCode => @@ -23,7 +23,9 @@ class MissingCodeBlockLanguageInDocComment extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addComment(this, visitor); } diff --git a/pkg/linter/lib/src/rules/missing_whitespace_between_adjacent_strings.dart b/pkg/linter/lib/src/rules/missing_whitespace_between_adjacent_strings.dart index eafda96b6e52..025e11ecf97b 100644 --- a/pkg/linter/lib/src/rules/missing_whitespace_between_adjacent_strings.dart +++ b/pkg/linter/lib/src/rules/missing_whitespace_between_adjacent_strings.dart @@ -11,10 +11,10 @@ const _desc = r'Missing whitespace between adjacent strings.'; class MissingWhitespaceBetweenAdjacentStrings extends LintRule { MissingWhitespaceBetweenAdjacentStrings() - : super( - name: LintNames.missing_whitespace_between_adjacent_strings, - description: _desc, - ); + : super( + name: LintNames.missing_whitespace_between_adjacent_strings, + description: _desc, + ); @override LintCode get lintCode => @@ -22,7 +22,9 @@ class MissingWhitespaceBetweenAdjacentStrings extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAdjacentStrings(this, visitor); } @@ -42,8 +44,10 @@ class _Visitor extends SimpleAstVisitor { if (_isRegExpInstanceCreation(parentParent) || parentParent is MethodInvocation && parentParent.realTarget == null && - const ['RegExp', 'matches'] - .contains(parentParent.methodName.name)) { + const [ + 'RegExp', + 'matches', + ].contains(parentParent.methodName.name)) { return; } } @@ -84,8 +88,9 @@ extension on StringLiteral { return last.value.isEmpty || last.value.endsWithWhitespace; } throw ArgumentError( - 'Expected SimpleStringLiteral or StringInterpolation, but got ' - '$runtimeType'); + 'Expected SimpleStringLiteral or StringInterpolation, but got ' + '$runtimeType', + ); } /// Returns whether this contains whitespace, where any @@ -95,8 +100,9 @@ extension on StringLiteral { if (self is SimpleStringLiteral) { return self.value.hasWhitespace; } else if (self is StringInterpolation) { - return self.elements - .any((e) => e is InterpolationString && e.value.hasWhitespace); + return self.elements.any( + (e) => e is InterpolationString && e.value.hasWhitespace, + ); } return false; } @@ -112,8 +118,9 @@ extension on StringLiteral { return first.value.isEmpty || first.value.startsWithWhitespace; } throw ArgumentError( - 'Expected SimpleStringLiteral or StringInterpolation, but got ' - '$runtimeType'); + 'Expected SimpleStringLiteral or StringInterpolation, but got ' + '$runtimeType', + ); } } diff --git a/pkg/linter/lib/src/rules/no_adjacent_strings_in_list.dart b/pkg/linter/lib/src/rules/no_adjacent_strings_in_list.dart index 419491928364..fd7966435fb3 100644 --- a/pkg/linter/lib/src/rules/no_adjacent_strings_in_list.dart +++ b/pkg/linter/lib/src/rules/no_adjacent_strings_in_list.dart @@ -11,17 +11,16 @@ const _desc = r"Don't use adjacent strings in list."; class NoAdjacentStringsInList extends LintRule { NoAdjacentStringsInList() - : super( - name: LintNames.no_adjacent_strings_in_list, - description: _desc, - ); + : super(name: LintNames.no_adjacent_strings_in_list, description: _desc); @override LintCode get lintCode => LinterLintCode.no_adjacent_strings_in_list; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addForElement(this, visitor); registry.addIfElement(this, visitor); diff --git a/pkg/linter/lib/src/rules/no_default_cases.dart b/pkg/linter/lib/src/rules/no_default_cases.dart index 80240fc142bd..e7420ee22534 100644 --- a/pkg/linter/lib/src/rules/no_default_cases.dart +++ b/pkg/linter/lib/src/rules/no_default_cases.dart @@ -14,18 +14,20 @@ const _desc = r'No default cases.'; class NoDefaultCases extends LintRule { NoDefaultCases() - : super( - name: LintNames.no_default_cases, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.no_default_cases, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.no_default_cases; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSwitchStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/no_duplicate_case_values.dart b/pkg/linter/lib/src/rules/no_duplicate_case_values.dart index 312df40ff448..85f52ceec22e 100644 --- a/pkg/linter/lib/src/rules/no_duplicate_case_values.dart +++ b/pkg/linter/lib/src/rules/no_duplicate_case_values.dart @@ -13,17 +13,16 @@ const _desc = r"Don't use more than one case with same value."; class NoDuplicateCaseValues extends LintRule { NoDuplicateCaseValues() - : super( - name: LintNames.no_duplicate_case_values, - description: _desc, - ); + : super(name: LintNames.no_duplicate_case_values, description: _desc); @override LintCode get lintCode => LinterLintCode.no_duplicate_case_values; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSwitchStatement(this, visitor); } @@ -53,8 +52,10 @@ class _Visitor extends SimpleAstVisitor { // TODO(brianwilkeson): This would benefit from having a context message // pointing at the `duplicateValue`. if (duplicateValue != null) { - rule.reportLint(expression, - arguments: [expression.toString(), duplicateValue.toString()]); + rule.reportLint( + expression, + arguments: [expression.toString(), duplicateValue.toString()], + ); } else { values[value] = expression; } diff --git a/pkg/linter/lib/src/rules/no_leading_underscores_for_library_prefixes.dart b/pkg/linter/lib/src/rules/no_leading_underscores_for_library_prefixes.dart index 8d52e228cc3b..803a745ff2e1 100644 --- a/pkg/linter/lib/src/rules/no_leading_underscores_for_library_prefixes.dart +++ b/pkg/linter/lib/src/rules/no_leading_underscores_for_library_prefixes.dart @@ -14,10 +14,10 @@ const _desc = r'Avoid leading underscores for library prefixes.'; class NoLeadingUnderscoresForLibraryPrefixes extends LintRule { NoLeadingUnderscoresForLibraryPrefixes() - : super( - name: LintNames.no_leading_underscores_for_library_prefixes, - description: _desc, - ); + : super( + name: LintNames.no_leading_underscores_for_library_prefixes, + description: _desc, + ); @override LintCode get lintCode => @@ -25,7 +25,9 @@ class NoLeadingUnderscoresForLibraryPrefixes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addImportDirective(this, visitor); } @@ -38,8 +40,7 @@ class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule, LinterContext context) - : _wildCardVariablesEnabled = - context.isEnabled(Feature.wildcard_variables); + : _wildCardVariablesEnabled = context.isEnabled(Feature.wildcard_variables); void checkIdentifier(SimpleIdentifier? id) { if (id == null) return; diff --git a/pkg/linter/lib/src/rules/no_leading_underscores_for_local_identifiers.dart b/pkg/linter/lib/src/rules/no_leading_underscores_for_local_identifiers.dart index 771ee82055a4..fdc33d112bfd 100644 --- a/pkg/linter/lib/src/rules/no_leading_underscores_for_local_identifiers.dart +++ b/pkg/linter/lib/src/rules/no_leading_underscores_for_local_identifiers.dart @@ -14,10 +14,10 @@ const _desc = r'Avoid leading underscores for local identifiers.'; class NoLeadingUnderscoresForLocalIdentifiers extends LintRule { NoLeadingUnderscoresForLocalIdentifiers() - : super( - name: LintNames.no_leading_underscores_for_local_identifiers, - description: _desc, - ); + : super( + name: LintNames.no_leading_underscores_for_local_identifiers, + description: _desc, + ); @override LintCode get lintCode => @@ -25,7 +25,9 @@ class NoLeadingUnderscoresForLocalIdentifiers extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); registry.addDeclaredIdentifier(this, visitor); diff --git a/pkg/linter/lib/src/rules/no_literal_bool_comparisons.dart b/pkg/linter/lib/src/rules/no_literal_bool_comparisons.dart index c6b531d06a25..80d6346b4e97 100644 --- a/pkg/linter/lib/src/rules/no_literal_bool_comparisons.dart +++ b/pkg/linter/lib/src/rules/no_literal_bool_comparisons.dart @@ -13,17 +13,16 @@ const _desc = r"Don't compare boolean expressions to boolean literals."; class NoLiteralBoolComparisons extends LintRule { NoLiteralBoolComparisons() - : super( - name: LintNames.no_literal_bool_comparisons, - description: _desc, - ); + : super(name: LintNames.no_literal_bool_comparisons, description: _desc); @override LintCode get lintCode => LinterLintCode.no_literal_bool_comparisons; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addBinaryExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/no_logic_in_create_state.dart b/pkg/linter/lib/src/rules/no_logic_in_create_state.dart index a47257d3adbe..3305318a411e 100644 --- a/pkg/linter/lib/src/rules/no_logic_in_create_state.dart +++ b/pkg/linter/lib/src/rules/no_logic_in_create_state.dart @@ -12,17 +12,16 @@ const _desc = r"Don't put any logic in createState."; class NoLogicInCreateState extends LintRule { NoLogicInCreateState() - : super( - name: LintNames.no_logic_in_create_state, - description: _desc, - ); + : super(name: LintNames.no_logic_in_create_state, description: _desc); @override LintCode get lintCode => LinterLintCode.no_logic_in_create_state; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/no_runtimeType_toString.dart b/pkg/linter/lib/src/rules/no_runtimeType_toString.dart index 2d408e5e2402..22652da9a5e7 100644 --- a/pkg/linter/lib/src/rules/no_runtimeType_toString.dart +++ b/pkg/linter/lib/src/rules/no_runtimeType_toString.dart @@ -14,17 +14,16 @@ const _desc = r'Avoid calling `toString()` on `runtimeType`.'; class NoRuntimeTypeToString extends LintRule { NoRuntimeTypeToString() - : super( - name: LintNames.no_runtimeType_toString, - description: _desc, - ); + : super(name: LintNames.no_runtimeType_toString, description: _desc); @override LintCode get lintCode => LinterLintCode.no_runtimeType_toString; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInterpolationExpression(this, visitor); registry.addMethodInvocation(this, visitor); diff --git a/pkg/linter/lib/src/rules/no_self_assignments.dart b/pkg/linter/lib/src/rules/no_self_assignments.dart index 5570513dce55..7e13256598e8 100644 --- a/pkg/linter/lib/src/rules/no_self_assignments.dart +++ b/pkg/linter/lib/src/rules/no_self_assignments.dart @@ -12,17 +12,16 @@ const _desc = r"Don't assign a variable to itself."; class NoSelfAssignments extends LintRule { NoSelfAssignments() - : super( - name: LintNames.no_self_assignments, - description: _desc, - ); + : super(name: LintNames.no_self_assignments, description: _desc); @override LintCode get lintCode => LinterLintCode.no_self_assignments; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAssignmentExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/no_wildcard_variable_uses.dart b/pkg/linter/lib/src/rules/no_wildcard_variable_uses.dart index 24855cd47314..cedc56632419 100644 --- a/pkg/linter/lib/src/rules/no_wildcard_variable_uses.dart +++ b/pkg/linter/lib/src/rules/no_wildcard_variable_uses.dart @@ -14,17 +14,16 @@ const _desc = r"Don't use wildcard parameters or variables."; class NoWildcardVariableUses extends LintRule { NoWildcardVariableUses() - : super( - name: LintNames.no_wildcard_variable_uses, - description: _desc, - ); + : super(name: LintNames.no_wildcard_variable_uses, description: _desc); @override LintCode get lintCode => LinterLintCode.no_wildcard_variable_uses; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (context.libraryElement2.hasWildcardVariablesFeatureEnabled2) return; var visitor = _Visitor(this); diff --git a/pkg/linter/lib/src/rules/non_constant_identifier_names.dart b/pkg/linter/lib/src/rules/non_constant_identifier_names.dart index b88501b3ba64..1122eff869f0 100644 --- a/pkg/linter/lib/src/rules/non_constant_identifier_names.dart +++ b/pkg/linter/lib/src/rules/non_constant_identifier_names.dart @@ -15,17 +15,16 @@ const _desc = r'Name non-constant identifiers using lowerCamelCase.'; class NonConstantIdentifierNames extends LintRule { NonConstantIdentifierNames() - : super( - name: LintNames.non_constant_identifier_names, - description: _desc, - ); + : super(name: LintNames.non_constant_identifier_names, description: _desc); @override LintCode get lintCode => LinterLintCode.non_constant_identifier_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); registry.addConstructorDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/noop_primitive_operations.dart b/pkg/linter/lib/src/rules/noop_primitive_operations.dart index a3767fc863e3..0581f5a2f4cc 100644 --- a/pkg/linter/lib/src/rules/noop_primitive_operations.dart +++ b/pkg/linter/lib/src/rules/noop_primitive_operations.dart @@ -12,10 +12,7 @@ const _desc = r'Noop primitive operations.'; class NoopPrimitiveOperations extends LintRule { NoopPrimitiveOperations() - : super( - name: LintNames.noop_primitive_operations, - description: _desc, - ); + : super(name: LintNames.noop_primitive_operations, description: _desc); @override LintCode get lintCode => LinterLintCode.noop_primitive_operations; @@ -77,8 +74,13 @@ class _Visitor extends SimpleAstVisitor { // int invariant methods if (type.isDartCoreInt && - ['toInt', 'round', 'ceil', 'floor', 'truncate'] - .contains(node.methodName.name)) { + [ + 'toInt', + 'round', + 'ceil', + 'floor', + 'truncate', + ].contains(node.methodName.name)) { rule.reportLint(node.methodName); return; } diff --git a/pkg/linter/lib/src/rules/null_check_on_nullable_type_parameter.dart b/pkg/linter/lib/src/rules/null_check_on_nullable_type_parameter.dart index 0df812b47fc9..de38cba3b0e3 100644 --- a/pkg/linter/lib/src/rules/null_check_on_nullable_type_parameter.dart +++ b/pkg/linter/lib/src/rules/null_check_on_nullable_type_parameter.dart @@ -15,17 +15,19 @@ const _desc = class NullCheckOnNullableTypeParameter extends LintRule { NullCheckOnNullableTypeParameter() - : super( - name: LintNames.null_check_on_nullable_type_parameter, - description: _desc, - ); + : super( + name: LintNames.null_check_on_nullable_type_parameter, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.null_check_on_nullable_type_parameter; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addPostfixExpression(this, visitor); registry.addNullAssertPattern(this, visitor); diff --git a/pkg/linter/lib/src/rules/null_closures.dart b/pkg/linter/lib/src/rules/null_closures.dart index 053b5653352e..294345fc3c75 100644 --- a/pkg/linter/lib/src/rules/null_closures.dart +++ b/pkg/linter/lib/src/rules/null_closures.dart @@ -14,16 +14,16 @@ const _desc = r'Do not pass `null` as an argument where a closure is expected.'; List _constructorsWithNonNullableArguments = [ - NonNullableFunction('dart.async', 'Future', null, positional: [0]), - NonNullableFunction('dart.async', 'Future', 'microtask', positional: [0]), - NonNullableFunction('dart.async', 'Future', 'sync', positional: [0]), - NonNullableFunction('dart.async', 'Timer', null, positional: [1]), - NonNullableFunction('dart.async', 'Timer', 'periodic', positional: [1]), - NonNullableFunction('dart.core', 'List', 'generate', positional: [1]), -]; + NonNullableFunction('dart.async', 'Future', null, positional: [0]), + NonNullableFunction('dart.async', 'Future', 'microtask', positional: [0]), + NonNullableFunction('dart.async', 'Future', 'sync', positional: [0]), + NonNullableFunction('dart.async', 'Timer', null, positional: [1]), + NonNullableFunction('dart.async', 'Timer', 'periodic', positional: [1]), + NonNullableFunction('dart.core', 'List', 'generate', positional: [1]), + ]; final Map> - _instanceMethodsWithNonNullableArguments = { +_instanceMethodsWithNonNullableArguments = { 'any': { NonNullableFunction('dart.core', 'Iterable', 'any', positional: [0]), }, @@ -37,8 +37,13 @@ final Map> NonNullableFunction('dart.core', 'Iterable', 'expand', positional: [0]), }, 'firstWhere': { - NonNullableFunction('dart.core', 'Iterable', 'firstWhere', - positional: [0], named: ['orElse']), + NonNullableFunction( + 'dart.core', + 'Iterable', + 'firstWhere', + positional: [0], + named: ['orElse'], + ), }, 'forEach': { NonNullableFunction('dart.core', 'Iterable', 'forEach', positional: [0]), @@ -48,8 +53,13 @@ final Map> NonNullableFunction('dart.core', 'Iterable', 'fold', positional: [1]), }, 'lastWhere': { - NonNullableFunction('dart.core', 'Iterable', 'lastWhere', - positional: [0], named: ['orElse']), + NonNullableFunction( + 'dart.core', + 'Iterable', + 'lastWhere', + positional: [0], + named: ['orElse'], + ), }, 'map': { NonNullableFunction('dart.core', 'Iterable', 'map', positional: [0]), @@ -61,42 +71,72 @@ final Map> NonNullableFunction('dart.core', 'Iterable', 'reduce', positional: [0]), }, 'removeWhere': { - NonNullableFunction('dart.collection', 'Queue', 'removeWhere', - positional: [0]), + NonNullableFunction( + 'dart.collection', + 'Queue', + 'removeWhere', + positional: [0], + ), NonNullableFunction('dart.core', 'List', 'removeWhere', positional: [0]), NonNullableFunction('dart.core', 'Set', 'removeWhere', positional: [0]), }, 'replaceAllMapped': { - NonNullableFunction('dart.core', 'String', 'replaceAllMapped', - positional: [1]), + NonNullableFunction( + 'dart.core', + 'String', + 'replaceAllMapped', + positional: [1], + ), }, 'replaceFirstMapped': { - NonNullableFunction('dart.core', 'String', 'replaceFirstMapped', - positional: [1]), + NonNullableFunction( + 'dart.core', + 'String', + 'replaceFirstMapped', + positional: [1], + ), }, 'retainWhere': { - NonNullableFunction('dart.collection', 'Queue', 'retainWhere', - positional: [0]), + NonNullableFunction( + 'dart.collection', + 'Queue', + 'retainWhere', + positional: [0], + ), NonNullableFunction('dart.core', 'List', 'retainWhere', positional: [0]), NonNullableFunction('dart.core', 'Set', 'retainWhere', positional: [0]), }, 'singleWhere': { - NonNullableFunction('dart.core', 'Iterable', 'singleWhere', - positional: [0], named: ['orElse']), + NonNullableFunction( + 'dart.core', + 'Iterable', + 'singleWhere', + positional: [0], + named: ['orElse'], + ), }, 'skipWhile': { NonNullableFunction('dart.core', 'Iterable', 'skipWhile', positional: [0]), }, 'splitMapJoin': { - NonNullableFunction('dart.core', 'String', 'splitMapJoin', - named: ['onMatch', 'onNonMatch']), + NonNullableFunction( + 'dart.core', + 'String', + 'splitMapJoin', + named: ['onMatch', 'onNonMatch'], + ), }, 'takeWhile': { NonNullableFunction('dart.core', 'Iterable', 'takeWhile', positional: [0]), }, 'then': { - NonNullableFunction('dart.async', 'Future', 'then', - positional: [0], named: ['onError']), + NonNullableFunction( + 'dart.async', + 'Future', + 'then', + positional: [0], + named: ['onError'], + ), }, 'where': { NonNullableFunction('dart.core', 'Iterable', 'where', positional: [0]), @@ -105,12 +145,17 @@ final Map> List _staticFunctionsWithNonNullableArguments = [ - NonNullableFunction('dart.async', null, 'scheduleMicrotask', positional: [0]), - NonNullableFunction('dart.async', 'Future', 'doWhile', positional: [0]), - NonNullableFunction('dart.async', 'Future', 'forEach', positional: [1]), - NonNullableFunction('dart.async', 'Future', 'wait', named: ['cleanUp']), - NonNullableFunction('dart.async', 'Timer', 'run', positional: [0]), -]; + NonNullableFunction( + 'dart.async', + null, + 'scheduleMicrotask', + positional: [0], + ), + NonNullableFunction('dart.async', 'Future', 'doWhile', positional: [0]), + NonNullableFunction('dart.async', 'Future', 'forEach', positional: [1]), + NonNullableFunction('dart.async', 'Future', 'wait', named: ['cleanUp']), + NonNullableFunction('dart.async', 'Timer', 'run', positional: [0]), + ]; /// Function with closure parameters that cannot accept null arguments. class NonNullableFunction { @@ -120,8 +165,13 @@ class NonNullableFunction { final List positional; final List named; - NonNullableFunction(this.library, this.type, this.name, - {this.positional = const [], this.named = const []}); + NonNullableFunction( + this.library, + this.type, + this.name, { + this.positional = const [], + this.named = const [], + }); @override int get hashCode => @@ -136,18 +186,16 @@ class NonNullableFunction { } class NullClosures extends LintRule { - NullClosures() - : super( - name: LintNames.null_closures, - description: _desc, - ); + NullClosures() : super(name: LintNames.null_closures, description: _desc); @override LintCode get lintCode => LinterLintCode.null_closures; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); registry.addMethodInvocation(this, visitor); @@ -167,7 +215,10 @@ class _Visitor extends SimpleAstVisitor { if (constructorName.name?.name == constructor.name) { if (type.extendsClass(constructor.type, constructor.library)) { _checkNullArgForClosure( - node.argumentList, constructor.positional, constructor.named); + node.argumentList, + constructor.positional, + constructor.named, + ); } } } @@ -184,7 +235,10 @@ class _Visitor extends SimpleAstVisitor { if (methodName == function.name) { if (element.name3 == function.type) { _checkNullArgForClosure( - node.argumentList, function.positional, function.named); + node.argumentList, + function.positional, + function.named, + ); } } } @@ -195,12 +249,18 @@ class _Visitor extends SimpleAstVisitor { if (method == null) return; _checkNullArgForClosure( - node.argumentList, method.positional, method.named); + node.argumentList, + method.positional, + method.named, + ); } } void _checkNullArgForClosure( - ArgumentList node, List positions, List names) { + ArgumentList node, + List positions, + List names, + ) { var args = node.arguments; for (var i = 0; i < args.length; i++) { var arg = args[i]; @@ -226,8 +286,9 @@ class _Visitor extends SimpleAstVisitor { NonNullableFunction? getMethod(String? libraryName, String className) { if (libraryName == null) return null; - return possibleMethods - .lookup(NonNullableFunction(libraryName, className, methodName)); + return possibleMethods.lookup( + NonNullableFunction(libraryName, className, methodName), + ); } var element = type.element3; diff --git a/pkg/linter/lib/src/rules/omit_local_variable_types.dart b/pkg/linter/lib/src/rules/omit_local_variable_types.dart index 0f87904ab366..fe6f337be35b 100644 --- a/pkg/linter/lib/src/rules/omit_local_variable_types.dart +++ b/pkg/linter/lib/src/rules/omit_local_variable_types.dart @@ -14,23 +14,22 @@ const _desc = r'Omit type annotations for local variables.'; class OmitLocalVariableTypes extends LintRule { OmitLocalVariableTypes() - : super( - name: LintNames.omit_local_variable_types, - description: _desc, - ); + : super(name: LintNames.omit_local_variable_types, description: _desc); @override List get incompatibleRules => const [ - LintNames.always_specify_types, - LintNames.specify_nonobvious_local_variable_types, - ]; + LintNames.always_specify_types, + LintNames.specify_nonobvious_local_variable_types, + ]; @override LintCode get lintCode => LinterLintCode.omit_local_variable_types; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeProvider); registry.addForStatement(this, visitor); registry.addVariableDeclarationStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/omit_obvious_local_variable_types.dart b/pkg/linter/lib/src/rules/omit_obvious_local_variable_types.dart index 021eeb73a424..733c8343dc7a 100644 --- a/pkg/linter/lib/src/rules/omit_obvious_local_variable_types.dart +++ b/pkg/linter/lib/src/rules/omit_obvious_local_variable_types.dart @@ -13,11 +13,11 @@ const _desc = r'Omit obvious type annotations for local variables.'; class OmitObviousLocalVariableTypes extends LintRule { OmitObviousLocalVariableTypes() - : super( - name: LintNames.omit_obvious_local_variable_types, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.omit_obvious_local_variable_types, + description: _desc, + state: const State.experimental(), + ); @override List get incompatibleRules => const [LintNames.always_specify_types]; @@ -27,7 +27,9 @@ class OmitObviousLocalVariableTypes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addForStatement(this, visitor); registry.addVariableDeclarationStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/omit_obvious_property_types.dart b/pkg/linter/lib/src/rules/omit_obvious_property_types.dart index 4cdeb63a2011..18f1788874dd 100644 --- a/pkg/linter/lib/src/rules/omit_obvious_property_types.dart +++ b/pkg/linter/lib/src/rules/omit_obvious_property_types.dart @@ -13,11 +13,11 @@ const _desc = class OmitObviousPropertyTypes extends LintRule { OmitObviousPropertyTypes() - : super( - name: 'omit_obvious_property_types', - description: _desc, - state: const State.experimental(), - ); + : super( + name: 'omit_obvious_property_types', + description: _desc, + state: const State.experimental(), + ); @override List get incompatibleRules => const ['always_specify_types']; @@ -27,7 +27,9 @@ class OmitObviousPropertyTypes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addTopLevelVariableDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/one_member_abstracts.dart b/pkg/linter/lib/src/rules/one_member_abstracts.dart index 2290a9f71831..d490873ffc34 100644 --- a/pkg/linter/lib/src/rules/one_member_abstracts.dart +++ b/pkg/linter/lib/src/rules/one_member_abstracts.dart @@ -13,17 +13,16 @@ const _desc = class OneMemberAbstracts extends LintRule { OneMemberAbstracts() - : super( - name: LintNames.one_member_abstracts, - description: _desc, - ); + : super(name: LintNames.one_member_abstracts, description: _desc); @override LintCode get lintCode => LinterLintCode.one_member_abstracts; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/only_throw_errors.dart b/pkg/linter/lib/src/rules/only_throw_errors.dart index a77776a47a9e..2ed5c6af7ba4 100644 --- a/pkg/linter/lib/src/rules/only_throw_errors.dart +++ b/pkg/linter/lib/src/rules/only_throw_errors.dart @@ -28,17 +28,16 @@ bool _isThrowable(DartType? type) { class OnlyThrowErrors extends LintRule { OnlyThrowErrors() - : super( - name: LintNames.only_throw_errors, - description: _desc, - ); + : super(name: LintNames.only_throw_errors, description: _desc); @override LintCode get lintCode => LinterLintCode.only_throw_errors; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addThrowExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/overridden_fields.dart b/pkg/linter/lib/src/rules/overridden_fields.dart index d53dacba4055..6b6e1996118c 100644 --- a/pkg/linter/lib/src/rules/overridden_fields.dart +++ b/pkg/linter/lib/src/rules/overridden_fields.dart @@ -13,17 +13,16 @@ const _desc = r"Don't override fields."; class OverriddenFields extends LintRule { OverriddenFields() - : super( - name: LintNames.overridden_fields, - description: _desc, - ); + : super(name: LintNames.overridden_fields, description: _desc); @override LintCode get lintCode => LinterLintCode.overridden_fields; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addFieldDeclaration(this, visitor); } @@ -44,13 +43,17 @@ class _Visitor extends SimpleAstVisitor { var parent = variable.declaredFragment?.element.enclosingElement2; if (parent is InterfaceElement2) { var overriddenMember = inheritanceManager.getMember4( - parent, Name(parent.library2.uri, variable.name.lexeme), - forSuper: true); + parent, + Name(parent.library2.uri, variable.name.lexeme), + forSuper: true, + ); if (overriddenMember is GetterElement && overriddenMember.isSynthetic) { var definingInterface = overriddenMember.enclosingElement2; if (definingInterface != null) { - rule.reportLintForToken(variable.name, - arguments: [definingInterface.displayName]); + rule.reportLintForToken( + variable.name, + arguments: [definingInterface.displayName], + ); } } } diff --git a/pkg/linter/lib/src/rules/package_api_docs.dart b/pkg/linter/lib/src/rules/package_api_docs.dart index 95202900b21a..ba132f4689cf 100644 --- a/pkg/linter/lib/src/rules/package_api_docs.dart +++ b/pkg/linter/lib/src/rules/package_api_docs.dart @@ -8,10 +8,11 @@ import '../analyzer.dart'; class PackageApiDocs extends LintRule { PackageApiDocs() - : super( - name: LintNames.package_api_docs, - description: r'Provide doc comments for all public APIs.', - state: State.removed(since: Version(3, 7, 0))); + : super( + name: LintNames.package_api_docs, + description: r'Provide doc comments for all public APIs.', + state: State.removed(since: Version(3, 7, 0)), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/package_prefixed_library_names.dart b/pkg/linter/lib/src/rules/package_prefixed_library_names.dart index 99b9b5ba2324..a9d8023a5821 100644 --- a/pkg/linter/lib/src/rules/package_prefixed_library_names.dart +++ b/pkg/linter/lib/src/rules/package_prefixed_library_names.dart @@ -17,17 +17,16 @@ bool matchesOrIsPrefixedBy(String name, String prefix) => class PackagePrefixedLibraryNames extends LintRule { PackagePrefixedLibraryNames() - : super( - name: LintNames.package_prefixed_library_names, - description: _desc, - ); + : super(name: LintNames.package_prefixed_library_names, description: _desc); @override LintCode get lintCode => LinterLintCode.package_prefixed_library_names; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addLibraryDirective(this, visitor); } diff --git a/pkg/linter/lib/src/rules/parameter_assignments.dart b/pkg/linter/lib/src/rules/parameter_assignments.dart index fd657e639508..67f4612ab511 100644 --- a/pkg/linter/lib/src/rules/parameter_assignments.dart +++ b/pkg/linter/lib/src/rules/parameter_assignments.dart @@ -15,7 +15,9 @@ bool _isDefaultFormalParameterWithDefaultValue(FormalParameter parameter) => parameter is DefaultFormalParameter && parameter.defaultValue != null; bool _isFormalParameterReassigned( - FormalParameter parameter, AssignmentExpression assignment) { + FormalParameter parameter, + AssignmentExpression assignment, +) { var leftHandSide = assignment.leftHandSide; return leftHandSide is SimpleIdentifier && leftHandSide.element == parameter.declaredFragment?.element; @@ -23,17 +25,16 @@ bool _isFormalParameterReassigned( class ParameterAssignments extends LintRule { ParameterAssignments() - : super( - name: LintNames.parameter_assignments, - description: _desc, - ); + : super(name: LintNames.parameter_assignments, description: _desc); @override LintCode get lintCode => LinterLintCode.parameter_assignments; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); @@ -47,9 +48,12 @@ class _DeclarationVisitor extends RecursiveAstVisitor { final bool paramDefaultsToNull; bool hasBeenAssigned = false; - _DeclarationVisitor(this.parameter, this.rule, - {required this.paramIsNotNullByDefault, - required this.paramDefaultsToNull}); + _DeclarationVisitor( + this.parameter, + this.rule, { + required this.paramIsNotNullByDefault, + required this.paramDefaultsToNull, + }); Element2? get parameterElement => parameter.declaredFragment?.element; @@ -141,7 +145,9 @@ class _Visitor extends SimpleAstVisitor { @override void visitFunctionDeclaration(FunctionDeclaration node) { _checkParameters( - node.functionExpression.parameters, node.functionExpression.body); + node.functionExpression.parameters, + node.functionExpression.body, + ); } @override @@ -156,14 +162,21 @@ class _Visitor extends SimpleAstVisitor { var declaredElement = parameter.declaredFragment?.element; if (declaredElement != null && body.isPotentiallyMutatedInScope2(declaredElement)) { - var paramIsNotNullByDefault = parameter is SimpleFormalParameter || + var paramIsNotNullByDefault = + parameter is SimpleFormalParameter || _isDefaultFormalParameterWithDefaultValue(parameter); - var paramDefaultsToNull = parameter is DefaultFormalParameter && + var paramDefaultsToNull = + parameter is DefaultFormalParameter && parameter.defaultValue == null; if (paramDefaultsToNull || paramIsNotNullByDefault) { - body.accept(_DeclarationVisitor(parameter, rule, + body.accept( + _DeclarationVisitor( + parameter, + rule, paramDefaultsToNull: paramDefaultsToNull, - paramIsNotNullByDefault: paramIsNotNullByDefault)); + paramIsNotNullByDefault: paramIsNotNullByDefault, + ), + ); } } } @@ -172,7 +185,7 @@ class _Visitor extends SimpleAstVisitor { extension on AstNode { Element2? get element => switch (this) { - AssignedVariablePattern(:var element2) => element2, - _ => null, - }; + AssignedVariablePattern(:var element2) => element2, + _ => null, + }; } diff --git a/pkg/linter/lib/src/rules/prefer_adjacent_string_concatenation.dart b/pkg/linter/lib/src/rules/prefer_adjacent_string_concatenation.dart index f872abac1372..d537ef62082f 100644 --- a/pkg/linter/lib/src/rules/prefer_adjacent_string_concatenation.dart +++ b/pkg/linter/lib/src/rules/prefer_adjacent_string_concatenation.dart @@ -11,17 +11,19 @@ const _desc = r'Use adjacent strings to concatenate string literals.'; class PreferAdjacentStringConcatenation extends LintRule { PreferAdjacentStringConcatenation() - : super( - name: LintNames.prefer_adjacent_string_concatenation, - description: _desc, - ); + : super( + name: LintNames.prefer_adjacent_string_concatenation, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.prefer_adjacent_string_concatenation; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBinaryExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_asserts_in_initializer_lists.dart b/pkg/linter/lib/src/rules/prefer_asserts_in_initializer_lists.dart index cff862c5b7d9..a243cab1a352 100644 --- a/pkg/linter/lib/src/rules/prefer_asserts_in_initializer_lists.dart +++ b/pkg/linter/lib/src/rules/prefer_asserts_in_initializer_lists.dart @@ -13,17 +13,19 @@ const _desc = r'Prefer putting asserts in initializer lists.'; class PreferAssertsInInitializerLists extends LintRule { PreferAssertsInInitializerLists() - : super( - name: LintNames.prefer_asserts_in_initializer_lists, - description: _desc, - ); + : super( + name: LintNames.prefer_asserts_in_initializer_lists, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.prefer_asserts_in_initializer_lists; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addConstructorDeclaration(this, visitor); @@ -43,11 +45,13 @@ class _AssertVisitor extends RecursiveAstVisitor { var element = getWriteOrReadElement(node); // use method - needInstance = needInstance || + needInstance = + needInstance || element is MethodElement2 && !element.isStatic && _hasMethod(element); // use property accessor not used as field formal parameter - needInstance = needInstance || + needInstance = + needInstance || (element is PropertyAccessorElement2) && !element.isStatic && _hasAccessor(element) && @@ -69,8 +73,10 @@ class _AssertVisitor extends RecursiveAstVisitor { return classes != null && classes.contains(element.enclosingElement2); } - bool _paramMatchesField(PropertyAccessorElement2 element, - List parameters) { + bool _paramMatchesField( + PropertyAccessorElement2 element, + List parameters, + ) { for (var p in parameters) { FormalParameterElement? parameterElement = p; if (parameterElement is SuperFormalParameterElement2) { @@ -122,8 +128,9 @@ class _Visitor extends SimpleAstVisitor { @override void visitClassDeclaration(ClassDeclaration node) { - _classAndSuperClasses = - _ClassAndSuperClasses(node.declaredFragment?.element); + _classAndSuperClasses = _ClassAndSuperClasses( + node.declaredFragment?.element, + ); } @override @@ -136,8 +143,10 @@ class _Visitor extends SimpleAstVisitor { for (var statement in body.block.statements) { if (statement is! AssertStatement) break; - var assertVisitor = - _AssertVisitor(declaredElement, _classAndSuperClasses); + var assertVisitor = _AssertVisitor( + declaredElement, + _classAndSuperClasses, + ); statement.visitChildren(assertVisitor); if (!assertVisitor.needInstance) { rule.reportLintForToken(statement.beginToken); diff --git a/pkg/linter/lib/src/rules/prefer_asserts_with_message.dart b/pkg/linter/lib/src/rules/prefer_asserts_with_message.dart index 52b9cc9387ce..88310bb9dd33 100644 --- a/pkg/linter/lib/src/rules/prefer_asserts_with_message.dart +++ b/pkg/linter/lib/src/rules/prefer_asserts_with_message.dart @@ -11,17 +11,16 @@ const _desc = r'Prefer asserts with message.'; class PreferAssertsWithMessage extends LintRule { PreferAssertsWithMessage() - : super( - name: LintNames.prefer_asserts_with_message, - description: _desc, - ); + : super(name: LintNames.prefer_asserts_with_message, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_asserts_with_message; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAssertInitializer(this, visitor); registry.addAssertStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_bool_in_asserts.dart b/pkg/linter/lib/src/rules/prefer_bool_in_asserts.dart index b454099138ec..a6dc3c75d575 100644 --- a/pkg/linter/lib/src/rules/prefer_bool_in_asserts.dart +++ b/pkg/linter/lib/src/rules/prefer_bool_in_asserts.dart @@ -8,11 +8,11 @@ const _desc = r'Prefer using a boolean as the assert condition.'; class PreferBoolInAsserts extends LintRule { PreferBoolInAsserts() - : super( - name: LintNames.prefer_bool_in_asserts, - description: _desc, - state: State.removed(since: dart3), - ); + : super( + name: LintNames.prefer_bool_in_asserts, + description: _desc, + state: State.removed(since: dart3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/prefer_collection_literals.dart b/pkg/linter/lib/src/rules/prefer_collection_literals.dart index e81a0884cd95..dd68a6c524eb 100644 --- a/pkg/linter/lib/src/rules/prefer_collection_literals.dart +++ b/pkg/linter/lib/src/rules/prefer_collection_literals.dart @@ -15,17 +15,16 @@ const _desc = r'Use collection literals when possible.'; class PreferCollectionLiterals extends LintRule { PreferCollectionLiterals() - : super( - name: LintNames.prefer_collection_literals, - description: _desc, - ); + : super(name: LintNames.prefer_collection_literals, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_collection_literals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeProvider); registry.addInstanceCreationExpression(this, visitor); registry.addMethodInvocation(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_conditional_assignment.dart b/pkg/linter/lib/src/rules/prefer_conditional_assignment.dart index c0f8095d14b7..29bf615cb804 100644 --- a/pkg/linter/lib/src/rules/prefer_conditional_assignment.dart +++ b/pkg/linter/lib/src/rules/prefer_conditional_assignment.dart @@ -15,7 +15,9 @@ const _desc = r'Prefer using `??=` over testing for `null`.'; bool _checkExpression(Expression expression, Expression condition) => expression is AssignmentExpression && type_utils.canonicalElementsFromIdentifiersAreEqual( - expression.leftHandSide, condition); + expression.leftHandSide, + condition, + ); bool _checkStatement(Statement statement, Expression condition) { if (statement is ExpressionStatement) { @@ -43,17 +45,16 @@ Expression? _getExpressionCondition(Expression rawExpression) { class PreferConditionalAssignment extends LintRule { PreferConditionalAssignment() - : super( - name: LintNames.prefer_conditional_assignment, - description: _desc, - ); + : super(name: LintNames.prefer_conditional_assignment, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_conditional_assignment; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addIfStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_const_constructors.dart b/pkg/linter/lib/src/rules/prefer_const_constructors.dart index 5642fae4407b..1da31271a972 100644 --- a/pkg/linter/lib/src/rules/prefer_const_constructors.dart +++ b/pkg/linter/lib/src/rules/prefer_const_constructors.dart @@ -15,17 +15,16 @@ const _desc = r'Prefer `const` with constant constructors.'; class PreferConstConstructors extends LintRule { PreferConstConstructors() - : super( - name: LintNames.prefer_const_constructors, - description: _desc, - ); + : super(name: LintNames.prefer_const_constructors, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_const_constructors; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } @@ -58,11 +57,12 @@ class _Visitor extends SimpleAstVisitor { if (enclosingElement.typeParameters2.isNotEmpty && node.constructorName.type.typeArguments == null) { var approximateContextType = node.approximateContextType; - var contextTypeAsInstanceOfEnclosing = - approximateContextType?.asInstanceOf2(enclosingElement); + var contextTypeAsInstanceOfEnclosing = approximateContextType + ?.asInstanceOf2(enclosingElement); if (contextTypeAsInstanceOfEnclosing != null) { - if (contextTypeAsInstanceOfEnclosing.typeArguments - .any((e) => e is TypeParameterType)) { + if (contextTypeAsInstanceOfEnclosing.typeArguments.any( + (e) => e is TypeParameterType, + )) { // The context type has type parameters, which may be substituted via // upward inference from the static type of `node`. Changing `node` // from non-const to const will affect inference to change its own diff --git a/pkg/linter/lib/src/rules/prefer_const_constructors_in_immutables.dart b/pkg/linter/lib/src/rules/prefer_const_constructors_in_immutables.dart index 49ff7a23ad77..6327569d256a 100644 --- a/pkg/linter/lib/src/rules/prefer_const_constructors_in_immutables.dart +++ b/pkg/linter/lib/src/rules/prefer_const_constructors_in_immutables.dart @@ -15,10 +15,10 @@ const _desc = r'Prefer declaring `const` constructors on `@immutable` classes.'; class PreferConstConstructorsInImmutables extends LintRule { PreferConstConstructorsInImmutables() - : super( - name: LintNames.prefer_const_constructors_in_immutables, - description: _desc, - ); + : super( + name: LintNames.prefer_const_constructors_in_immutables, + description: _desc, + ); @override LintCode get lintCode => @@ -26,7 +26,9 @@ class PreferConstConstructorsInImmutables extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addExtensionTypeDeclaration(this, visitor); @@ -72,7 +74,8 @@ class _Visitor extends SimpleAstVisitor { } static List _getSelfAndSuperClasses( - InterfaceElement2 self) { + InterfaceElement2 self, + ) { InterfaceElement2? current = self; var seenElements = {}; while (current != null && seenElements.add(current)) { @@ -94,9 +97,10 @@ class _Visitor extends SimpleAstVisitor { return superInvocation.element?.isConst ?? false; } // Constructor with 'this' redirecting initializer. - var redirectInvocation = node.initializers - .whereType() - .firstOrNull; + var redirectInvocation = + node.initializers + .whereType() + .firstOrNull; if (redirectInvocation != null) { return redirectInvocation.element?.isConst ?? false; } diff --git a/pkg/linter/lib/src/rules/prefer_const_declarations.dart b/pkg/linter/lib/src/rules/prefer_const_declarations.dart index c14737b050a1..e50e38ca772d 100644 --- a/pkg/linter/lib/src/rules/prefer_const_declarations.dart +++ b/pkg/linter/lib/src/rules/prefer_const_declarations.dart @@ -13,17 +13,16 @@ const _desc = r'Prefer `const` over `final` for declarations.'; class PreferConstDeclarations extends LintRule { PreferConstDeclarations() - : super( - name: LintNames.prefer_const_declarations, - description: _desc, - ); + : super(name: LintNames.prefer_const_declarations, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_const_declarations; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addTopLevelVariableDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_const_literals_to_create_immutables.dart b/pkg/linter/lib/src/rules/prefer_const_literals_to_create_immutables.dart index a16ca76ac7f6..790f879130ba 100644 --- a/pkg/linter/lib/src/rules/prefer_const_literals_to_create_immutables.dart +++ b/pkg/linter/lib/src/rules/prefer_const_literals_to_create_immutables.dart @@ -14,10 +14,10 @@ const desc = class PreferConstLiteralsToCreateImmutables extends LintRule { PreferConstLiteralsToCreateImmutables() - : super( - name: LintNames.prefer_const_literals_to_create_immutables, - description: desc, - ); + : super( + name: LintNames.prefer_const_literals_to_create_immutables, + description: desc, + ); @override LintCode get lintCode => @@ -25,7 +25,9 @@ class PreferConstLiteralsToCreateImmutables extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addListLiteral(this, visitor); registry.addSetOrMapLiteral(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_constructors_over_static_methods.dart b/pkg/linter/lib/src/rules/prefer_constructors_over_static_methods.dart index 85c00081e92f..9a7fb420f6f9 100644 --- a/pkg/linter/lib/src/rules/prefer_constructors_over_static_methods.dart +++ b/pkg/linter/lib/src/rules/prefer_constructors_over_static_methods.dart @@ -17,10 +17,10 @@ bool _hasNewInvocation(DartType returnType, FunctionBody body) => class PreferConstructorsOverStaticMethods extends LintRule { PreferConstructorsOverStaticMethods() - : super( - name: LintNames.prefer_constructors_over_static_methods, - description: _desc, - ); + : super( + name: LintNames.prefer_constructors_over_static_methods, + description: _desc, + ); @override LintCode get lintCode => @@ -28,7 +28,9 @@ class PreferConstructorsOverStaticMethods extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } @@ -80,12 +82,10 @@ class _Visitor extends SimpleAstVisitor { extension on AstNode? { InterfaceType? typeToCheckOrNull() => switch (this) { - ExtensionTypeDeclaration e => e.typeParameters == null - ? e.declaredFragment?.element.thisType - : null, - ClassDeclaration c => c.typeParameters == null - ? c.declaredFragment?.element.thisType - : null, - _ => null - }; + ExtensionTypeDeclaration e => + e.typeParameters == null ? e.declaredFragment?.element.thisType : null, + ClassDeclaration c => + c.typeParameters == null ? c.declaredFragment?.element.thisType : null, + _ => null, + }; } diff --git a/pkg/linter/lib/src/rules/prefer_contains.dart b/pkg/linter/lib/src/rules/prefer_contains.dart index a3f7811d31a5..67e27656f4b3 100644 --- a/pkg/linter/lib/src/rules/prefer_contains.dart +++ b/pkg/linter/lib/src/rules/prefer_contains.dart @@ -14,25 +14,23 @@ import '../util/dart_type_utilities.dart'; const _desc = r'Use contains for `List` and `String` instances.'; class PreferContains extends LintRule { - PreferContains() - : super( - name: LintNames.prefer_contains, - description: _desc, - ); + PreferContains() : super(name: LintNames.prefer_contains, description: _desc); // TODO(brianwilkerson): Both `alwaysFalse` and `alwaysTrue` should be warnings // rather than lints because they represent a bug rather than a style // preference. @override List get lintCodes => [ - LinterLintCode.prefer_contains_always_false, - LinterLintCode.prefer_contains_always_true, - LinterLintCode.prefer_contains_use_contains - ]; + LinterLintCode.prefer_contains_always_false, + LinterLintCode.prefer_contains_always_true, + LinterLintCode.prefer_contains_use_contains, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addBinaryExpression(this, visitor); } @@ -79,23 +77,31 @@ class _Visitor extends SimpleAstVisitor { type == TokenType.BANG_EQ || type == TokenType.LT_EQ || type == TokenType.GT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_use_contains); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_use_contains, + ); } else if (type == TokenType.LT) { // indexOf < -1 is always false - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_always_false); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_always_false, + ); } else if (type == TokenType.GT_EQ) { // indexOf >= -1 is always true - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_always_true); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_always_true, + ); } } else if (value == 0) { // 'indexOf >= 0' is same as 'contains', // and 'indexOf < 0' is same as '!contains' if (type == TokenType.GT_EQ || type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_use_contains); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_use_contains, + ); } } else if (value < -1) { // 'indexOf' is always >= -1, so comparing with lesser values makes @@ -103,13 +109,17 @@ class _Visitor extends SimpleAstVisitor { if (type == TokenType.EQ_EQ || type == TokenType.LT_EQ || type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_always_false); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_always_false, + ); } else if (type == TokenType.BANG_EQ || type == TokenType.GT_EQ || type == TokenType.GT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_contains_always_true); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_contains_always_true, + ); } } } diff --git a/pkg/linter/lib/src/rules/prefer_double_quotes.dart b/pkg/linter/lib/src/rules/prefer_double_quotes.dart index 9c600230977f..4d2e4eb5d71a 100644 --- a/pkg/linter/lib/src/rules/prefer_double_quotes.dart +++ b/pkg/linter/lib/src/rules/prefer_double_quotes.dart @@ -10,10 +10,7 @@ const _desc = class PreferDoubleQuotes extends LintRule { PreferDoubleQuotes() - : super( - name: LintNames.prefer_double_quotes, - description: _desc, - ); + : super(name: LintNames.prefer_double_quotes, description: _desc); @override List get incompatibleRules => const [LintNames.prefer_single_quotes]; @@ -23,7 +20,9 @@ class PreferDoubleQuotes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = QuoteVisitor(this, useSingle: false); registry.addSimpleStringLiteral(this, visitor); registry.addStringInterpolation(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_equal_for_default_values.dart b/pkg/linter/lib/src/rules/prefer_equal_for_default_values.dart index 20c93691e365..529e51543bc2 100644 --- a/pkg/linter/lib/src/rules/prefer_equal_for_default_values.dart +++ b/pkg/linter/lib/src/rules/prefer_equal_for_default_values.dart @@ -8,11 +8,11 @@ const _desc = r'Use `=` to separate a named parameter from its default value.'; class PreferEqualForDefaultValues extends LintRule { PreferEqualForDefaultValues() - : super( - name: LintNames.prefer_equal_for_default_values, - description: _desc, - state: State.removed(since: dart3), - ); + : super( + name: LintNames.prefer_equal_for_default_values, + description: _desc, + state: State.removed(since: dart3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/prefer_expression_function_bodies.dart b/pkg/linter/lib/src/rules/prefer_expression_function_bodies.dart index 89b6298a5995..1a3fae2b9735 100644 --- a/pkg/linter/lib/src/rules/prefer_expression_function_bodies.dart +++ b/pkg/linter/lib/src/rules/prefer_expression_function_bodies.dart @@ -12,17 +12,19 @@ const _desc = class PreferExpressionFunctionBodies extends LintRule { PreferExpressionFunctionBodies() - : super( - name: LintNames.prefer_expression_function_bodies, - description: _desc, - ); + : super( + name: LintNames.prefer_expression_function_bodies, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.prefer_expression_function_bodies; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBlockFunctionBody(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_final_fields.dart b/pkg/linter/lib/src/rules/prefer_final_fields.dart index f6a13ef0db05..243d28e47d6f 100644 --- a/pkg/linter/lib/src/rules/prefer_final_fields.dart +++ b/pkg/linter/lib/src/rules/prefer_final_fields.dart @@ -14,17 +14,16 @@ const _desc = r'Private field could be `final`.'; class PreferFinalFields extends LintRule { PreferFinalFields() - : super( - name: LintNames.prefer_final_fields, - description: _desc, - ); + : super(name: LintNames.prefer_final_fields, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_final_fields; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); } @@ -38,8 +37,10 @@ class _DeclarationsCollector extends RecursiveAstVisitor { bool overridesField(FieldElement2 field) { var enclosingElement = field.enclosingElement2; if (enclosingElement is! InterfaceElement2) return false; - return inheritanceManager.getOverridden4(enclosingElement, - Name.forLibrary(field.library2, '${field.name3!}=')) != + return inheritanceManager.getOverridden4( + enclosingElement, + Name.forLibrary(field.library2, '${field.name3!}='), + ) != null; } @@ -111,8 +112,9 @@ class _Visitor extends SimpleAstVisitor { @override void visitCompilationUnit(CompilationUnit node) { - var declarationsCollector = - _DeclarationsCollector(context.inheritanceManager); + var declarationsCollector = _DeclarationsCollector( + context.inheritanceManager, + ); node.accept(declarationsCollector); var fields = declarationsCollector.fields; @@ -126,16 +128,19 @@ class _Visitor extends SimpleAstVisitor { // of which fields are initialized by any, and a set of which fields are // initialized by all. This would conceivably improve performance. var classDeclaration = variable.parent?.parent?.parent; - var constructors = classDeclaration is ClassDeclaration - ? classDeclaration.members.whereType() - : []; + var constructors = + classDeclaration is ClassDeclaration + ? classDeclaration.members.whereType() + : []; - var isSetInAnyConstructor = constructors - .any((constructor) => field.isSetInConstructor(constructor)); + var isSetInAnyConstructor = constructors.any( + (constructor) => field.isSetInConstructor(constructor), + ); if (isSetInAnyConstructor) { - var isSetInEveryConstructor = constructors - .every((constructor) => field.isSetInConstructor(constructor)); + var isSetInEveryConstructor = constructors.every( + (constructor) => field.isSetInConstructor(constructor), + ); if (isSetInEveryConstructor) { rule.reportLint(variable, arguments: [variable.name.lexeme]); diff --git a/pkg/linter/lib/src/rules/prefer_final_in_for_each.dart b/pkg/linter/lib/src/rules/prefer_final_in_for_each.dart index 849c6a708626..e716868d319d 100644 --- a/pkg/linter/lib/src/rules/prefer_final_in_for_each.dart +++ b/pkg/linter/lib/src/rules/prefer_final_in_for_each.dart @@ -13,23 +13,22 @@ const _desc = class PreferFinalInForEach extends LintRule { PreferFinalInForEach() - : super( - name: LintNames.prefer_final_in_for_each, - description: _desc, - ); + : super(name: LintNames.prefer_final_in_for_each, description: _desc); @override List get incompatibleRules => const [LintNames.unnecessary_final]; @override List get lintCodes => [ - LinterLintCode.prefer_final_in_for_each_pattern, - LinterLintCode.prefer_final_in_for_each_variable - ]; + LinterLintCode.prefer_final_in_for_each_pattern, + LinterLintCode.prefer_final_in_for_each_variable, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addForEachPartsWithDeclaration(this, visitor); registry.addForEachPartsWithPattern(this, visitor); @@ -52,9 +51,11 @@ class _Visitor extends SimpleAstVisitor { loopVariableElement != null && !function.isPotentiallyMutatedInScope2(loopVariableElement)) { var name = loopVariable.name; - rule.reportLintForToken(name, - errorCode: LinterLintCode.prefer_final_in_for_each_variable, - arguments: [name.lexeme]); + rule.reportLintForToken( + name, + errorCode: LinterLintCode.prefer_final_in_for_each_variable, + arguments: [name.lexeme], + ); } } @@ -68,24 +69,33 @@ class _Visitor extends SimpleAstVisitor { var pattern = node.pattern; if (pattern is RecordPattern) { if (!function.potentiallyMutatesAnyField(pattern.fields)) { - rule.reportLint(pattern, - errorCode: LinterLintCode.prefer_final_in_for_each_pattern); + rule.reportLint( + pattern, + errorCode: LinterLintCode.prefer_final_in_for_each_pattern, + ); } } else if (pattern is ObjectPattern) { if (!function.potentiallyMutatesAnyField(pattern.fields)) { - rule.reportLint(pattern, - errorCode: LinterLintCode.prefer_final_in_for_each_pattern); + rule.reportLint( + pattern, + errorCode: LinterLintCode.prefer_final_in_for_each_pattern, + ); } } else if (pattern is ListPattern) { if (!pattern.elements.any((e) => function.potentiallyMutates(e))) { - rule.reportLint(pattern, - errorCode: LinterLintCode.prefer_final_in_for_each_pattern); + rule.reportLint( + pattern, + errorCode: LinterLintCode.prefer_final_in_for_each_pattern, + ); } } else if (pattern is MapPattern) { - if (!pattern.elements.any((e) => - e is! MapPatternEntry || function.potentiallyMutates(e.value))) { - rule.reportLint(pattern, - errorCode: LinterLintCode.prefer_final_in_for_each_pattern); + if (!pattern.elements.any( + (e) => e is! MapPatternEntry || function.potentiallyMutates(e.value), + )) { + rule.reportLint( + pattern, + errorCode: LinterLintCode.prefer_final_in_for_each_pattern, + ); } } } diff --git a/pkg/linter/lib/src/rules/prefer_final_locals.dart b/pkg/linter/lib/src/rules/prefer_final_locals.dart index 3c2bdee0bd75..dfc0bda5f8cf 100644 --- a/pkg/linter/lib/src/rules/prefer_final_locals.dart +++ b/pkg/linter/lib/src/rules/prefer_final_locals.dart @@ -15,10 +15,7 @@ const _desc = class PreferFinalLocals extends LintRule { PreferFinalLocals() - : super( - name: LintNames.prefer_final_locals, - description: _desc, - ); + : super(name: LintNames.prefer_final_locals, description: _desc); @override List get incompatibleRules => const [LintNames.unnecessary_final]; @@ -28,7 +25,9 @@ class PreferFinalLocals extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDeclaredVariablePattern(this, visitor); registry.addPatternVariableDeclaration(this, visitor); @@ -82,8 +81,9 @@ class _Visitor extends SimpleAstVisitor { } else { var forEachPattern = node.thisOrAncestorOfType(); if (forEachPattern != null) { - if (forEachPattern - .hasPotentiallyMutatedDeclaredVariableInScope(function)) { + if (forEachPattern.hasPotentiallyMutatedDeclaredVariableInScope( + function, + )) { return; } } else { @@ -148,15 +148,19 @@ extension on DartPattern { bool get containsJustWildcards { var pattern = this; return switch (pattern) { - ListPattern() => pattern.elements - .every((e) => e is DartPattern && e.containsJustWildcards), - MapPattern() => pattern.elements - .every((e) => e is MapPatternEntry && e.value is WildcardPattern), - ObjectPattern() => - pattern.fields.every((e) => e.pattern.containsJustWildcards), + ListPattern() => pattern.elements.every( + (e) => e is DartPattern && e.containsJustWildcards, + ), + MapPattern() => pattern.elements.every( + (e) => e is MapPatternEntry && e.value is WildcardPattern, + ), + ObjectPattern() => pattern.fields.every( + (e) => e.pattern.containsJustWildcards, + ), ParenthesizedPattern() => pattern.pattern.containsJustWildcards, - RecordPattern() => - pattern.fields.every((e) => e.pattern.containsJustWildcards), + RecordPattern() => pattern.fields.every( + (e) => e.pattern.containsJustWildcards, + ), WildcardPattern() => true, _ => false, }; diff --git a/pkg/linter/lib/src/rules/prefer_final_parameters.dart b/pkg/linter/lib/src/rules/prefer_final_parameters.dart index 7533e9234ebc..ddf41d3850cf 100644 --- a/pkg/linter/lib/src/rules/prefer_final_parameters.dart +++ b/pkg/linter/lib/src/rules/prefer_final_parameters.dart @@ -13,21 +13,22 @@ const _desc = class PreferFinalParameters extends LintRule { PreferFinalParameters() - : super( - name: LintNames.prefer_final_parameters, - description: _desc, - ); + : super(name: LintNames.prefer_final_parameters, description: _desc); @override - List get incompatibleRules => - const [LintNames.unnecessary_final, LintNames.avoid_final_parameters]; + List get incompatibleRules => const [ + LintNames.unnecessary_final, + LintNames.avoid_final_parameters, + ]; @override LintCode get lintCode => LinterLintCode.prefer_final_parameters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addFunctionExpression(this, visitor); @@ -55,7 +56,9 @@ class _Visitor extends SimpleAstVisitor { /// Report the lint for parameters in the [parameters] list that are not /// const or final already and not potentially mutated in the function [body]. void _reportApplicableParameters( - FormalParameterList? parameters, FunctionBody body) { + FormalParameterList? parameters, + FunctionBody body, + ) { if (parameters != null) { for (var param in parameters.parameters) { if (param is DefaultFormalParameter) { diff --git a/pkg/linter/lib/src/rules/prefer_for_elements_to_map_fromIterable.dart b/pkg/linter/lib/src/rules/prefer_for_elements_to_map_fromIterable.dart index 3dadf58251b1..09cf01a90adf 100644 --- a/pkg/linter/lib/src/rules/prefer_for_elements_to_map_fromIterable.dart +++ b/pkg/linter/lib/src/rules/prefer_for_elements_to_map_fromIterable.dart @@ -12,10 +12,10 @@ const _desc = r'Prefer `for` elements when building maps from iterables.'; class PreferForElementsToMapFromIterable extends LintRule { PreferForElementsToMapFromIterable() - : super( - name: LintNames.prefer_for_elements_to_map_fromIterable, - description: _desc, - ); + : super( + name: LintNames.prefer_for_elements_to_map_fromIterable, + description: _desc, + ); @override LintCode get lintCode => @@ -23,7 +23,9 @@ class PreferForElementsToMapFromIterable extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addInstanceCreationExpression(this, visitor); } @@ -58,7 +60,8 @@ class _Visitor extends SimpleAstVisitor { var keyClosure = _extractClosure('key', secondArg) ?? _extractClosure('key', thirdArg); - var valueClosure = _extractClosure('value', thirdArg) ?? + var valueClosure = + _extractClosure('value', thirdArg) ?? _extractClosure('value', secondArg); if (keyClosure == null || valueClosure == null) { return; diff --git a/pkg/linter/lib/src/rules/prefer_foreach.dart b/pkg/linter/lib/src/rules/prefer_foreach.dart index 6b7ace4ab203..67532058d5b5 100644 --- a/pkg/linter/lib/src/rules/prefer_foreach.dart +++ b/pkg/linter/lib/src/rules/prefer_foreach.dart @@ -12,18 +12,16 @@ import '../extensions.dart'; const _desc = r'Use `forEach` to only apply a function to all the elements.'; class PreferForeach extends LintRule { - PreferForeach() - : super( - name: LintNames.prefer_foreach, - description: _desc, - ); + PreferForeach() : super(name: LintNames.prefer_foreach, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_foreach; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addForStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_function_declarations_over_variables.dart b/pkg/linter/lib/src/rules/prefer_function_declarations_over_variables.dart index 2de4344e90de..a9e55ec1d002 100644 --- a/pkg/linter/lib/src/rules/prefer_function_declarations_over_variables.dart +++ b/pkg/linter/lib/src/rules/prefer_function_declarations_over_variables.dart @@ -11,10 +11,10 @@ const _desc = r'Use a function declaration to bind a function to a name.'; class PreferFunctionDeclarationsOverVariables extends LintRule { PreferFunctionDeclarationsOverVariables() - : super( - name: LintNames.prefer_function_declarations_over_variables, - description: _desc, - ); + : super( + name: LintNames.prefer_function_declarations_over_variables, + description: _desc, + ); @override LintCode get lintCode => @@ -22,7 +22,9 @@ class PreferFunctionDeclarationsOverVariables extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addVariableDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_generic_function_type_aliases.dart b/pkg/linter/lib/src/rules/prefer_generic_function_type_aliases.dart index 4c264c4ad226..1a1832e6413e 100644 --- a/pkg/linter/lib/src/rules/prefer_generic_function_type_aliases.dart +++ b/pkg/linter/lib/src/rules/prefer_generic_function_type_aliases.dart @@ -11,10 +11,10 @@ const _desc = r'Prefer generic function type aliases.'; class PreferGenericFunctionTypeAliases extends LintRule { PreferGenericFunctionTypeAliases() - : super( - name: LintNames.prefer_generic_function_type_aliases, - description: _desc, - ); + : super( + name: LintNames.prefer_generic_function_type_aliases, + description: _desc, + ); @override bool get canUseParsedResult => true; @@ -24,7 +24,9 @@ class PreferGenericFunctionTypeAliases extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionTypeAlias(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_if_elements_to_conditional_expressions.dart b/pkg/linter/lib/src/rules/prefer_if_elements_to_conditional_expressions.dart index c25badfa9d12..46a361cf5c8c 100644 --- a/pkg/linter/lib/src/rules/prefer_if_elements_to_conditional_expressions.dart +++ b/pkg/linter/lib/src/rules/prefer_if_elements_to_conditional_expressions.dart @@ -11,10 +11,10 @@ const _desc = r'Prefer if elements to conditional expressions where possible.'; class PreferIfElementsToConditionalExpressions extends LintRule { PreferIfElementsToConditionalExpressions() - : super( - name: LintNames.prefer_if_elements_to_conditional_expressions, - description: _desc, - ); + : super( + name: LintNames.prefer_if_elements_to_conditional_expressions, + description: _desc, + ); @override LintCode get lintCode => @@ -22,7 +22,9 @@ class PreferIfElementsToConditionalExpressions extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConditionalExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_if_null_operators.dart b/pkg/linter/lib/src/rules/prefer_if_null_operators.dart index 337a5230ef38..f1b0798910a4 100644 --- a/pkg/linter/lib/src/rules/prefer_if_null_operators.dart +++ b/pkg/linter/lib/src/rules/prefer_if_null_operators.dart @@ -12,17 +12,16 @@ const _desc = r'Prefer using `??` operators.'; class PreferIfNullOperators extends LintRule { PreferIfNullOperators() - : super( - name: LintNames.prefer_if_null_operators, - description: _desc, - ); + : super(name: LintNames.prefer_if_null_operators, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_if_null_operators; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConditionalExpression(this, visitor); } @@ -49,9 +48,10 @@ class _Visitor extends SimpleAstVisitor { return; } - var exp = condition.operator.type == TokenType.EQ_EQ - ? node.elseExpression - : node.thenExpression; + var exp = + condition.operator.type == TokenType.EQ_EQ + ? node.elseExpression + : node.thenExpression; if (exp.toString() == expression.toString()) { rule.reportLint(node); } diff --git a/pkg/linter/lib/src/rules/prefer_initializing_formals.dart b/pkg/linter/lib/src/rules/prefer_initializing_formals.dart index f2702e37c20a..c05679bc0907 100644 --- a/pkg/linter/lib/src/rules/prefer_initializing_formals.dart +++ b/pkg/linter/lib/src/rules/prefer_initializing_formals.dart @@ -12,7 +12,8 @@ import '../extensions.dart'; const _desc = r'Use initializing formals when possible.'; Iterable _getAssignmentExpressionsInConstructorBody( - ConstructorDeclaration node) { + ConstructorDeclaration node, +) { var body = node.body; if (body is! BlockFunctionBody) return []; var assignments = []; @@ -28,9 +29,8 @@ Iterable _getAssignmentExpressionsInConstructorBody( } Iterable - _getConstructorFieldInitializersInInitializers( - ConstructorDeclaration node) => - node.initializers.whereType(); +_getConstructorFieldInitializersInInitializers(ConstructorDeclaration node) => + node.initializers.whereType(); Element2? _getLeftElement(AssignmentExpression assignment) => assignment.writeElement2?.canonicalElement2; @@ -43,17 +43,16 @@ Element2? _getRightElement(AssignmentExpression assignment) => class PreferInitializingFormals extends LintRule { PreferInitializingFormals() - : super( - name: LintNames.prefer_initializing_formals, - description: _desc, - ); + : super(name: LintNames.prefer_initializing_formals, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_initializing_formals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); } @@ -94,7 +93,8 @@ class _Visitor extends SimpleAstVisitor { } bool isConstructorFieldInitializerToLint( - ConstructorFieldInitializer constructorFieldInitializer) { + ConstructorFieldInitializer constructorFieldInitializer, + ) { var expression = constructorFieldInitializer.expression; if (expression is SimpleIdentifier) { var fieldName = constructorFieldInitializer.fieldName; diff --git a/pkg/linter/lib/src/rules/prefer_inlined_adds.dart b/pkg/linter/lib/src/rules/prefer_inlined_adds.dart index 326a8d05dda3..78205a11eabb 100644 --- a/pkg/linter/lib/src/rules/prefer_inlined_adds.dart +++ b/pkg/linter/lib/src/rules/prefer_inlined_adds.dart @@ -11,20 +11,19 @@ const _desc = r'Inline list item declarations where possible.'; class PreferInlinedAdds extends LintRule { PreferInlinedAdds() - : super( - name: LintNames.prefer_inlined_adds, - description: _desc, - ); + : super(name: LintNames.prefer_inlined_adds, description: _desc); @override List get lintCodes => [ - LinterLintCode.prefer_inlined_adds_multiple, - LinterLintCode.prefer_inlined_adds_single - ]; + LinterLintCode.prefer_inlined_adds_multiple, + LinterLintCode.prefer_inlined_adds_single, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } @@ -58,9 +57,12 @@ class _Visitor extends SimpleAstVisitor { return; } - rule.reportLint(invocation.methodName, - errorCode: addAll - ? LinterLintCode.prefer_inlined_adds_multiple - : LinterLintCode.prefer_inlined_adds_single); + rule.reportLint( + invocation.methodName, + errorCode: + addAll + ? LinterLintCode.prefer_inlined_adds_multiple + : LinterLintCode.prefer_inlined_adds_single, + ); } } diff --git a/pkg/linter/lib/src/rules/prefer_int_literals.dart b/pkg/linter/lib/src/rules/prefer_int_literals.dart index fe541323a896..4154784f804b 100644 --- a/pkg/linter/lib/src/rules/prefer_int_literals.dart +++ b/pkg/linter/lib/src/rules/prefer_int_literals.dart @@ -12,17 +12,16 @@ const _desc = 'Prefer int literals over double literals.'; class PreferIntLiterals extends LintRule { PreferIntLiterals() - : super( - name: LintNames.prefer_int_literals, - description: _desc, - ); + : super(name: LintNames.prefer_int_literals, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_int_literals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { registry.addDoubleLiteral(this, _Visitor(this)); } } diff --git a/pkg/linter/lib/src/rules/prefer_interpolation_to_compose_strings.dart b/pkg/linter/lib/src/rules/prefer_interpolation_to_compose_strings.dart index de5ce6bc29b4..cd32b6703cfe 100644 --- a/pkg/linter/lib/src/rules/prefer_interpolation_to_compose_strings.dart +++ b/pkg/linter/lib/src/rules/prefer_interpolation_to_compose_strings.dart @@ -13,10 +13,10 @@ const _desc = r'Use interpolation to compose strings and values.'; class PreferInterpolationToComposeStrings extends LintRule { PreferInterpolationToComposeStrings() - : super( - name: LintNames.prefer_interpolation_to_compose_strings, - description: _desc, - ); + : super( + name: LintNames.prefer_interpolation_to_compose_strings, + description: _desc, + ); @override LintCode get lintCode => @@ -24,7 +24,9 @@ class PreferInterpolationToComposeStrings extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBinaryExpression(this, visitor); } @@ -71,7 +73,9 @@ class _Visitor extends SimpleAstVisitor { if (leftOperand.staticType?.isDartCoreString ?? false) { rule.reportLintForOffset( - leftOperand.offset, rightOperand.end - leftOperand.offset); + leftOperand.offset, + rightOperand.end - leftOperand.offset, + ); // We've just reported `rightNode`; skip over it. i++; } @@ -85,9 +89,6 @@ extension on Expression { var self = this; if (self is! BinaryExpression) return [self]; if (self.operator.type != TokenType.PLUS) return const []; - return [ - ...self.leftOperand.chainedAdditions, - self.rightOperand, - ]; + return [...self.leftOperand.chainedAdditions, self.rightOperand]; } } diff --git a/pkg/linter/lib/src/rules/prefer_is_empty.dart b/pkg/linter/lib/src/rules/prefer_is_empty.dart index 78fa6c61d0b2..c889d20f39d7 100644 --- a/pkg/linter/lib/src/rules/prefer_is_empty.dart +++ b/pkg/linter/lib/src/rules/prefer_is_empty.dart @@ -14,26 +14,24 @@ import '../extensions.dart'; const _desc = r'Use `isEmpty` for `Iterable`s and `Map`s.'; class PreferIsEmpty extends LintRule { - PreferIsEmpty() - : super( - name: LintNames.prefer_is_empty, - description: _desc, - ); + PreferIsEmpty() : super(name: LintNames.prefer_is_empty, description: _desc); // TODO(brianwilkerson): Both `alwaysFalse` and `alwaysTrue` should be warnings // rather than lints because they represent a bug rather than a style // preference. @override List get lintCodes => [ - LinterLintCode.prefer_is_empty_always_false, - LinterLintCode.prefer_is_empty_always_true, - LinterLintCode.prefer_is_empty_use_is_empty, - LinterLintCode.prefer_is_empty_use_is_not_empty - ]; + LinterLintCode.prefer_is_empty_always_false, + LinterLintCode.prefer_is_empty_always_true, + LinterLintCode.prefer_is_empty_use_is_empty, + LinterLintCode.prefer_is_empty_use_is_not_empty, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addBinaryExpression(this, visitor); } @@ -65,8 +63,11 @@ class _Visitor extends SimpleAstVisitor { } } - void _check(BinaryExpression expression, int value, - {required bool constantOnRight}) { + void _check( + BinaryExpression expression, + int value, { + required bool constantOnRight, + }) { // Don't lint if we're in a const constructor initializer. var constructorInitializer = expression.thisOrAncestorOfType(); @@ -88,39 +89,55 @@ class _Visitor extends SimpleAstVisitor { if (value == 0) { if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.LT_EQ) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_empty, + ); } else if (operator.type == TokenType.GT || operator.type == TokenType.BANG_EQ) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty, + ); } else if (operator.type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_false); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_false, + ); } else if (operator.type == TokenType.GT_EQ) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_true); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_true, + ); } } else if (value == 1) { if (constantOnRight) { // 'length >= 1' is same as 'isNotEmpty', // and 'length < 1' is same as 'isEmpty' if (operator.type == TokenType.GT_EQ) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty, + ); } else if (operator.type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_empty, + ); } } else { // '1 <= length' is same as 'isNotEmpty', // and '1 > length' is same as 'isEmpty' if (operator.type == TokenType.LT_EQ) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_not_empty, + ); } else if (operator.type == TokenType.GT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_use_is_empty); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_use_is_empty, + ); } } } else if (value < 0) { @@ -129,34 +146,45 @@ class _Visitor extends SimpleAstVisitor { if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.LT_EQ || operator.type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_false); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_false, + ); } else if (operator.type == TokenType.BANG_EQ || operator.type == TokenType.GT_EQ || operator.type == TokenType.GT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_true); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_true, + ); } } else { // 'length' is always >= 0, so comparing with negative makes no sense. if (operator.type == TokenType.EQ_EQ || operator.type == TokenType.GT_EQ || operator.type == TokenType.GT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_false); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_false, + ); } else if (operator.type == TokenType.BANG_EQ || operator.type == TokenType.LT_EQ || operator.type == TokenType.LT) { - rule.reportLint(expression, - errorCode: LinterLintCode.prefer_is_empty_always_true); + rule.reportLint( + expression, + errorCode: LinterLintCode.prefer_is_empty_always_true, + ); } } } } // TODO(pq): consider sharing - T? _drillDownTo(Expression expression, - {required bool ignoreParens, required bool ignoreAs}) { + T? _drillDownTo( + Expression expression, { + required bool ignoreParens, + required bool ignoreAs, + }) { var search = expression; // ignore: literal_only_boolean_expressions while (true) { diff --git a/pkg/linter/lib/src/rules/prefer_is_not_empty.dart b/pkg/linter/lib/src/rules/prefer_is_not_empty.dart index d8b86684a416..fb6a73ed7000 100644 --- a/pkg/linter/lib/src/rules/prefer_is_not_empty.dart +++ b/pkg/linter/lib/src/rules/prefer_is_not_empty.dart @@ -14,17 +14,16 @@ const _desc = r'Use `isNotEmpty` for `Iterable`s and `Map`s.'; class PreferIsNotEmpty extends LintRule { PreferIsNotEmpty() - : super( - name: LintNames.prefer_is_not_empty, - description: _desc, - ); + : super(name: LintNames.prefer_is_not_empty, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_is_not_empty; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addPrefixExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_is_not_operator.dart b/pkg/linter/lib/src/rules/prefer_is_not_operator.dart index 8e432c58dbb4..3fe39fb280a8 100644 --- a/pkg/linter/lib/src/rules/prefer_is_not_operator.dart +++ b/pkg/linter/lib/src/rules/prefer_is_not_operator.dart @@ -12,17 +12,16 @@ const _desc = r'Prefer is! operator.'; class PreferIsNotOperator extends LintRule { PreferIsNotOperator() - : super( - name: LintNames.prefer_is_not_operator, - description: _desc, - ); + : super(name: LintNames.prefer_is_not_operator, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_is_not_operator; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addIsExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_iterable_whereType.dart b/pkg/linter/lib/src/rules/prefer_iterable_whereType.dart index 71df2eec8453..1b700a619f51 100644 --- a/pkg/linter/lib/src/rules/prefer_iterable_whereType.dart +++ b/pkg/linter/lib/src/rules/prefer_iterable_whereType.dart @@ -13,17 +13,16 @@ const _desc = r'Prefer to use `whereType` on iterable.'; class PreferIterableWhereType extends LintRule { PreferIterableWhereType() - : super( - name: LintNames.prefer_iterable_whereType, - description: _desc, - ); + : super(name: LintNames.prefer_iterable_whereType, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_iterable_whereType; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_mixin.dart b/pkg/linter/lib/src/rules/prefer_mixin.dart index 4c09e965b337..9c9cae16a1b1 100644 --- a/pkg/linter/lib/src/rules/prefer_mixin.dart +++ b/pkg/linter/lib/src/rules/prefer_mixin.dart @@ -12,18 +12,16 @@ import '../analyzer.dart'; const _desc = r'Prefer using mixins.'; class PreferMixin extends LintRule { - PreferMixin() - : super( - name: LintNames.prefer_mixin, - description: _desc, - ); + PreferMixin() : super(name: LintNames.prefer_mixin, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_mixin; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addWithClause(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_null_aware_method_calls.dart b/pkg/linter/lib/src/rules/prefer_null_aware_method_calls.dart index 64ea7254bf4d..c2ea3b3a9e3f 100644 --- a/pkg/linter/lib/src/rules/prefer_null_aware_method_calls.dart +++ b/pkg/linter/lib/src/rules/prefer_null_aware_method_calls.dart @@ -12,17 +12,16 @@ const _desc = r'Prefer `null`-aware method calls.'; class PreferNullAwareMethodCalls extends LintRule { PreferNullAwareMethodCalls() - : super( - name: LintNames.prefer_null_aware_method_calls, - description: _desc, - ); + : super(name: LintNames.prefer_null_aware_method_calls, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_null_aware_method_calls; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addIfStatement(this, visitor); registry.addConditionalExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/prefer_null_aware_operators.dart b/pkg/linter/lib/src/rules/prefer_null_aware_operators.dart index 83f14252788c..ea5a9faf6b28 100644 --- a/pkg/linter/lib/src/rules/prefer_null_aware_operators.dart +++ b/pkg/linter/lib/src/rules/prefer_null_aware_operators.dart @@ -12,17 +12,16 @@ const _desc = r'Prefer using `null`-aware operators.'; class PreferNullAwareOperators extends LintRule { PreferNullAwareOperators() - : super( - name: LintNames.prefer_null_aware_operators, - description: _desc, - ); + : super(name: LintNames.prefer_null_aware_operators, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_null_aware_operators; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConditionalExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_relative_imports.dart b/pkg/linter/lib/src/rules/prefer_relative_imports.dart index a2cf68e43da3..2a24ac308cb0 100644 --- a/pkg/linter/lib/src/rules/prefer_relative_imports.dart +++ b/pkg/linter/lib/src/rules/prefer_relative_imports.dart @@ -14,21 +14,21 @@ const _desc = r'Prefer relative imports for files in `lib/`.'; class PreferRelativeImports extends LintRule { PreferRelativeImports() - : super( - name: LintNames.prefer_relative_imports, - description: _desc, - ); + : super(name: LintNames.prefer_relative_imports, description: _desc); @override - List get incompatibleRules => - const [LintNames.always_use_package_imports]; + List get incompatibleRules => const [ + LintNames.always_use_package_imports, + ]; @override LintCode get lintCode => LinterLintCode.prefer_relative_imports; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isInLibDir) return; var sourceUri = context.libraryElement2?.uri; diff --git a/pkg/linter/lib/src/rules/prefer_single_quotes.dart b/pkg/linter/lib/src/rules/prefer_single_quotes.dart index 59af218f54e4..cb09786eaaa0 100644 --- a/pkg/linter/lib/src/rules/prefer_single_quotes.dart +++ b/pkg/linter/lib/src/rules/prefer_single_quotes.dart @@ -11,10 +11,7 @@ const _desc = r'Only use double quotes for strings containing single quotes.'; class PreferSingleQuotes extends LintRule { PreferSingleQuotes() - : super( - name: LintNames.prefer_single_quotes, - description: _desc, - ); + : super(name: LintNames.prefer_single_quotes, description: _desc); @override List get incompatibleRules => const [LintNames.prefer_double_quotes]; @@ -24,7 +21,9 @@ class PreferSingleQuotes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = QuoteVisitor(this, useSingle: true); registry.addSimpleStringLiteral(this, visitor); registry.addStringInterpolation(this, visitor); @@ -35,16 +34,14 @@ class QuoteVisitor extends SimpleAstVisitor { final LintRule rule; final bool useSingle; - QuoteVisitor( - this.rule, { - required this.useSingle, - }); + QuoteVisitor(this.rule, {required this.useSingle}); /// Strings interpolations can contain other string nodes. Check like this. bool containsString(StringInterpolation string) { var checkHasString = _IsOrContainsStringVisitor(); - return string.elements - .any((child) => child.accept(checkHasString) ?? false); + return string.elements.any( + (child) => child.accept(checkHasString) ?? false, + ); } /// Strings can be within interpolations (ie, nested). Check like this. @@ -73,10 +70,12 @@ class QuoteVisitor extends SimpleAstVisitor { } // slightly more complicated check there are no single quotes - if (node.elements.any((e) => - e is InterpolationString && - (useSingle && e.value.contains("'") || - !useSingle && e.value.contains('"')))) { + if (node.elements.any( + (e) => + e is InterpolationString && + (useSingle && e.value.contains("'") || + !useSingle && e.value.contains('"')), + )) { return; } diff --git a/pkg/linter/lib/src/rules/prefer_spread_collections.dart b/pkg/linter/lib/src/rules/prefer_spread_collections.dart index af6aba41723a..da4b88eb5c9a 100644 --- a/pkg/linter/lib/src/rules/prefer_spread_collections.dart +++ b/pkg/linter/lib/src/rules/prefer_spread_collections.dart @@ -11,17 +11,16 @@ const _desc = r'Use spread collections when possible.'; class PreferSpreadCollections extends LintRule { PreferSpreadCollections() - : super( - name: LintNames.prefer_spread_collections, - description: _desc, - ); + : super(name: LintNames.prefer_spread_collections, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_spread_collections; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/prefer_typing_uninitialized_variables.dart b/pkg/linter/lib/src/rules/prefer_typing_uninitialized_variables.dart index 238e6d0753fc..83f003e893b4 100644 --- a/pkg/linter/lib/src/rules/prefer_typing_uninitialized_variables.dart +++ b/pkg/linter/lib/src/rules/prefer_typing_uninitialized_variables.dart @@ -12,20 +12,22 @@ const _desc = r'Prefer typing uninitialized variables and fields.'; class PreferTypingUninitializedVariables extends LintRule { PreferTypingUninitializedVariables() - : super( - name: LintNames.prefer_typing_uninitialized_variables, - description: _desc, - ); + : super( + name: LintNames.prefer_typing_uninitialized_variables, + description: _desc, + ); @override List get lintCodes => [ - LinterLintCode.prefer_typing_uninitialized_variables_for_field, - LinterLintCode.prefer_typing_uninitialized_variables_for_local_variable - ]; + LinterLintCode.prefer_typing_uninitialized_variables_for_field, + LinterLintCode.prefer_typing_uninitialized_variables_for_local_variable, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addVariableDeclarationList(this, visitor); } @@ -42,10 +44,11 @@ class _Visitor extends SimpleAstVisitor { for (var v in node.variables) { if (v.initializer == null && !v.isAugmentation) { - var code = node.parent is FieldDeclaration - ? LinterLintCode.prefer_typing_uninitialized_variables_for_field - : LinterLintCode - .prefer_typing_uninitialized_variables_for_local_variable; + var code = + node.parent is FieldDeclaration + ? LinterLintCode.prefer_typing_uninitialized_variables_for_field + : LinterLintCode + .prefer_typing_uninitialized_variables_for_local_variable; rule.reportLint(v, errorCode: code); } } diff --git a/pkg/linter/lib/src/rules/prefer_void_to_null.dart b/pkg/linter/lib/src/rules/prefer_void_to_null.dart index 84fc78733342..a70f4f3c9247 100644 --- a/pkg/linter/lib/src/rules/prefer_void_to_null.dart +++ b/pkg/linter/lib/src/rules/prefer_void_to_null.dart @@ -14,17 +14,16 @@ const _desc = class PreferVoidToNull extends LintRule { PreferVoidToNull() - : super( - name: LintNames.prefer_void_to_null, - description: _desc, - ); + : super(name: LintNames.prefer_void_to_null, description: _desc); @override LintCode get lintCode => LinterLintCode.prefer_void_to_null; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addNamedType(this, visitor); } @@ -45,8 +44,9 @@ class _Visitor extends SimpleAstVisitor { // Make sure we're checking a return type. if (parent.returnType?.offset != node.offset) return false; - var member = context.inheritanceManager - .overriddenMember(parent.declaredFragment?.element); + var member = context.inheritanceManager.overriddenMember( + parent.declaredFragment?.element, + ); if (member == null) return false; var returnType = member.returnType; diff --git a/pkg/linter/lib/src/rules/provide_deprecation_message.dart b/pkg/linter/lib/src/rules/provide_deprecation_message.dart index 1820fc46eb8f..cf5aa241e4ee 100644 --- a/pkg/linter/lib/src/rules/provide_deprecation_message.dart +++ b/pkg/linter/lib/src/rules/provide_deprecation_message.dart @@ -11,17 +11,16 @@ const _desc = r'Provide a deprecation message, via `@Deprecated("message")`.'; class ProvideDeprecationMessage extends LintRule { ProvideDeprecationMessage() - : super( - name: LintNames.provide_deprecation_message, - description: _desc, - ); + : super(name: LintNames.provide_deprecation_message, description: _desc); @override LintCode get lintCode => LinterLintCode.provide_deprecation_message; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAnnotation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/pub/depend_on_referenced_packages.dart b/pkg/linter/lib/src/rules/pub/depend_on_referenced_packages.dart index 00080c19f81b..f14b958e80a7 100644 --- a/pkg/linter/lib/src/rules/pub/depend_on_referenced_packages.dart +++ b/pkg/linter/lib/src/rules/pub/depend_on_referenced_packages.dart @@ -12,17 +12,16 @@ const _desc = r'Depend on referenced packages.'; class DependOnReferencedPackages extends LintRule { DependOnReferencedPackages() - : super( - name: LintNames.depend_on_referenced_packages, - description: _desc, - ); + : super(name: LintNames.depend_on_referenced_packages, description: _desc); @override LintCode get lintCode => LinterLintCode.depend_on_referenced_packages; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { // Only lint if we have a pubspec. var package = context.package; if (package is! PubPackage) return; diff --git a/pkg/linter/lib/src/rules/pub/package_names.dart b/pkg/linter/lib/src/rules/pub/package_names.dart index 672af6901fae..e64d9521eb75 100644 --- a/pkg/linter/lib/src/rules/pub/package_names.dart +++ b/pkg/linter/lib/src/rules/pub/package_names.dart @@ -8,11 +8,7 @@ import '../../utils.dart'; const _desc = r'Use `lowercase_with_underscores` for package names.'; class PackageNames extends LintRule { - PackageNames() - : super( - name: LintNames.package_names, - description: _desc, - ); + PackageNames() : super(name: LintNames.package_names, description: _desc); @override LintCode get lintCode => LinterLintCode.package_names; diff --git a/pkg/linter/lib/src/rules/pub/secure_pubspec_urls.dart b/pkg/linter/lib/src/rules/pub/secure_pubspec_urls.dart index 795099d5079f..ba796d365f8b 100644 --- a/pkg/linter/lib/src/rules/pub/secure_pubspec_urls.dart +++ b/pkg/linter/lib/src/rules/pub/secure_pubspec_urls.dart @@ -10,10 +10,7 @@ const _desc = r'Use secure urls in `pubspec.yaml`.'; class SecurePubspecUrls extends LintRule { SecurePubspecUrls() - : super( - name: LintNames.secure_pubspec_urls, - description: _desc, - ); + : super(name: LintNames.secure_pubspec_urls, description: _desc); @override LintCode get lintCode => LinterLintCode.secure_pubspec_urls; diff --git a/pkg/linter/lib/src/rules/pub/sort_pub_dependencies.dart b/pkg/linter/lib/src/rules/pub/sort_pub_dependencies.dart index 8d68f2f45f45..b9bdfff95402 100644 --- a/pkg/linter/lib/src/rules/pub/sort_pub_dependencies.dart +++ b/pkg/linter/lib/src/rules/pub/sort_pub_dependencies.dart @@ -11,10 +11,7 @@ const _desc = r'Sort pub dependencies alphabetically.'; class SortPubDependencies extends LintRule { SortPubDependencies() - : super( - name: LintNames.sort_pub_dependencies, - description: _desc, - ); + : super(name: LintNames.sort_pub_dependencies, description: _desc); @override LintCode get lintCode => LinterLintCode.sort_pub_dependencies; @@ -51,8 +48,9 @@ class Visitor extends PubspecVisitor { return lc1.compareTo(lc2); } - var depsByLocation = dependencies.toList() - ..sort((d1, d2) => compare(d1.name?.span.start, d2.name?.span.start)); + var depsByLocation = + dependencies.toList() + ..sort((d1, d2) => compare(d1.name?.span.start, d2.name?.span.start)); var previousName = ''; for (var dep in depsByLocation) { var name = dep.name; diff --git a/pkg/linter/lib/src/rules/public_member_api_docs.dart b/pkg/linter/lib/src/rules/public_member_api_docs.dart index decde2a9bdda..b2771c39fe27 100644 --- a/pkg/linter/lib/src/rules/public_member_api_docs.dart +++ b/pkg/linter/lib/src/rules/public_member_api_docs.dart @@ -18,17 +18,16 @@ const _desc = r'Document all public members.'; class PublicMemberApiDocs extends LintRule { PublicMemberApiDocs() - : super( - name: LintNames.public_member_api_docs, - description: _desc, - ); + : super(name: LintNames.public_member_api_docs, description: _desc); @override LintCode get lintCode => LinterLintCode.public_member_api_docs; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var package = context.package; if (package != null && !package.canHavePublicApi) { return; @@ -111,8 +110,9 @@ class _Visitor extends SimpleAstVisitor { /// Whether [node] overrides some other member. bool isOverridingMember(Declaration node) => - context.inheritanceManager - .overriddenMember(node.declaredFragment?.element) != + context.inheritanceManager.overriddenMember( + node.declaredFragment?.element, + ) != null; @override diff --git a/pkg/linter/lib/src/rules/recursive_getters.dart b/pkg/linter/lib/src/rules/recursive_getters.dart index d2c0a3e79df2..55cbd6f44350 100644 --- a/pkg/linter/lib/src/rules/recursive_getters.dart +++ b/pkg/linter/lib/src/rules/recursive_getters.dart @@ -12,17 +12,16 @@ const _desc = r'Property getter recursively returns itself.'; class RecursiveGetters extends LintRule { RecursiveGetters() - : super( - name: LintNames.recursive_getters, - description: _desc, - ); + : super(name: LintNames.recursive_getters, description: _desc); @override LintCode get lintCode => LinterLintCode.recursive_getters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionDeclaration(this, visitor); registry.addMethodDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/require_trailing_commas.dart b/pkg/linter/lib/src/rules/require_trailing_commas.dart index 4c1ea0bc2293..729185c2bc51 100644 --- a/pkg/linter/lib/src/rules/require_trailing_commas.dart +++ b/pkg/linter/lib/src/rules/require_trailing_commas.dart @@ -13,10 +13,7 @@ const _desc = class RequireTrailingCommas extends LintRule { RequireTrailingCommas() - : super( - name: LintNames.require_trailing_commas, - description: _desc, - ); + : super(name: LintNames.require_trailing_commas, description: _desc); @override LintCode get lintCode => LinterLintCode.require_trailing_commas; @@ -163,8 +160,10 @@ class _Visitor extends SimpleAstVisitor { // This case arises a lot in asserts. if (lastNode is FunctionExpressionInvocation && lastNode.function is FunctionExpression && - _isSameLine(lastNode.argumentList.leftParenthesis, - lastNode.argumentList.rightParenthesis)) { + _isSameLine( + lastNode.argumentList.leftParenthesis, + lastNode.argumentList.rightParenthesis, + )) { return true; } diff --git a/pkg/linter/lib/src/rules/sized_box_for_whitespace.dart b/pkg/linter/lib/src/rules/sized_box_for_whitespace.dart index 15b4241b0980..fcf295114dde 100644 --- a/pkg/linter/lib/src/rules/sized_box_for_whitespace.dart +++ b/pkg/linter/lib/src/rules/sized_box_for_whitespace.dart @@ -12,17 +12,16 @@ const _desc = r'`SizedBox` for whitespace.'; class SizedBoxForWhitespace extends LintRule { SizedBoxForWhitespace() - : super( - name: LintNames.sized_box_for_whitespace, - description: _desc, - ); + : super(name: LintNames.sized_box_for_whitespace, description: _desc); @override LintCode get lintCode => LinterLintCode.sized_box_for_whitespace; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/sized_box_shrink_expand.dart b/pkg/linter/lib/src/rules/sized_box_shrink_expand.dart index bae0eaf08e48..8623af320dab 100644 --- a/pkg/linter/lib/src/rules/sized_box_shrink_expand.dart +++ b/pkg/linter/lib/src/rules/sized_box_shrink_expand.dart @@ -10,17 +10,19 @@ import '../util/flutter_utils.dart'; class SizedBoxShrinkExpand extends LintRule { SizedBoxShrinkExpand() - : super( - name: LintNames.sized_box_shrink_expand, - description: 'Use SizedBox shrink and expand named constructors.', - ); + : super( + name: LintNames.sized_box_shrink_expand, + description: 'Use SizedBox shrink and expand named constructors.', + ); @override LintCode get lintCode => LinterLintCode.sized_box_shrink_expand; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); @@ -56,7 +58,8 @@ class _Visitor extends SimpleAstVisitor { /// Determine the value of the arguments specified in the [argumentList], /// and return `null` if there are unsupported arguments. static ({double? height, double? width})? _analyzeArguments( - ArgumentList argumentList) { + ArgumentList argumentList, + ) { double? height; double? width; diff --git a/pkg/linter/lib/src/rules/slash_for_doc_comments.dart b/pkg/linter/lib/src/rules/slash_for_doc_comments.dart index 367341ff3c6b..fda5c7e361f0 100644 --- a/pkg/linter/lib/src/rules/slash_for_doc_comments.dart +++ b/pkg/linter/lib/src/rules/slash_for_doc_comments.dart @@ -20,10 +20,7 @@ bool isJavaStyle(Comment comment) { class SlashForDocComments extends LintRule { SlashForDocComments() - : super( - name: LintNames.slash_for_doc_comments, - description: _desc, - ); + : super(name: LintNames.slash_for_doc_comments, description: _desc); @override bool get canUseParsedResult => true; @@ -33,7 +30,9 @@ class SlashForDocComments extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addClassTypeAlias(this, visitor); diff --git a/pkg/linter/lib/src/rules/sort_child_properties_last.dart b/pkg/linter/lib/src/rules/sort_child_properties_last.dart index 77e2496afda8..7071a09c4bd9 100644 --- a/pkg/linter/lib/src/rules/sort_child_properties_last.dart +++ b/pkg/linter/lib/src/rules/sort_child_properties_last.dart @@ -12,17 +12,16 @@ const _desc = r'Sort child properties last in widget instance creations.'; class SortChildPropertiesLast extends LintRule { SortChildPropertiesLast() - : super( - name: LintNames.sort_child_properties_last, - description: _desc, - ); + : super(name: LintNames.sort_child_properties_last, description: _desc); @override LintCode get lintCode => LinterLintCode.sort_child_properties_last; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } @@ -46,14 +45,17 @@ class _Visitor extends SimpleAstVisitor { return; } - var onlyClosuresAfterChild = arguments.reversed - .takeWhile((argument) => !isChildArg(argument)) - .toList() - .reversed - .where((element) => - element is NamedExpression && - element.expression is! FunctionExpression) - .isEmpty; + var onlyClosuresAfterChild = + arguments.reversed + .takeWhile((argument) => !isChildArg(argument)) + .toList() + .reversed + .where( + (element) => + element is NamedExpression && + element.expression is! FunctionExpression, + ) + .isEmpty; if (!onlyClosuresAfterChild) { var argument = arguments.firstWhere(isChildArg); var name = (argument as NamedExpression).name.label.name; diff --git a/pkg/linter/lib/src/rules/sort_constructors_first.dart b/pkg/linter/lib/src/rules/sort_constructors_first.dart index a23adbbc6b1e..9d359d9d6ae4 100644 --- a/pkg/linter/lib/src/rules/sort_constructors_first.dart +++ b/pkg/linter/lib/src/rules/sort_constructors_first.dart @@ -11,17 +11,16 @@ const _desc = r'Sort constructor declarations before other members.'; class SortConstructorsFirst extends LintRule { SortConstructorsFirst() - : super( - name: LintNames.sort_constructors_first, - description: _desc, - ); + : super(name: LintNames.sort_constructors_first, description: _desc); @override LintCode get lintCode => LinterLintCode.sort_constructors_first; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addEnumDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/sort_unnamed_constructors_first.dart b/pkg/linter/lib/src/rules/sort_unnamed_constructors_first.dart index d41f561ab0cf..e7b0271157b1 100644 --- a/pkg/linter/lib/src/rules/sort_unnamed_constructors_first.dart +++ b/pkg/linter/lib/src/rules/sort_unnamed_constructors_first.dart @@ -11,17 +11,19 @@ const _desc = r'Sort unnamed constructor declarations first.'; class SortUnnamedConstructorsFirst extends LintRule { SortUnnamedConstructorsFirst() - : super( - name: LintNames.sort_unnamed_constructors_first, - description: _desc, - ); + : super( + name: LintNames.sort_unnamed_constructors_first, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.sort_unnamed_constructors_first; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addEnumDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/specify_nonobvious_local_variable_types.dart b/pkg/linter/lib/src/rules/specify_nonobvious_local_variable_types.dart index 62411d3be4e8..24af15a0e807 100644 --- a/pkg/linter/lib/src/rules/specify_nonobvious_local_variable_types.dart +++ b/pkg/linter/lib/src/rules/specify_nonobvious_local_variable_types.dart @@ -13,15 +13,16 @@ const _desc = r'Specify non-obvious type annotations for local variables.'; class SpecifyNonObviousLocalVariableTypes extends LintRule { SpecifyNonObviousLocalVariableTypes() - : super( - name: LintNames.specify_nonobvious_local_variable_types, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.specify_nonobvious_local_variable_types, + description: _desc, + state: const State.experimental(), + ); @override - List get incompatibleRules => - const [LintNames.omit_local_variable_types]; + List get incompatibleRules => const [ + LintNames.omit_local_variable_types, + ]; @override LintCode get lintCode => @@ -29,7 +30,9 @@ class SpecifyNonObviousLocalVariableTypes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addForStatement(this, visitor); registry.addPatternVariableDeclarationStatement(this, visitor); @@ -82,7 +85,8 @@ class _Visitor extends SimpleAstVisitor { @override void visitPatternVariableDeclarationStatement( - PatternVariableDeclarationStatement node) { + PatternVariableDeclarationStatement node, + ) { if (node.declaration.expression.hasObviousType) return; _PatternVisitor(rule).visitDartPattern(node.declaration.pattern); } diff --git a/pkg/linter/lib/src/rules/specify_nonobvious_property_types.dart b/pkg/linter/lib/src/rules/specify_nonobvious_property_types.dart index c257c79fa24a..7ec78e8029b9 100644 --- a/pkg/linter/lib/src/rules/specify_nonobvious_property_types.dart +++ b/pkg/linter/lib/src/rules/specify_nonobvious_property_types.dart @@ -15,11 +15,11 @@ const _desc = class SpecifyNonObviousPropertyTypes extends LintRule { SpecifyNonObviousPropertyTypes() - : super( - name: LintNames.specify_nonobvious_property_types, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.specify_nonobvious_property_types, + description: _desc, + state: const State.experimental(), + ); @override List get incompatibleRules => const []; @@ -29,7 +29,9 @@ class SpecifyNonObviousPropertyTypes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addTopLevelVariableDeclaration(this, visitor); @@ -43,15 +45,19 @@ class _Visitor extends SimpleAstVisitor { @override void visitFieldDeclaration(FieldDeclaration node) => - _visitVariableDeclarationList(node.fields, - isInstanceVariable: !node.isStatic); + _visitVariableDeclarationList( + node.fields, + isInstanceVariable: !node.isStatic, + ); @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) => _visitVariableDeclarationList(node.variables, isInstanceVariable: false); - void _visitVariableDeclarationList(VariableDeclarationList node, - {required bool isInstanceVariable}) { + void _visitVariableDeclarationList( + VariableDeclarationList node, { + required bool isInstanceVariable, + }) { var staticType = node.type?.type; if (staticType != null && !staticType.isDartCoreNull) { return; diff --git a/pkg/linter/lib/src/rules/strict_top_level_inference.dart b/pkg/linter/lib/src/rules/strict_top_level_inference.dart index fd1e3bce051c..4c6ddb343543 100644 --- a/pkg/linter/lib/src/rules/strict_top_level_inference.dart +++ b/pkg/linter/lib/src/rules/strict_top_level_inference.dart @@ -17,21 +17,20 @@ const _desc = r'Specify type annotations.'; class StrictTopLevelInference extends LintRule { StrictTopLevelInference() - : super( - name: LintNames.strict_top_level_inference, - description: _desc, - ); + : super(name: LintNames.strict_top_level_inference, description: _desc); @override List get lintCodes => [ - LinterLintCode.strict_top_level_inference_add_type, - LinterLintCode.strict_top_level_inference_replace_keyword, - LinterLintCode.strict_top_level_inference_split_to_types, - ]; + LinterLintCode.strict_top_level_inference_add_type, + LinterLintCode.strict_top_level_inference_replace_keyword, + LinterLintCode.strict_top_level_inference_split_to_types, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConstructorDeclaration(this, visitor); registry.addFunctionDeclaration(this, visitor); @@ -97,8 +96,9 @@ class _Visitor extends SimpleAstVisitor { if (node.variables.length == 1) { var variable = node.variables.single; - var overriddenMember = context.inheritanceManager - .overriddenMember(variable.declaredFragment?.element); + var overriddenMember = context.inheritanceManager.overriddenMember( + variable.declaredFragment?.element, + ); if (overriddenMember == null) { _report(variable.name, keyword: node.keyword); } @@ -106,8 +106,9 @@ class _Visitor extends SimpleAstVisitor { // Handle the multiple-variable case separately so that we can instead // report `LinterLintCode.strict_top_level_inference_split_to_types`. for (var variable in variablesMissingAnInitializer) { - var overriddenMember = context.inheritanceManager - .overriddenMember(variable.declaredFragment?.element); + var overriddenMember = context.inheritanceManager.overriddenMember( + variable.declaredFragment?.element, + ); if (overriddenMember == null) { rule.reportLintForToken( variable.name, @@ -118,8 +119,10 @@ class _Visitor extends SimpleAstVisitor { } } - void _checkFormalParameters(List parameters, - {ExecutableElement2? overriddenMember}) { + void _checkFormalParameters( + List parameters, { + ExecutableElement2? overriddenMember, + }) { for (var i = 0; i < parameters.length; i++) { var parameter = parameters[i]; if (parameter is DefaultFormalParameter) { @@ -178,27 +181,33 @@ class _Visitor extends SimpleAstVisitor { } var container = element.enclosingFragment!.element; - var noOverride = node.isStatic || + var noOverride = + node.isStatic || container is ExtensionElement2 || container is ExtensionTypeElement2; if (noOverride) { if (node.returnType == null) { - rule.reportLintForToken(node.name, - errorCode: LinterLintCode.strict_top_level_inference_add_type); + rule.reportLintForToken( + node.name, + errorCode: LinterLintCode.strict_top_level_inference_add_type, + ); } if (node.parameters case var parameters?) { _checkFormalParameters(parameters.parameters); } } else { - var overriddenMember = context.inheritanceManager - .overriddenMember(node.declaredFragment?.element); + var overriddenMember = context.inheritanceManager.overriddenMember( + node.declaredFragment?.element, + ); if (overriddenMember == null && node.returnType == null) { _report(node.name); } if (node.parameters case var parameters?) { - _checkFormalParameters(parameters.parameters, - overriddenMember: overriddenMember); + _checkFormalParameters( + parameters.parameters, + overriddenMember: overriddenMember, + ); } } } @@ -222,8 +231,9 @@ class _Visitor extends SimpleAstVisitor { if (node.isStatic) return false; if (container is ExtensionElement2) return false; if (container is ExtensionTypeElement2) return false; - var overriddenMember = context.inheritanceManager - .overriddenMember(node.declaredFragment?.element); + var overriddenMember = context.inheritanceManager.overriddenMember( + node.declaredFragment?.element, + ); return overriddenMember != null; } diff --git a/pkg/linter/lib/src/rules/super_goes_last.dart b/pkg/linter/lib/src/rules/super_goes_last.dart index 22417e0d5e14..6160d2de3dec 100644 --- a/pkg/linter/lib/src/rules/super_goes_last.dart +++ b/pkg/linter/lib/src/rules/super_goes_last.dart @@ -9,11 +9,11 @@ const _desc = class SuperGoesLast extends LintRule { SuperGoesLast() - : super( - name: LintNames.super_goes_last, - description: _desc, - state: State.removed(since: dart3), - ); + : super( + name: LintNames.super_goes_last, + description: _desc, + state: State.removed(since: dart3), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/test_types_in_equals.dart b/pkg/linter/lib/src/rules/test_types_in_equals.dart index 92960b5db7eb..a9f00fb8bfa6 100644 --- a/pkg/linter/lib/src/rules/test_types_in_equals.dart +++ b/pkg/linter/lib/src/rules/test_types_in_equals.dart @@ -11,17 +11,16 @@ const _desc = r'Test type of argument in `operator ==(Object other)`.'; class TestTypesInEquals extends LintRule { TestTypesInEquals() - : super( - name: LintNames.test_types_in_equals, - description: _desc, - ); + : super(name: LintNames.test_types_in_equals, description: _desc); @override LintCode get lintCode => LinterLintCode.test_types_in_equals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAsExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/throw_in_finally.dart b/pkg/linter/lib/src/rules/throw_in_finally.dart index 857f80a85780..d271a6e85ad7 100644 --- a/pkg/linter/lib/src/rules/throw_in_finally.dart +++ b/pkg/linter/lib/src/rules/throw_in_finally.dart @@ -12,17 +12,16 @@ const _desc = r'Avoid `throw` in `finally` block.'; class ThrowInFinally extends LintRule { ThrowInFinally() - : super( - name: LintNames.throw_in_finally, - description: _desc, - ); + : super(name: LintNames.throw_in_finally, description: _desc); @override LintCode get lintCode => LinterLintCode.throw_in_finally; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addThrowExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/tighten_type_of_initializing_formals.dart b/pkg/linter/lib/src/rules/tighten_type_of_initializing_formals.dart index 3cf132060d95..9a1393f2de15 100644 --- a/pkg/linter/lib/src/rules/tighten_type_of_initializing_formals.dart +++ b/pkg/linter/lib/src/rules/tighten_type_of_initializing_formals.dart @@ -13,17 +13,19 @@ const _desc = r'Tighten type of initializing formal.'; class TightenTypeOfInitializingFormals extends LintRule { TightenTypeOfInitializingFormals() - : super( - name: LintNames.tighten_type_of_initializing_formals, - description: _desc, - ); + : super( + name: LintNames.tighten_type_of_initializing_formals, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.tighten_type_of_initializing_formals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConstructorDeclaration(this, visitor); } @@ -70,8 +72,11 @@ class _Visitor extends SimpleAstVisitor { void _check(Element2? element, ConstructorDeclaration node) { if (element is FieldFormalParameterElement2 || element is SuperFormalParameterElement2) { - rule.reportLint(node.parameters.parameters - .firstWhere((p) => p.declaredFragment?.element == element)); + rule.reportLint( + node.parameters.parameters.firstWhere( + (p) => p.declaredFragment?.element == element, + ), + ); } } } diff --git a/pkg/linter/lib/src/rules/type_annotate_public_apis.dart b/pkg/linter/lib/src/rules/type_annotate_public_apis.dart index 2cf1c3e45fb0..a8e48a434e8d 100644 --- a/pkg/linter/lib/src/rules/type_annotate_public_apis.dart +++ b/pkg/linter/lib/src/rules/type_annotate_public_apis.dart @@ -14,17 +14,16 @@ const _desc = r'Type annotate public APIs.'; class TypeAnnotatePublicApis extends LintRule { TypeAnnotatePublicApis() - : super( - name: LintNames.type_annotate_public_apis, - description: _desc, - ); + : super(name: LintNames.type_annotate_public_apis, description: _desc); @override LintCode get lintCode => LinterLintCode.type_annotate_public_apis; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addFunctionDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/type_init_formals.dart b/pkg/linter/lib/src/rules/type_init_formals.dart index 7ae47d08a3b2..4a8c901400e1 100644 --- a/pkg/linter/lib/src/rules/type_init_formals.dart +++ b/pkg/linter/lib/src/rules/type_init_formals.dart @@ -12,17 +12,16 @@ const _desc = "Don't type annotate initializing formals."; class TypeInitFormals extends LintRule { TypeInitFormals() - : super( - name: LintNames.type_init_formals, - description: _desc, - ); + : super(name: LintNames.type_init_formals, description: _desc); @override LintCode get lintCode => LinterLintCode.type_init_formals; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldFormalParameter(this, visitor); registry.addSuperFormalParameter(this, visitor); diff --git a/pkg/linter/lib/src/rules/type_literal_in_constant_pattern.dart b/pkg/linter/lib/src/rules/type_literal_in_constant_pattern.dart index c3b55be362fa..3c1d724953cf 100644 --- a/pkg/linter/lib/src/rules/type_literal_in_constant_pattern.dart +++ b/pkg/linter/lib/src/rules/type_literal_in_constant_pattern.dart @@ -11,17 +11,19 @@ const _desc = r"Don't use constant patterns with type literals."; class TypeLiteralInConstantPattern extends LintRule { TypeLiteralInConstantPattern() - : super( - name: LintNames.type_literal_in_constant_pattern, - description: _desc, - ); + : super( + name: LintNames.type_literal_in_constant_pattern, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.type_literal_in_constant_pattern; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConstantPattern(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unawaited_futures.dart b/pkg/linter/lib/src/rules/unawaited_futures.dart index 62445cb609eb..9e1fc779c513 100644 --- a/pkg/linter/lib/src/rules/unawaited_futures.dart +++ b/pkg/linter/lib/src/rules/unawaited_futures.dart @@ -9,22 +9,22 @@ import 'package:analyzer/dart/element/element2.dart'; import '../analyzer.dart'; import '../extensions.dart'; -const _desc = r'`Future` results in `async` function bodies must be ' +const _desc = + r'`Future` results in `async` function bodies must be ' '`await`ed or marked `unawaited` using `dart:async`.'; class UnawaitedFutures extends LintRule { UnawaitedFutures() - : super( - name: LintNames.unawaited_futures, - description: _desc, - ); + : super(name: LintNames.unawaited_futures, description: _desc); @override LintCode get lintCode => LinterLintCode.unawaited_futures; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addExpressionStatement(this, visitor); registry.addCascadeExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/unintended_html_in_doc_comment.dart b/pkg/linter/lib/src/rules/unintended_html_in_doc_comment.dart index 6def2fb8392c..dacb95119487 100644 --- a/pkg/linter/lib/src/rules/unintended_html_in_doc_comment.dart +++ b/pkg/linter/lib/src/rules/unintended_html_in_doc_comment.dart @@ -8,7 +8,8 @@ import 'package:collection/collection.dart'; import '../analyzer.dart'; -const _desc = r'Use of angle brackets in a doc comment is treated as HTML by ' +const _desc = + r'Use of angle brackets in a doc comment is treated as HTML by ' 'Markdown.'; /// Valid HTML tags that should not be linted. @@ -118,17 +119,16 @@ const _validHtmlTags = [ class UnintendedHtmlInDocComment extends LintRule { UnintendedHtmlInDocComment() - : super( - name: LintNames.unintended_html_in_doc_comment, - description: _desc, - ); + : super(name: LintNames.unintended_html_in_doc_comment, description: _desc); @override LintCode get lintCode => LinterLintCode.unintended_html_in_doc_comment; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addComment(this, visitor); } @@ -152,52 +152,44 @@ class _Visitor extends SimpleAstVisitor { /// non-HTML sections in the same RegExp ensures that the HTML tag match /// will not be matched against the non-HTML content. static final _markdownTokenPattern = RegExp( - // Escaped Markdown character, including `\<` and `\\`. - r'\\.' - - // Or a Markdown code span, from "`"*N to "`"*N. - // Also matches an unterminated start tag to avoid "```a``" - // being matched as "``a``". - // The ```-sequence is atomic. - r'|(?`+)(?:[^]+?\k)?' - - // Or autolink, starting with scheme + `:`, followed by non-whitespace/ - // control characters until a closing `>`. - r'|<[a-z][a-z\d\-+.]+:[^\x00-\x20\x7f<>]*>' - - // Or HTML comments. - r'|)' - - // Or HTML declarations, like ``. - r'|' - - // Or HTML processing instructions. - r'|<\?[^]*?\?>' - - // Or HTML CDATA sections sections. - r'|<\[CDATA[^]*\]>' - - // Or plain `[...]` which DartDoc interprets as Dart source links, - // and which can contain type parameters like `... [List] ...`. - // Here recognized as `[...]` with no `]` inside, not preceded by `]` - // or followed by `(` or `[`. - r'|(?`, ``, ``, `` - // and `. - r'|<(?/?)(?:' - '${_validHtmlTags.join('|')}' - r')' - r'(?:/(?=\k)>|>|[\x20\r\n\t][^]*?>)' - - // Or any of the following matches which are considered invalid tags. - // If the "nh" capture group is participating, one of these matched. - r'|(?)(?:' - - // Any other `` sequence. - r'' - r')', caseSensitive: false); + // Escaped Markdown character, including `\<` and `\\`. + r'\\.' + // Or a Markdown code span, from "`"*N to "`"*N. + // Also matches an unterminated start tag to avoid "```a``" + // being matched as "``a``". + // The ```-sequence is atomic. + r'|(?`+)(?:[^]+?\k)?' + // Or autolink, starting with scheme + `:`, followed by non-whitespace/ + // control characters until a closing `>`. + r'|<[a-z][a-z\d\-+.]+:[^\x00-\x20\x7f<>]*>' + // Or HTML comments. + r'|)' + // Or HTML declarations, like ``. + r'|' + // Or HTML processing instructions. + r'|<\?[^]*?\?>' + // Or HTML CDATA sections sections. + r'|<\[CDATA[^]*\]>' + // Or plain `[...]` which DartDoc interprets as Dart source links, + // and which can contain type parameters like `... [List] ...`. + // Here recognized as `[...]` with no `]` inside, not preceded by `]` + // or followed by `(` or `[`. + r'|(?`, ``, ``, `` + // and `. + r'|<(?/?)(?:' + '${_validHtmlTags.join('|')}' + r')' + r'(?:/(?=\k)>|>|[\x20\r\n\t][^]*?>)' + // Or any of the following matches which are considered invalid tags. + // If the "nh" capture group is participating, one of these matched. + r'|(?)(?:' + // Any other `` sequence. + r'' + r')', + caseSensitive: false, + ); final LintRule rule; @@ -212,9 +204,11 @@ class _Visitor extends SimpleAstVisitor { // Make sure that the current doc comment line isn't contained in a code // block. var offsetAfterSlash = token.offset + 3; - var inCodeBlock = codeBlockLines.any((codeBlockLine) => - codeBlockLine.offset <= offsetAfterSlash && - offsetAfterSlash <= codeBlockLine.offset + codeBlockLine.length); + var inCodeBlock = codeBlockLines.any( + (codeBlockLine) => + codeBlockLine.offset <= offsetAfterSlash && + offsetAfterSlash <= codeBlockLine.offset + codeBlockLine.length, + ); if (inCodeBlock) continue; var tags = _findUnintendedHtmlTags(token.lexeme); diff --git a/pkg/linter/lib/src/rules/unnecessary_async.dart b/pkg/linter/lib/src/rules/unnecessary_async.dart index 30be4af58ece..a0210966dbcc 100644 --- a/pkg/linter/lib/src/rules/unnecessary_async.dart +++ b/pkg/linter/lib/src/rules/unnecessary_async.dart @@ -15,11 +15,11 @@ const _desc = r'No await no async.'; class UnnecessaryAsync extends LintRule { UnnecessaryAsync() - : super( - name: LintNames.unnecessary_async, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.unnecessary_async, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.unnecessary_async; @@ -116,20 +116,14 @@ class _Visitor extends SimpleAstVisitor { var bodyContext = node.body.bodyContext; - _checkBody( - body: node.body, - returnType: bodyContext?.imposedType, - ); + _checkBody(body: node.body, returnType: bodyContext?.imposedType); } @override void visitMethodDeclaration(covariant MethodDeclarationImpl node) { var element = node.declaredFragment!.element; - _checkBody( - body: node.body, - returnType: element.returnType, - ); + _checkBody(body: node.body, returnType: element.returnType); } void _checkBody({ diff --git a/pkg/linter/lib/src/rules/unnecessary_await_in_return.dart b/pkg/linter/lib/src/rules/unnecessary_await_in_return.dart index a8a7430084ad..0af790174931 100644 --- a/pkg/linter/lib/src/rules/unnecessary_await_in_return.dart +++ b/pkg/linter/lib/src/rules/unnecessary_await_in_return.dart @@ -12,17 +12,16 @@ const _desc = r'Unnecessary `await` keyword in return.'; class UnnecessaryAwaitInReturn extends LintRule { UnnecessaryAwaitInReturn() - : super( - name: LintNames.unnecessary_await_in_return, - description: _desc, - ); + : super(name: LintNames.unnecessary_await_in_return, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_await_in_return; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeSystem); registry.addExpressionFunctionBody(this, visitor); registry.addReturnStatement(this, visitor); @@ -56,10 +55,12 @@ class _Visitor extends SimpleAstVisitor { return; } - var parent = node.thisOrAncestorMatching((e) => - e is FunctionExpression || - e is MethodDeclaration || - e is Block && e.parent is TryStatement); + var parent = node.thisOrAncestorMatching( + (e) => + e is FunctionExpression || + e is MethodDeclaration || + e is Block && e.parent is TryStatement, + ); if (parent == null) return; DartType? returnType; diff --git a/pkg/linter/lib/src/rules/unnecessary_brace_in_string_interps.dart b/pkg/linter/lib/src/rules/unnecessary_brace_in_string_interps.dart index 6597387d7e0a..53fad13aff30 100644 --- a/pkg/linter/lib/src/rules/unnecessary_brace_in_string_interps.dart +++ b/pkg/linter/lib/src/rules/unnecessary_brace_in_string_interps.dart @@ -17,17 +17,19 @@ bool isIdentifierPart(Token? token) => class UnnecessaryBraceInStringInterps extends LintRule { UnnecessaryBraceInStringInterps() - : super( - name: LintNames.unnecessary_brace_in_string_interps, - description: _desc, - ); + : super( + name: LintNames.unnecessary_brace_in_string_interps, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.unnecessary_brace_in_string_interps; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addStringInterpolation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_breaks.dart b/pkg/linter/lib/src/rules/unnecessary_breaks.dart index 4f6ab6c69f24..d25713df9461 100644 --- a/pkg/linter/lib/src/rules/unnecessary_breaks.dart +++ b/pkg/linter/lib/src/rules/unnecessary_breaks.dart @@ -13,17 +13,16 @@ const _desc = r"Don't use explicit `break`s when a break is implied."; class UnnecessaryBreaks extends LintRule { UnnecessaryBreaks() - : super( - name: LintNames.unnecessary_breaks, - description: _desc, - ); + : super(name: LintNames.unnecessary_breaks, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_breaks; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isEnabled(Feature.patterns)) return; var visitor = _Visitor(this); diff --git a/pkg/linter/lib/src/rules/unnecessary_const.dart b/pkg/linter/lib/src/rules/unnecessary_const.dart index 3163ba7dbafb..e2c71fb37a4a 100644 --- a/pkg/linter/lib/src/rules/unnecessary_const.dart +++ b/pkg/linter/lib/src/rules/unnecessary_const.dart @@ -12,10 +12,7 @@ const _desc = r'Avoid `const` keyword.'; class UnnecessaryConst extends LintRule { UnnecessaryConst() - : super( - name: LintNames.unnecessary_const, - description: _desc, - ); + : super(name: LintNames.unnecessary_const, description: _desc); @override bool get canUseParsedResult => true; @@ -25,7 +22,9 @@ class UnnecessaryConst extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); registry.addListLiteral(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_constructor_name.dart b/pkg/linter/lib/src/rules/unnecessary_constructor_name.dart index 5db9e9242330..003d89d1036f 100644 --- a/pkg/linter/lib/src/rules/unnecessary_constructor_name.dart +++ b/pkg/linter/lib/src/rules/unnecessary_constructor_name.dart @@ -12,17 +12,16 @@ const _desc = r'Unnecessary `.new` constructor name.'; class UnnecessaryConstructorName extends LintRule { UnnecessaryConstructorName() - : super( - name: LintNames.unnecessary_constructor_name, - description: _desc, - ); + : super(name: LintNames.unnecessary_constructor_name, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_constructor_name; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addConstructorDeclaration(this, visitor); registry.addRepresentationConstructorName(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_final.dart b/pkg/linter/lib/src/rules/unnecessary_final.dart index 379b076d2448..2c091a97d26c 100644 --- a/pkg/linter/lib/src/rules/unnecessary_final.dart +++ b/pkg/linter/lib/src/rules/unnecessary_final.dart @@ -13,27 +13,26 @@ const _desc = "Don't use `final` for local variables."; class UnnecessaryFinal extends LintRule { UnnecessaryFinal() - : super( - name: LintNames.unnecessary_final, - description: _desc, - ); + : super(name: LintNames.unnecessary_final, description: _desc); @override List get incompatibleRules => const [ - LintNames.prefer_final_locals, - LintNames.prefer_final_parameters, - LintNames.prefer_final_in_for_each - ]; + LintNames.prefer_final_locals, + LintNames.prefer_final_parameters, + LintNames.prefer_final_in_for_each, + ]; @override List get lintCodes => [ - LinterLintCode.unnecessary_final_with_type, - LinterLintCode.unnecessary_final_without_type - ]; + LinterLintCode.unnecessary_final_with_type, + LinterLintCode.unnecessary_final_without_type, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry ..addFormalParameterList(this, visitor) @@ -48,9 +47,10 @@ class _Visitor extends SimpleAstVisitor { _Visitor(this.rule); - LintCode getErrorCode(Object? type) => type == null - ? LinterLintCode.unnecessary_final_without_type - : LinterLintCode.unnecessary_final_with_type; + LintCode getErrorCode(Object? type) => + type == null + ? LinterLintCode.unnecessary_final_without_type + : LinterLintCode.unnecessary_final_with_type; (Token?, AstNode?) getParameterDetails(FormalParameter node) { var parameter = node is DefaultFormalParameter ? node.parameter : node; @@ -102,8 +102,10 @@ class _Visitor extends SimpleAstVisitor { } else if (forLoopParts is ForEachPartsWithPattern) { var keyword = forLoopParts.keyword; if (keyword.isFinal) { - rule.reportLintForToken(keyword, - errorCode: LinterLintCode.unnecessary_final_without_type); + rule.reportLintForToken( + keyword, + errorCode: LinterLintCode.unnecessary_final_without_type, + ); } } } diff --git a/pkg/linter/lib/src/rules/unnecessary_getters_setters.dart b/pkg/linter/lib/src/rules/unnecessary_getters_setters.dart index dde812f822de..fc47ff39f15e 100644 --- a/pkg/linter/lib/src/rules/unnecessary_getters_setters.dart +++ b/pkg/linter/lib/src/rules/unnecessary_getters_setters.dart @@ -14,17 +14,16 @@ const _desc = class UnnecessaryGettersSetters extends LintRule { UnnecessaryGettersSetters() - : super( - name: LintNames.unnecessary_getters_setters, - description: _desc, - ); + : super(name: LintNames.unnecessary_getters_setters, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_getters_setters; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addExtensionTypeDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_lambdas.dart b/pkg/linter/lib/src/rules/unnecessary_lambdas.dart index a4896194b679..6784edb7917a 100644 --- a/pkg/linter/lib/src/rules/unnecessary_lambdas.dart +++ b/pkg/linter/lib/src/rules/unnecessary_lambdas.dart @@ -18,17 +18,16 @@ Set _extractElementsOfSimpleIdentifiers(AstNode node) => class UnnecessaryLambdas extends LintRule { UnnecessaryLambdas() - : super( - name: LintNames.unnecessary_lambdas, - description: _desc, - ); + : super(name: LintNames.unnecessary_lambdas, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_lambdas; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFunctionExpression(this, visitor); } @@ -94,9 +93,10 @@ class _Visitor extends SimpleAstVisitor { final TypeSystem typeSystem; _Visitor(this.rule, LinterContext context) - : constructorTearOffsEnabled = - context.isEnabled(Feature.constructor_tearoffs), - typeSystem = context.typeSystem; + : constructorTearOffsEnabled = context.isEnabled( + Feature.constructor_tearoffs, + ), + typeSystem = context.typeSystem; @override void visitFunctionExpression(FunctionExpression node) { @@ -110,7 +110,9 @@ class _Visitor extends SimpleAstVisitor { if (statement is ExpressionStatement && statement.expression is InvocationExpression) { _visitInvocationExpression( - statement.expression as InvocationExpression, node); + statement.expression as InvocationExpression, + node, + ); } else if (statement is ReturnStatement && statement.expression is InvocationExpression) { var expression = statement.expression; @@ -135,7 +137,9 @@ class _Visitor extends SimpleAstVisitor { /// Checks [expression], the singular child the body of [node], to see whether /// [node] unnecessarily wraps [node]. void _visitInstanceCreation( - InstanceCreationExpression expression, FunctionExpression node) { + InstanceCreationExpression expression, + FunctionExpression node, + ) { if (expression.isConst || expression.constructorName.type.isDeferred) { return; } @@ -170,11 +174,15 @@ class _Visitor extends SimpleAstVisitor { } void _visitInvocationExpression( - InvocationExpression node, FunctionExpression nodeToLint) { + InvocationExpression node, + FunctionExpression nodeToLint, + ) { var nodeToLintParams = nodeToLint.parameters?.parameters; if (nodeToLintParams == null || !argumentsMatchParameters( - node.argumentList.arguments, nodeToLintParams)) { + node.argumentList.arguments, + nodeToLintParams, + )) { return; } @@ -234,10 +242,10 @@ extension on Expression? { extension on Element2? { /// Returns whether this is a `final` variable or property and not `late`. bool get isFinal => switch (this) { - PropertyAccessorElement2(:var isSynthetic, :var variable3?) => - isSynthetic && variable3.isFinal && !variable3.isLate, - VariableElement2(:var isLate, :var isFinal) => isFinal && !isLate, - // TODO(pq): [element model] this preserves existing v1 semantics but looks fishy - _ => true, - }; + PropertyAccessorElement2(:var isSynthetic, :var variable3?) => + isSynthetic && variable3.isFinal && !variable3.isLate, + VariableElement2(:var isLate, :var isFinal) => isFinal && !isLate, + // TODO(pq): [element model] this preserves existing v1 semantics but looks fishy + _ => true, + }; } diff --git a/pkg/linter/lib/src/rules/unnecessary_late.dart b/pkg/linter/lib/src/rules/unnecessary_late.dart index d03f8bc9f408..b6b8a86613c9 100644 --- a/pkg/linter/lib/src/rules/unnecessary_late.dart +++ b/pkg/linter/lib/src/rules/unnecessary_late.dart @@ -11,17 +11,16 @@ const _desc = r"Don't specify the `late` modifier when it is not needed."; class UnnecessaryLate extends LintRule { UnnecessaryLate() - : super( - name: LintNames.unnecessary_late, - description: _desc, - ); + : super(name: LintNames.unnecessary_late, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_late; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFieldDeclaration(this, visitor); registry.addTopLevelVariableDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_library_directive.dart b/pkg/linter/lib/src/rules/unnecessary_library_directive.dart index ee5e5509b369..1cffe40df022 100644 --- a/pkg/linter/lib/src/rules/unnecessary_library_directive.dart +++ b/pkg/linter/lib/src/rules/unnecessary_library_directive.dart @@ -13,10 +13,7 @@ const _desc = class UnnecessaryLibraryDirective extends LintRule { UnnecessaryLibraryDirective() - : super( - name: LintNames.unnecessary_library_directive, - description: _desc, - ); + : super(name: LintNames.unnecessary_library_directive, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_library_directive; diff --git a/pkg/linter/lib/src/rules/unnecessary_library_name.dart b/pkg/linter/lib/src/rules/unnecessary_library_name.dart index a6e8ced1c479..91378d415547 100644 --- a/pkg/linter/lib/src/rules/unnecessary_library_name.dart +++ b/pkg/linter/lib/src/rules/unnecessary_library_name.dart @@ -13,17 +13,16 @@ const _desc = r"Don't have a library name in a `library` declaration."; class UnnecessaryLibraryName extends LintRule { UnnecessaryLibraryName() - : super( - name: LintNames.unnecessary_library_name, - description: _desc, - ); + : super(name: LintNames.unnecessary_library_name, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_library_name; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isEnabled(Feature.unnamedLibraries)) return; var visitor = _Visitor(this); diff --git a/pkg/linter/lib/src/rules/unnecessary_new.dart b/pkg/linter/lib/src/rules/unnecessary_new.dart index 252b904e5e4a..ab670bf29ff2 100644 --- a/pkg/linter/lib/src/rules/unnecessary_new.dart +++ b/pkg/linter/lib/src/rules/unnecessary_new.dart @@ -11,11 +11,7 @@ import '../analyzer.dart'; const _desc = r'Unnecessary new keyword.'; class UnnecessaryNew extends LintRule { - UnnecessaryNew() - : super( - name: LintNames.unnecessary_new, - description: _desc, - ); + UnnecessaryNew() : super(name: LintNames.unnecessary_new, description: _desc); @override bool get canUseParsedResult => true; @@ -25,7 +21,9 @@ class UnnecessaryNew extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_null_aware_assignments.dart b/pkg/linter/lib/src/rules/unnecessary_null_aware_assignments.dart index fb7efff026a9..4f223bc50c94 100644 --- a/pkg/linter/lib/src/rules/unnecessary_null_aware_assignments.dart +++ b/pkg/linter/lib/src/rules/unnecessary_null_aware_assignments.dart @@ -14,17 +14,19 @@ const _desc = r'Avoid `null` in `null`-aware assignment.'; class UnnecessaryNullAwareAssignments extends LintRule { UnnecessaryNullAwareAssignments() - : super( - name: LintNames.unnecessary_null_aware_assignments, - description: _desc, - ); + : super( + name: LintNames.unnecessary_null_aware_assignments, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.unnecessary_null_aware_assignments; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addAssignmentExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_null_aware_operator_on_extension_on_nullable.dart b/pkg/linter/lib/src/rules/unnecessary_null_aware_operator_on_extension_on_nullable.dart index de20ad32d07f..a2098e9ce905 100644 --- a/pkg/linter/lib/src/rules/unnecessary_null_aware_operator_on_extension_on_nullable.dart +++ b/pkg/linter/lib/src/rules/unnecessary_null_aware_operator_on_extension_on_nullable.dart @@ -13,11 +13,11 @@ const _desc = class UnnecessaryNullAwareOperatorOnExtensionOnNullable extends LintRule { UnnecessaryNullAwareOperatorOnExtensionOnNullable() - : super( - name: LintNames - .unnecessary_null_aware_operator_on_extension_on_nullable, - description: _desc, - ); + : super( + name: + LintNames.unnecessary_null_aware_operator_on_extension_on_nullable, + description: _desc, + ); @override LintCode get lintCode => @@ -25,7 +25,9 @@ class UnnecessaryNullAwareOperatorOnExtensionOnNullable extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addIndexExpression(this, visitor); registry.addMethodInvocation(this, visitor); @@ -42,12 +44,14 @@ class _Visitor extends SimpleAstVisitor { @override void visitIndexExpression(IndexExpression node) { if (node.isNullAware && - _isExtensionOnNullableType(node.inSetterContext() - ? node - .thisOrAncestorOfType() - ?.writeElement2 - ?.enclosingElement2 - : node.element?.enclosingElement2)) { + _isExtensionOnNullableType( + node.inSetterContext() + ? node + .thisOrAncestorOfType() + ?.writeElement2 + ?.enclosingElement2 + : node.element?.enclosingElement2, + )) { rule.reportLintForToken(node.question); } } @@ -56,7 +60,8 @@ class _Visitor extends SimpleAstVisitor { void visitMethodInvocation(MethodInvocation node) { if (node.isNullAware && _isExtensionOnNullableType( - node.methodName.element?.enclosingElement2)) { + node.methodName.element?.enclosingElement2, + )) { rule.reportLintForToken(node.operator); } } @@ -65,10 +70,13 @@ class _Visitor extends SimpleAstVisitor { void visitPropertyAccess(PropertyAccess node) { if (node.isNullAware) { var realParent = node.thisOrAncestorMatching( - (p) => p != node && p is! ParenthesizedExpression); - if (_isExtensionOnNullableType(realParent is AssignmentExpression - ? realParent.writeElement2?.enclosingElement2 - : node.propertyName.element?.enclosingElement2)) { + (p) => p != node && p is! ParenthesizedExpression, + ); + if (_isExtensionOnNullableType( + realParent is AssignmentExpression + ? realParent.writeElement2?.enclosingElement2 + : node.propertyName.element?.enclosingElement2, + )) { rule.reportLintForToken(node.operator); } } diff --git a/pkg/linter/lib/src/rules/unnecessary_null_checks.dart b/pkg/linter/lib/src/rules/unnecessary_null_checks.dart index 8eef2e2d0aa2..0e5019d0c9b0 100644 --- a/pkg/linter/lib/src/rules/unnecessary_null_checks.dart +++ b/pkg/linter/lib/src/rules/unnecessary_null_checks.dart @@ -12,8 +12,9 @@ import '../analyzer.dart'; const _desc = r'Unnecessary `null` checks.'; DartType? getExpectedType(PostfixExpression node) { - var realNode = - node.thisOrAncestorMatching((e) => e.parent is! ParenthesizedExpression); + var realNode = node.thisOrAncestorMatching( + (e) => e.parent is! ParenthesizedExpression, + ); var parent = realNode?.parent; var withAwait = parent is AwaitExpression; if (withAwait) { @@ -134,18 +135,20 @@ DartType? getExpectedType(PostfixExpression node) { class UnnecessaryNullChecks extends LintRule { UnnecessaryNullChecks() - : super( - name: LintNames.unnecessary_null_checks, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.unnecessary_null_checks, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.unnecessary_null_checks; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addNullAssertPattern(this, visitor); registry.addPostfixExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_null_in_if_null_operators.dart b/pkg/linter/lib/src/rules/unnecessary_null_in_if_null_operators.dart index 12a8843c2899..b8efcc782db7 100644 --- a/pkg/linter/lib/src/rules/unnecessary_null_in_if_null_operators.dart +++ b/pkg/linter/lib/src/rules/unnecessary_null_in_if_null_operators.dart @@ -13,17 +13,19 @@ const _desc = r'Avoid using `null` in `??` operators.'; class UnnecessaryNullInIfNullOperators extends LintRule { UnnecessaryNullInIfNullOperators() - : super( - name: LintNames.unnecessary_null_in_if_null_operators, - description: _desc, - ); + : super( + name: LintNames.unnecessary_null_in_if_null_operators, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.unnecessary_null_in_if_null_operators; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBinaryExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_nullable_for_final_variable_declarations.dart b/pkg/linter/lib/src/rules/unnecessary_nullable_for_final_variable_declarations.dart index 1aedab152b9b..b4e8649ea9f0 100644 --- a/pkg/linter/lib/src/rules/unnecessary_nullable_for_final_variable_declarations.dart +++ b/pkg/linter/lib/src/rules/unnecessary_nullable_for_final_variable_declarations.dart @@ -9,15 +9,16 @@ import 'package:analyzer/dart/element/type.dart'; import '../analyzer.dart'; -const _desc = r'Use a non-nullable type for a final variable initialized ' +const _desc = + r'Use a non-nullable type for a final variable initialized ' 'with a non-nullable value.'; class UnnecessaryNullableForFinalVariableDeclarations extends LintRule { UnnecessaryNullableForFinalVariableDeclarations() - : super( - name: LintNames.unnecessary_nullable_for_final_variable_declarations, - description: _desc, - ); + : super( + name: LintNames.unnecessary_nullable_for_final_variable_declarations, + description: _desc, + ); @override LintCode get lintCode => @@ -25,7 +26,9 @@ class UnnecessaryNullableForFinalVariableDeclarations extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addFieldDeclaration(this, visitor); registry.addPatternVariableDeclaration(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_overrides.dart b/pkg/linter/lib/src/rules/unnecessary_overrides.dart index f9edd3b06fb4..d3488f4b94ae 100644 --- a/pkg/linter/lib/src/rules/unnecessary_overrides.dart +++ b/pkg/linter/lib/src/rules/unnecessary_overrides.dart @@ -16,17 +16,16 @@ const _desc = class UnnecessaryOverrides extends LintRule { UnnecessaryOverrides() - : super( - name: LintNames.unnecessary_overrides, - description: _desc, - ); + : super(name: LintNames.unnecessary_overrides, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_overrides; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } @@ -231,7 +230,9 @@ class _UnnecessaryMethodOverrideVisitor if (declarationParameters != null && node.methodName.name == _inheritedMethod.name3 && argumentsMatchParameters( - node.argumentList.arguments, declarationParameters.parameters)) { + node.argumentList.arguments, + declarationParameters.parameters, + )) { node.target?.accept(this); } } diff --git a/pkg/linter/lib/src/rules/unnecessary_parenthesis.dart b/pkg/linter/lib/src/rules/unnecessary_parenthesis.dart index 15c1ff8c8983..8a0dde4355e3 100644 --- a/pkg/linter/lib/src/rules/unnecessary_parenthesis.dart +++ b/pkg/linter/lib/src/rules/unnecessary_parenthesis.dart @@ -15,17 +15,16 @@ const _desc = r'Unnecessary parentheses can be removed.'; class UnnecessaryParenthesis extends LintRule { UnnecessaryParenthesis() - : super( - name: LintNames.unnecessary_parenthesis, - description: _desc, - ); + : super(name: LintNames.unnecessary_parenthesis, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_parenthesis; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeSystem); registry.addParenthesizedExpression(this, visitor); } @@ -171,7 +170,8 @@ class _Visitor extends SimpleAstVisitor { // `a..b = (c..d)` is OK. if (expression is CascadeExpression || node.thisOrAncestorMatching( - (n) => n is Statement || n is CascadeExpression) + (n) => n is Statement || n is CascadeExpression, + ) is CascadeExpression) { return; } diff --git a/pkg/linter/lib/src/rules/unnecessary_raw_strings.dart b/pkg/linter/lib/src/rules/unnecessary_raw_strings.dart index d2947e7f4d16..5a3a8a10f06b 100644 --- a/pkg/linter/lib/src/rules/unnecessary_raw_strings.dart +++ b/pkg/linter/lib/src/rules/unnecessary_raw_strings.dart @@ -11,17 +11,16 @@ const _desc = r'Unnecessary raw string.'; class UnnecessaryRawStrings extends LintRule { UnnecessaryRawStrings() - : super( - name: LintNames.unnecessary_raw_strings, - description: _desc, - ); + : super(name: LintNames.unnecessary_raw_strings, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_raw_strings; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSimpleStringLiteral(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_statements.dart b/pkg/linter/lib/src/rules/unnecessary_statements.dart index 35c51d80a3ca..b90ef2115069 100644 --- a/pkg/linter/lib/src/rules/unnecessary_statements.dart +++ b/pkg/linter/lib/src/rules/unnecessary_statements.dart @@ -13,17 +13,16 @@ const _desc = r'Avoid using unnecessary statements.'; class UnnecessaryStatements extends LintRule { UnnecessaryStatements() - : super( - name: LintNames.unnecessary_statements, - description: _desc, - ); + : super(name: LintNames.unnecessary_statements, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_statements; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(_ReportNoClearEffectVisitor(this)); registry.addExpressionStatement(this, visitor); registry.addForStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/unnecessary_string_escapes.dart b/pkg/linter/lib/src/rules/unnecessary_string_escapes.dart index 1934720ac703..d86492a2b6a4 100644 --- a/pkg/linter/lib/src/rules/unnecessary_string_escapes.dart +++ b/pkg/linter/lib/src/rules/unnecessary_string_escapes.dart @@ -12,10 +12,7 @@ const _desc = r'Remove unnecessary backslashes in strings.'; class UnnecessaryStringEscapes extends LintRule { UnnecessaryStringEscapes() - : super( - name: LintNames.unnecessary_string_escapes, - description: _desc, - ); + : super(name: LintNames.unnecessary_string_escapes, description: _desc); @override bool get canUseParsedResult => true; @@ -25,7 +22,9 @@ class UnnecessaryStringEscapes extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSimpleStringLiteral(this, visitor); registry.addStringInterpolation(this, visitor); @@ -66,8 +65,9 @@ class _Visitor extends SimpleAstVisitor { var pendingQuotes = {}; void checkPendingQuotes() { if (isMultiline && pendingQuotes.length < 3) { - var escapeIndexes = - pendingQuotes.entries.where((e) => e.value).map((e) => e.key); + var escapeIndexes = pendingQuotes.entries + .where((e) => e.value) + .map((e) => e.key); for (var index in escapeIndexes) { // case for '''___\'''' : without last backslash it leads a parsing error if (contentsEnd != token.end && index + 2 == contentsEnd) continue; @@ -76,8 +76,10 @@ class _Visitor extends SimpleAstVisitor { } } - var lexeme = token.lexeme - .substring(contentsOffset - token.offset, contentsEnd - token.offset); + var lexeme = token.lexeme.substring( + contentsOffset - token.offset, + contentsEnd - token.offset, + ); for (var i = 0; i < lexeme.length; i++) { var current = lexeme[i]; var escaped = false; diff --git a/pkg/linter/lib/src/rules/unnecessary_string_interpolations.dart b/pkg/linter/lib/src/rules/unnecessary_string_interpolations.dart index 797b26cf6ff7..3d13db2c6ad9 100644 --- a/pkg/linter/lib/src/rules/unnecessary_string_interpolations.dart +++ b/pkg/linter/lib/src/rules/unnecessary_string_interpolations.dart @@ -12,17 +12,19 @@ const _desc = r'Unnecessary string interpolation.'; class UnnecessaryStringInterpolations extends LintRule { UnnecessaryStringInterpolations() - : super( - name: LintNames.unnecessary_string_interpolations, - description: _desc, - ); + : super( + name: LintNames.unnecessary_string_interpolations, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.unnecessary_string_interpolations; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addStringInterpolation(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_this.dart b/pkg/linter/lib/src/rules/unnecessary_this.dart index 3054750eba32..5c77627555ac 100644 --- a/pkg/linter/lib/src/rules/unnecessary_this.dart +++ b/pkg/linter/lib/src/rules/unnecessary_this.dart @@ -14,17 +14,16 @@ const _desc = r"Don't access members with `this` unless avoiding shadowing."; class UnnecessaryThis extends LintRule { UnnecessaryThis() - : super( - name: LintNames.unnecessary_this, - description: _desc, - ); + : super(name: LintNames.unnecessary_this, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_this; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addConstructorFieldInitializer(this, visitor); registry.addThisExpression(this, visitor); @@ -67,8 +66,11 @@ class _Visitor extends SimpleAstVisitor { if (element == null) return false; var id = element.displayName; - var result = resolveNameInScope(id, node, - shouldResolveSetter: element is SetterElement); + var result = resolveNameInScope( + id, + node, + shouldResolveSetter: element is SetterElement, + ); // No result, definitely no shadowing. // The requested element is inherited, or from an extension. diff --git a/pkg/linter/lib/src/rules/unnecessary_to_list_in_spreads.dart b/pkg/linter/lib/src/rules/unnecessary_to_list_in_spreads.dart index 5e8da120271a..079c2359f6ee 100644 --- a/pkg/linter/lib/src/rules/unnecessary_to_list_in_spreads.dart +++ b/pkg/linter/lib/src/rules/unnecessary_to_list_in_spreads.dart @@ -12,17 +12,16 @@ const _desc = r'Unnecessary `toList()` in spreads.'; class UnnecessaryToListInSpreads extends LintRule { UnnecessaryToListInSpreads() - : super( - name: LintNames.unnecessary_to_list_in_spreads, - description: _desc, - ); + : super(name: LintNames.unnecessary_to_list_in_spreads, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_to_list_in_spreads; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSpreadElement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/unnecessary_underscores.dart b/pkg/linter/lib/src/rules/unnecessary_underscores.dart index 844690d82d01..f86d3a1be441 100644 --- a/pkg/linter/lib/src/rules/unnecessary_underscores.dart +++ b/pkg/linter/lib/src/rules/unnecessary_underscores.dart @@ -17,17 +17,16 @@ const _desc = r'Unnecessary underscores can be removed.'; class UnnecessaryUnderscores extends LintRule { UnnecessaryUnderscores() - : super( - name: LintNames.unnecessary_underscores, - description: _desc, - ); + : super(name: LintNames.unnecessary_underscores, description: _desc); @override LintCode get lintCode => LinterLintCode.unnecessary_underscores; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isEnabled(Feature.wildcard_variables)) return; var visitor = _Visitor(this); registry.addFormalParameterList(this, visitor); diff --git a/pkg/linter/lib/src/rules/unreachable_from_main.dart b/pkg/linter/lib/src/rules/unreachable_from_main.dart index e69e9f0f2394..445eab6a1122 100644 --- a/pkg/linter/lib/src/rules/unreachable_from_main.dart +++ b/pkg/linter/lib/src/rules/unreachable_from_main.dart @@ -18,11 +18,11 @@ const _desc = 'Unreachable top-level members in executable libraries.'; class UnreachableFromMain extends LintRule { UnreachableFromMain() - : super( - name: LintNames.unreachable_from_main, - description: _desc, - state: State.stable(since: Version(3, 1, 0)), - ); + : super( + name: LintNames.unreachable_from_main, + description: _desc, + state: State.stable(since: Version(3, 1, 0)), + ); @override LintCode get lintCode => LinterLintCode.unreachable_from_main; @@ -44,9 +44,7 @@ class _DeclarationGatherer { /// All declarations which we may wish to report on. final Set declarations = {}; - _DeclarationGatherer({ - required this.linterContext, - }); + _DeclarationGatherer({required this.linterContext}); void addDeclarations(CompilationUnit node) { for (var declaration in node.declarations) { @@ -69,15 +67,9 @@ class _DeclarationGatherer { members: declaration.members, ); } else if (declaration is ExtensionDeclaration) { - _addMembers( - containerElement: null, - members: declaration.members, - ); + _addMembers(containerElement: null, members: declaration.members); } else if (declaration is ExtensionTypeDeclaration) { - _addMembers( - containerElement: null, - members: declaration.members, - ); + _addMembers(containerElement: null, members: declaration.members); } else if (declaration is MixinDeclaration) { _addMembers( containerElement: declaration.declaredFragment?.element, @@ -130,7 +122,8 @@ class _DeclarationGatherer { var element = member.declaredFragment?.element; if (element != null && element.isPublic) { var rawName = member.name.lexeme; - var isTestMethod = rawName.startsWith('test_') || + var isTestMethod = + rawName.startsWith('test_') || rawName.startsWith('solo_test_') || rawName == 'setUp' || rawName == 'tearDown'; @@ -181,8 +174,9 @@ class _ReferenceVisitor extends RecursiveAstVisitor { var element = node.declaredFragment?.element; if (element != null) { - var hasConstructors = - node.members.any((e) => e is ConstructorDeclaration); + var hasConstructors = node.members.any( + (e) => e is ConstructorDeclaration, + ); if (!hasConstructors) { // The default constructor will have an implicit super-initializer to // the super-type's unnamed constructor. @@ -199,8 +193,9 @@ class _ReferenceVisitor extends RecursiveAstVisitor { annotation.library2.name3 == 'test_reflective_loader') { // The class is instantiated through the use of mirrors in // 'test_reflective_loader'. - var unnamedConstructor = element.constructors2 - .firstWhereOrNull((constructor) => constructor.name3 == 'new'); + var unnamedConstructor = element.constructors2.firstWhereOrNull( + (constructor) => constructor.name3 == 'new', + ); if (unnamedConstructor != null) { _addDeclaration(unnamedConstructor); } @@ -225,8 +220,9 @@ class _ReferenceVisitor extends RecursiveAstVisitor { // If a constructor in a class declaration does not have an explicit // super-initializer (or redirection?) then it has an implicit // super-initializer to the super-type's unnamed constructor. - var hasSuperInitializer = - node.initializers.any((e) => e is SuperConstructorInvocation); + var hasSuperInitializer = node.initializers.any( + (e) => e is SuperConstructorInvocation, + ); if (!hasSuperInitializer) { var enclosingClass = node.parent; if (enclosingClass is ClassDeclaration) { @@ -281,17 +277,17 @@ class _ReferenceVisitor extends RecursiveAstVisitor { node.thisOrAncestorOfType() != null; if ( - // Any reference to a typedef marks it as reachable, since structural - // typing is used to match against objects. - node.type?.alias != null || - // Any reference to an extension type marks it as reachable, since - // casting can be used to instantiate the type. - node.type?.element3 is ExtensionTypeElement2 || - nodeIsInTypeArgument || - // A reference to any type in an external variable declaration marks - // that type as reachable, since the external implementation can - // instantiate it. - node.isInExternalVariableTypeOrFunctionReturnType) { + // Any reference to a typedef marks it as reachable, since structural + // typing is used to match against objects. + node.type?.alias != null || + // Any reference to an extension type marks it as reachable, since + // casting can be used to instantiate the type. + node.type?.element3 is ExtensionTypeElement2 || + nodeIsInTypeArgument || + // A reference to any type in an external variable declaration marks + // that type as reachable, since the external implementation can + // instantiate it. + node.isInExternalVariableTypeOrFunctionReturnType) { _addDeclaration(element); } @@ -332,7 +328,8 @@ class _ReferenceVisitor extends RecursiveAstVisitor { @override void visitRedirectingConstructorInvocation( - RedirectingConstructorInvocation node) { + RedirectingConstructorInvocation node, + ) { var element = node.element; if (element != null) { _addDeclaration(element); @@ -379,8 +376,10 @@ class _ReferenceVisitor extends RecursiveAstVisitor { /// or static method on a public top-level element. void _addDeclaration(Element2 element) { // First add the enclosing top-level declaration. - var enclosingTopLevelElement = element.thisOrAncestorMatching2((a) => - a.enclosingElement2 == null || a.enclosingElement2 is LibraryElement2); + var enclosingTopLevelElement = element.thisOrAncestorMatching2( + (a) => + a.enclosingElement2 == null || a.enclosingElement2 is LibraryElement2, + ); var enclosingTopLevelDeclaration = declarationMap[enclosingTopLevelElement]; if (enclosingTopLevelDeclaration != null) { declarations.add(enclosingTopLevelDeclaration); @@ -410,8 +409,9 @@ class _ReferenceVisitor extends RecursiveAstVisitor { var classElement = class_.declaredFragment?.element; var supertype = classElement?.supertype; if (supertype != null) { - var unnamedConstructor = - supertype.constructors2.firstWhereOrNull((e) => e.name3 == 'new'); + var unnamedConstructor = supertype.constructors2.firstWhereOrNull( + (e) => e.name3 == 'new', + ); if (unnamedConstructor != null) { _addDeclaration(unnamedConstructor); } @@ -520,20 +520,23 @@ class _Visitor extends SimpleAstVisitor { unitDeclarationGatherer.addDeclarations(node); var unitDeclarations = unitDeclarationGatherer.declarations; var unusedDeclarations = unitDeclarations.difference(usedMembers); - var unusedMembers = unusedDeclarations.where((declaration) { - var element = declaration.declaredFragment?.element; - return element != null && - element.isPublic && - !element.hasVisibleForTesting; - }).toList(); + var unusedMembers = + unusedDeclarations.where((declaration) { + var element = declaration.declaredFragment?.element; + return element != null && + element.isPublic && + !element.hasVisibleForTesting; + }).toList(); for (var member in unusedMembers) { if (member is ConstructorDeclaration) { if (member.name == null) { rule.reportLint(member.returnType, arguments: [member.nameForError]); } else { - rule.reportLintForToken(member.name, - arguments: [member.nameForError]); + rule.reportLintForToken( + member.name, + arguments: [member.nameForError], + ); } } else if (member is NamedCompilationUnitMember) { rule.reportLintForToken(member.name, arguments: [member.nameForError]); @@ -570,9 +573,9 @@ class _Visitor extends SimpleAstVisitor { extension on Element2 { bool get hasVisibleForTesting => switch (this) { - Annotatable(:var metadata2) => metadata2.hasVisibleForTesting, - _ => false, - }; + Annotatable(:var metadata2) => metadata2.hasVisibleForTesting, + _ => false, + }; bool get isPragma => (library2?.isDartCore ?? false) && name3 == 'pragma'; } @@ -625,11 +628,11 @@ extension on NamedType { case MethodDeclaration(:var externalKeyword, :var returnType): return externalKeyword != null && returnType == topTypeAnnotation; case VariableDeclarationList( - parent: FieldDeclaration(:var externalKeyword), - ): + parent: FieldDeclaration(:var externalKeyword), + ): case VariableDeclarationList( - parent: TopLevelVariableDeclaration(:var externalKeyword), - ): + parent: TopLevelVariableDeclaration(:var externalKeyword), + ): return externalKeyword != null; } return false; diff --git a/pkg/linter/lib/src/rules/unrelated_type_equality_checks.dart b/pkg/linter/lib/src/rules/unrelated_type_equality_checks.dart index 3f2c249d7fb5..0c2336414f90 100644 --- a/pkg/linter/lib/src/rules/unrelated_type_equality_checks.dart +++ b/pkg/linter/lib/src/rules/unrelated_type_equality_checks.dart @@ -15,20 +15,19 @@ const _desc = class UnrelatedTypeEqualityChecks extends LintRule { UnrelatedTypeEqualityChecks() - : super( - name: LintNames.unrelated_type_equality_checks, - description: _desc, - ); + : super(name: LintNames.unrelated_type_equality_checks, description: _desc); @override List get lintCodes => [ - LinterLintCode.unrelated_type_equality_checks_in_expression, - LinterLintCode.unrelated_type_equality_checks_in_pattern - ]; + LinterLintCode.unrelated_type_equality_checks_in_expression, + LinterLintCode.unrelated_type_equality_checks_in_pattern, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.typeSystem); registry.addBinaryExpression(this, visitor); registry.addRelationalPattern(this, visitor); @@ -61,10 +60,7 @@ class _Visitor extends SimpleAstVisitor { rule.reportLintForToken( node.operator, errorCode: LinterLintCode.unrelated_type_equality_checks_in_expression, - arguments: [ - rightType.getDisplayString(), - leftType.getDisplayString(), - ], + arguments: [rightType.getDisplayString(), leftType.getDisplayString()], ); } @@ -80,10 +76,7 @@ class _Visitor extends SimpleAstVisitor { rule.reportLint( node, errorCode: LinterLintCode.unrelated_type_equality_checks_in_pattern, - arguments: [ - operandType.getDisplayString(), - valueType.getDisplayString(), - ], + arguments: [operandType.getDisplayString(), valueType.getDisplayString()], ); } diff --git a/pkg/linter/lib/src/rules/unsafe_html.dart b/pkg/linter/lib/src/rules/unsafe_html.dart index d6b12978db87..d984b3179383 100644 --- a/pkg/linter/lib/src/rules/unsafe_html.dart +++ b/pkg/linter/lib/src/rules/unsafe_html.dart @@ -8,10 +8,11 @@ import '../analyzer.dart'; class UnsafeHtml extends LintRule { UnsafeHtml() - : super( - name: LintNames.unsafe_html, - description: 'Avoid unsafe HTML APIs.', - state: State.removed(since: Version(3, 7, 0))); + : super( + name: LintNames.unsafe_html, + description: 'Avoid unsafe HTML APIs.', + state: State.removed(since: Version(3, 7, 0)), + ); @override LintCode get lintCode => LinterLintCode.removed_lint; diff --git a/pkg/linter/lib/src/rules/unsafe_variance.dart b/pkg/linter/lib/src/rules/unsafe_variance.dart index c614dddde9f0..587ba59a9d45 100644 --- a/pkg/linter/lib/src/rules/unsafe_variance.dart +++ b/pkg/linter/lib/src/rules/unsafe_variance.dart @@ -17,18 +17,20 @@ const _desc = r'Unsafe type: Has a type variable in a non-covariant position.'; class UnsafeVariance extends LintRule { UnsafeVariance() - : super( - name: LintNames.unsafe_variance, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.unsafe_variance, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => LinterLintCode.unsafe_variance; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addMethodDeclaration(this, visitor); registry.addVariableDeclarationList(this, visitor); diff --git a/pkg/linter/lib/src/rules/use_build_context_synchronously.dart b/pkg/linter/lib/src/rules/use_build_context_synchronously.dart index 6db52eeb1539..63db33d4b707 100644 --- a/pkg/linter/lib/src/rules/use_build_context_synchronously.dart +++ b/pkg/linter/lib/src/rules/use_build_context_synchronously.dart @@ -348,24 +348,24 @@ class AsyncStateVisitor extends SimpleAstVisitor { var referenceIsBody = node.body == _reference; return switch (forLoopParts) { ForPartsWithDeclarations() => _inOrderAsyncState([ - for (var declaration in forLoopParts.variables.variables) - (node: declaration, mountedCanGuard: false), - (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), - for (var updater in forLoopParts.updaters) - (node: updater, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + for (var declaration in forLoopParts.variables.variables) + (node: declaration, mountedCanGuard: false), + (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), + for (var updater in forLoopParts.updaters) + (node: updater, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), ForPartsWithExpression() => _inOrderAsyncState([ - (node: forLoopParts.initialization, mountedCanGuard: false), - (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), - for (var updater in forLoopParts.updaters) - (node: updater, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + (node: forLoopParts.initialization, mountedCanGuard: false), + (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), + for (var updater in forLoopParts.updaters) + (node: updater, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), ForEachParts() => _inOrderAsyncState([ - (node: forLoopParts.iterable, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + (node: forLoopParts.iterable, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), _ => null, }; } @@ -376,35 +376,37 @@ class AsyncStateVisitor extends SimpleAstVisitor { var referenceIsBody = node.body == _reference; return switch (forLoopParts) { ForPartsWithDeclarations() => _inOrderAsyncState([ - for (var declaration in forLoopParts.variables.variables) - (node: declaration, mountedCanGuard: false), - // The body can be guarded by the condition. - (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), - for (var updater in forLoopParts.updaters) - (node: updater, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + for (var declaration in forLoopParts.variables.variables) + (node: declaration, mountedCanGuard: false), + // The body can be guarded by the condition. + (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), + for (var updater in forLoopParts.updaters) + (node: updater, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), ForPartsWithExpression() => _inOrderAsyncState([ - (node: forLoopParts.initialization, mountedCanGuard: false), - // The body can be guarded by the condition. - (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), - for (var updater in forLoopParts.updaters) - (node: updater, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + (node: forLoopParts.initialization, mountedCanGuard: false), + // The body can be guarded by the condition. + (node: forLoopParts.condition, mountedCanGuard: referenceIsBody), + for (var updater in forLoopParts.updaters) + (node: updater, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), ForEachParts() => _inOrderAsyncState([ - (node: forLoopParts.iterable, mountedCanGuard: false), - (node: node.body, mountedCanGuard: false), - ]), + (node: forLoopParts.iterable, mountedCanGuard: false), + (node: node.body, mountedCanGuard: false), + ]), _ => null, }; } @override AsyncState? visitFunctionExpressionInvocation( - FunctionExpressionInvocation node) => - _asynchronousIfAnyIsAsync( - [node.function, ...node.argumentList.arguments]); + FunctionExpressionInvocation node, + ) => _asynchronousIfAnyIsAsync([ + node.function, + ...node.argumentList.arguments, + ]); @override AsyncState? visitGuardedPattern(GuardedPattern node) => @@ -412,19 +414,19 @@ class AsyncStateVisitor extends SimpleAstVisitor { @override AsyncState? visitIfElement(IfElement node) => _visitIfLike( - expression: node.expression, - caseClause: node.caseClause, - thenBranch: node.thenElement, - elseBranch: node.elseElement, - ); + expression: node.expression, + caseClause: node.caseClause, + thenBranch: node.thenElement, + elseBranch: node.elseElement, + ); @override AsyncState? visitIfStatement(IfStatement node) => _visitIfLike( - expression: node.expression, - caseClause: node.caseClause, - thenBranch: node.thenStatement, - elseBranch: node.elseStatement, - ); + expression: node.expression, + caseClause: node.caseClause, + thenBranch: node.thenStatement, + elseBranch: node.elseStatement, + ); @override AsyncState? visitIndexExpression(IndexExpression node) => @@ -432,8 +434,8 @@ class AsyncStateVisitor extends SimpleAstVisitor { @override AsyncState? visitInstanceCreationExpression( - InstanceCreationExpression node) => - _asynchronousIfAnyIsAsync(node.argumentList.arguments); + InstanceCreationExpression node, + ) => _asynchronousIfAnyIsAsync(node.argumentList.arguments); @override AsyncState? visitInterpolationExpression(InterpolationExpression node) => @@ -520,8 +522,8 @@ class AsyncStateVisitor extends SimpleAstVisitor { @override AsyncState? visitSwitchCase(SwitchCase node) => - // TODO(srawlins): Handle when `reference` is in one of the statements. - _inOrderAsyncStateGuardable([node.expression, ...node.statements]); + // TODO(srawlins): Handle when `reference` is in one of the statements. + _inOrderAsyncStateGuardable([node.expression, ...node.statements]); @override AsyncState? visitSwitchDefault(SwitchDefault node) => @@ -553,8 +555,10 @@ class AsyncStateVisitor extends SimpleAstVisitor { if (_reference == node.guardedPattern) { return null; } - var statementsAsyncState = - _visitBlockLike(node.statements, parent: node.parent); + var statementsAsyncState = _visitBlockLike( + node.statements, + parent: node.parent, + ); if (statementsAsyncState != null) return statementsAsyncState; if (node.statements.contains(_reference)) { // Any when-clause in `node` and any fallthrough when-clauses are handled @@ -644,10 +648,10 @@ class AsyncStateVisitor extends SimpleAstVisitor { @override AsyncState? visitVariableDeclarationStatement( - VariableDeclarationStatement node) => - _asynchronousIfAnyIsAsync([ - for (var variable in node.variables.variables) variable.initializer, - ]); + VariableDeclarationStatement node, + ) => _asynchronousIfAnyIsAsync([ + for (var variable in node.variables.variables) variable.initializer, + ]); @override AsyncState? visitWhenClause(WhenClause node) => node.expression.accept(this); @@ -709,11 +713,13 @@ class AsyncStateVisitor extends SimpleAstVisitor { /// If [_reference] is one of the [nodes], this traversal starts at the node /// that precedes it, rather than at the end of the list. AsyncState? _inOrderAsyncState( - List<({AstNode? node, bool mountedCanGuard})> nodes) { + List<({AstNode? node, bool mountedCanGuard})> nodes, + ) { if (nodes.isEmpty) return null; if (nodes.first.node == _reference) return null; - var referenceIndex = - nodes.indexWhere((element) => element.node == _reference); + var referenceIndex = nodes.indexWhere( + (element) => element.node == _reference, + ); var startingIndex = referenceIndex > 0 ? referenceIndex - 1 : nodes.length - 1; @@ -742,8 +748,10 @@ class AsyncStateVisitor extends SimpleAstVisitor { ]); /// Compute the [AsyncState] of a "block-like" node which has [statements]. - AsyncState? _visitBlockLike(List statements, - {required AstNode? parent}) { + AsyncState? _visitBlockLike( + List statements, { + required AstNode? parent, + }) { var reference = _reference; if (reference is Statement) { var index = statements.indexOf(reference); @@ -756,8 +764,9 @@ class AsyncStateVisitor extends SimpleAstVisitor { // Check for asynchrony in the statements that _follow_ [reference], // as they may lead to an async gap before we loop back to // [reference]. - return _inOrderAsyncStateGuardable(statements.skip(index + 1)) - ?.asynchronousOrNull; + return _inOrderAsyncStateGuardable( + statements.skip(index + 1), + )?.asynchronousOrNull; } return null; } @@ -808,8 +817,10 @@ class AsyncStateVisitor extends SimpleAstVisitor { var caseClauseAsyncState = caseClause?.accept(this); // The condition state is the combined state of `expression` and // `caseClause`. - var conditionAsyncState = - switch ((expressionAsyncState, caseClauseAsyncState)) { + var conditionAsyncState = switch (( + expressionAsyncState, + caseClauseAsyncState, + )) { // If the left is uninteresting, just return the state of the right. (null, _) => caseClauseAsyncState, // If the right is uninteresting, just return the state of the left. @@ -898,27 +909,34 @@ class ProtectedFunction { /// The list of named parameters that are protected. final List named; - const ProtectedFunction(this.library, this.type, this.name, - {this.positional = const [], this.named = const []}); + const ProtectedFunction( + this.library, + this.type, + this.name, { + this.positional = const [], + this.named = const [], + }); } class UseBuildContextSynchronously extends LintRule { UseBuildContextSynchronously() - : super( - name: LintNames.use_build_context_synchronously, - description: _desc, - state: State.stable(since: Version(3, 2, 0)), - ); + : super( + name: LintNames.use_build_context_synchronously, + description: _desc, + state: State.stable(since: Version(3, 2, 0)), + ); @override List get lintCodes => [ - LinterLintCode.use_build_context_synchronously_async_use, - LinterLintCode.use_build_context_synchronously_wrong_mounted - ]; + LinterLintCode.use_build_context_synchronously_async_use, + LinterLintCode.use_build_context_synchronously_wrong_mounted, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var unit = context.definingUnit.unit; if (!unit.inTestDir) { var visitor = _Visitor(this); @@ -942,65 +960,137 @@ class _Visitor extends SimpleAstVisitor { ProtectedFunction('dart.async', 'Future', 'microtask', positional: [0]), // Stream constructors. - ProtectedFunction('dart.async', 'Stream', 'eventTransformed', - positional: [1]), + ProtectedFunction( + 'dart.async', + 'Stream', + 'eventTransformed', + positional: [1], + ), ProtectedFunction('dart.async', 'Stream', 'multi', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'periodic', positional: [1]), // StreamController constructors. - ProtectedFunction('dart.async', 'StreamController', null, - named: ['onListen', 'onPause', 'onResume', 'onCancel']), - ProtectedFunction('dart.async', 'StreamController', 'new', - named: ['onListen', 'onPause', 'onResume', 'onCancel']), - ProtectedFunction('dart.async', 'StreamController', 'broadcast', - named: ['onListen', 'onCancel']), + ProtectedFunction( + 'dart.async', + 'StreamController', + null, + named: ['onListen', 'onPause', 'onResume', 'onCancel'], + ), + ProtectedFunction( + 'dart.async', + 'StreamController', + 'new', + named: ['onListen', 'onPause', 'onResume', 'onCancel'], + ), + ProtectedFunction( + 'dart.async', + 'StreamController', + 'broadcast', + named: ['onListen', 'onCancel'], + ), ]; static const protectedInstanceMethods = [ // Future instance methods. - ProtectedFunction('dart.async', 'Future', 'catchError', - positional: [0], named: ['test']), - ProtectedFunction('dart.async', 'Future', 'onError', - positional: [0], named: ['test']), - ProtectedFunction('dart.async', 'Future', 'then', - positional: [0], named: ['onError']), + ProtectedFunction( + 'dart.async', + 'Future', + 'catchError', + positional: [0], + named: ['test'], + ), + ProtectedFunction( + 'dart.async', + 'Future', + 'onError', + positional: [0], + named: ['test'], + ), + ProtectedFunction( + 'dart.async', + 'Future', + 'then', + positional: [0], + named: ['onError'], + ), ProtectedFunction('dart.async', 'Future', 'timeout', named: ['onTimeout']), ProtectedFunction('dart.async', 'Future', 'whenComplete', positional: [0]), // Stream instance methods. ProtectedFunction('dart.async', 'Stream', 'any', positional: [0]), - ProtectedFunction('dart.async', 'Stream', 'asBroadcastStream', - named: ['onListen', 'onCancel']), + ProtectedFunction( + 'dart.async', + 'Stream', + 'asBroadcastStream', + named: ['onListen', 'onCancel'], + ), ProtectedFunction('dart.async', 'Stream', 'asyncExpand', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'asyncMap', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'distinct', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'expand', positional: [0]), - ProtectedFunction('dart.async', 'Stream', 'firstWhere', - positional: [0], named: ['orElse']), + ProtectedFunction( + 'dart.async', + 'Stream', + 'firstWhere', + positional: [0], + named: ['orElse'], + ), ProtectedFunction('dart.async', 'Stream', 'fold', positional: [1]), ProtectedFunction('dart.async', 'Stream', 'forEach', positional: [0]), - ProtectedFunction('dart.async', 'Stream', 'handleError', - positional: [0], named: ['test']), - ProtectedFunction('dart.async', 'Stream', 'lastWhere', - positional: [0], named: ['orElse']), - ProtectedFunction('dart.async', 'Stream', 'listen', - positional: [0], named: ['onError', 'onDone']), + ProtectedFunction( + 'dart.async', + 'Stream', + 'handleError', + positional: [0], + named: ['test'], + ), + ProtectedFunction( + 'dart.async', + 'Stream', + 'lastWhere', + positional: [0], + named: ['orElse'], + ), + ProtectedFunction( + 'dart.async', + 'Stream', + 'listen', + positional: [0], + named: ['onError', 'onDone'], + ), ProtectedFunction('dart.async', 'Stream', 'map', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'reduce', positional: [0]), - ProtectedFunction('dart.async', 'Stream', 'singleWhere', - positional: [0], named: ['orElse']), + ProtectedFunction( + 'dart.async', + 'Stream', + 'singleWhere', + positional: [0], + named: ['orElse'], + ), ProtectedFunction('dart.async', 'Stream', 'skipWhile', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'takeWhile', positional: [0]), ProtectedFunction('dart.async', 'Stream', 'timeout', named: ['onTimeout']), ProtectedFunction('dart.async', 'Stream', 'where', positional: [0]), // StreamSubscription instance methods. - ProtectedFunction('dart.async', 'StreamSubscription', 'onData', - positional: [0]), - ProtectedFunction('dart.async', 'StreamSubscription', 'onDone', - positional: [0]), - ProtectedFunction('dart.async', 'StreamSubscription', 'onError', - positional: [0]), + ProtectedFunction( + 'dart.async', + 'StreamSubscription', + 'onData', + positional: [0], + ), + ProtectedFunction( + 'dart.async', + 'StreamSubscription', + 'onDone', + positional: [0], + ), + ProtectedFunction( + 'dart.async', + 'StreamSubscription', + 'onError', + positional: [0], + ), ]; static const protectedStaticMethods = [ @@ -1030,9 +1120,10 @@ class _Visitor extends SimpleAstVisitor { if (asyncState.isGuarded) return; if (asyncState == AsyncState.asynchronous) { - var errorCode = asyncStateTracker.hasUnrelatedMountedCheck - ? LinterLintCode.use_build_context_synchronously_wrong_mounted - : LinterLintCode.use_build_context_synchronously_async_use; + var errorCode = + asyncStateTracker.hasUnrelatedMountedCheck + ? LinterLintCode.use_build_context_synchronously_wrong_mounted + : LinterLintCode.use_build_context_synchronously_async_use; rule.reportLint(node, errorCode: errorCode); return; } @@ -1086,9 +1177,17 @@ class _Visitor extends SimpleAstVisitor { if (invocation.constructorName.name?.name == constructor.name && staticType.isSameAs(constructor.type, constructor.library)) { checkPositionalArguments( - constructor.positional, positionalArguments, callback, errorNode); + constructor.positional, + positionalArguments, + callback, + errorNode, + ); checkNamedArguments( - constructor.named, namedArguments, callback, errorNode); + constructor.named, + namedArguments, + callback, + errorNode, + ); } } } @@ -1117,9 +1216,17 @@ class _Visitor extends SimpleAstVisitor { if (invocation.methodName.name == method.name && targetElement.name3 == method.type) { checkPositionalArguments( - method.positional, positionalArguments, callback, errorNode); + method.positional, + positionalArguments, + callback, + errorNode, + ); checkNamedArguments( - method.named, namedArguments, callback, errorNode); + method.named, + namedArguments, + callback, + errorNode, + ); } } } else { @@ -1129,9 +1236,17 @@ class _Visitor extends SimpleAstVisitor { if (invocation.methodName.name == method.name && staticType.element3?.name3 == method.type) { checkPositionalArguments( - method.positional, positionalArguments, callback, errorNode); + method.positional, + positionalArguments, + callback, + errorNode, + ); checkNamedArguments( - method.named, namedArguments, callback, errorNode); + method.named, + namedArguments, + callback, + errorNode, + ); } } } @@ -1140,18 +1255,21 @@ class _Visitor extends SimpleAstVisitor { /// Checks whether [callback] is one of the [namedArguments] for one of the /// protected argument [names] for a protected function. void checkNamedArguments( - List names, - List namedArguments, - Expression callback, - Expression errorNode) { + List names, + List namedArguments, + Expression callback, + Expression errorNode, + ) { for (var named in names) { - var argument = - namedArguments.firstWhereOrNull((a) => a.name.label.name == named); + var argument = namedArguments.firstWhereOrNull( + (a) => a.name.label.name == named, + ); if (argument == null) continue; if (callback == argument.expression) { - rule.reportLint(errorNode, - errorCode: - LinterLintCode.use_build_context_synchronously_async_use); + rule.reportLint( + errorNode, + errorCode: LinterLintCode.use_build_context_synchronously_async_use, + ); } } } @@ -1159,16 +1277,18 @@ class _Visitor extends SimpleAstVisitor { /// Checks whether [callback] is one of the [positionalArguments] for one of /// the protected argument [positions] for a protected function. void checkPositionalArguments( - List positions, - List positionalArguments, - Expression callback, - Expression errorNode) { + List positions, + List positionalArguments, + Expression callback, + Expression errorNode, + ) { for (var position in positions) { if (positionalArguments.length > position && callback == positionalArguments[position]) { - rule.reportLint(errorNode, - errorCode: - LinterLintCode.use_build_context_synchronously_async_use); + rule.reportLint( + errorNode, + errorCode: LinterLintCode.use_build_context_synchronously_async_use, + ); } } } @@ -1343,19 +1463,23 @@ extension ElementExtension on Element2 { // This object can only be guarded by async gaps with a mounted // check on the State. return enclosingElement.lookUpGetter2( - name: 'mounted', library: enclosingElement.library2); + name: 'mounted', + library: enclosingElement.library2, + ); } } - var buildContextElement = switch (self) { - ExecutableElement2() => self.returnType, - VariableElement2() => self.type, - _ => null, - } - ?.element3; + var buildContextElement = + switch (self) { + ExecutableElement2() => self.returnType, + VariableElement2() => self.type, + _ => null, + }?.element3; if (buildContextElement is InterfaceElement2) { return buildContextElement.lookUpGetter2( - name: 'mounted', library: buildContextElement.library2); + name: 'mounted', + library: buildContextElement.library2, + ); } return null; diff --git a/pkg/linter/lib/src/rules/use_colored_box.dart b/pkg/linter/lib/src/rules/use_colored_box.dart index db3f940e0280..326d92193c10 100644 --- a/pkg/linter/lib/src/rules/use_colored_box.dart +++ b/pkg/linter/lib/src/rules/use_colored_box.dart @@ -12,18 +12,16 @@ import '../util/flutter_utils.dart'; const _desc = r'Use `ColoredBox`.'; class UseColoredBox extends LintRule { - UseColoredBox() - : super( - name: LintNames.use_colored_box, - description: _desc, - ); + UseColoredBox() : super(name: LintNames.use_colored_box, description: _desc); @override LintCode get lintCode => LinterLintCode.use_colored_box; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/use_decorated_box.dart b/pkg/linter/lib/src/rules/use_decorated_box.dart index d6fe9ac78cb7..fc8333de8b65 100644 --- a/pkg/linter/lib/src/rules/use_decorated_box.dart +++ b/pkg/linter/lib/src/rules/use_decorated_box.dart @@ -12,17 +12,16 @@ const _desc = r'Use `DecoratedBox`.'; class UseDecoratedBox extends LintRule { UseDecoratedBox() - : super( - name: LintNames.use_decorated_box, - description: _desc, - ); + : super(name: LintNames.use_decorated_box, description: _desc); @override LintCode get lintCode => LinterLintCode.use_decorated_box; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); diff --git a/pkg/linter/lib/src/rules/use_enums.dart b/pkg/linter/lib/src/rules/use_enums.dart index cf6d576943d6..8d213eb5c5dc 100644 --- a/pkg/linter/lib/src/rules/use_enums.dart +++ b/pkg/linter/lib/src/rules/use_enums.dart @@ -14,18 +14,16 @@ import '../extensions.dart'; const _desc = r'Use enums rather than classes that behave like enums.'; class UseEnums extends LintRule { - UseEnums() - : super( - name: LintNames.use_enums, - description: _desc, - ); + UseEnums() : super(name: LintNames.use_enums, description: _desc); @override LintCode get lintCode => LinterLintCode.use_enums; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isEnabled(Feature.enhanced_enums)) return; var visitor = _Visitor(this, context); diff --git a/pkg/linter/lib/src/rules/use_full_hex_values_for_flutter_colors.dart b/pkg/linter/lib/src/rules/use_full_hex_values_for_flutter_colors.dart index cdf71118520d..015287a9b461 100644 --- a/pkg/linter/lib/src/rules/use_full_hex_values_for_flutter_colors.dart +++ b/pkg/linter/lib/src/rules/use_full_hex_values_for_flutter_colors.dart @@ -14,10 +14,10 @@ const _desc = class UseFullHexValuesForFlutterColors extends LintRule { UseFullHexValuesForFlutterColors() - : super( - name: LintNames.use_full_hex_values_for_flutter_colors, - description: _desc, - ); + : super( + name: LintNames.use_full_hex_values_for_flutter_colors, + description: _desc, + ); @override LintCode get lintCode => @@ -25,7 +25,9 @@ class UseFullHexValuesForFlutterColors extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_function_type_syntax_for_parameters.dart b/pkg/linter/lib/src/rules/use_function_type_syntax_for_parameters.dart index 2773ced415e7..975e6b49938b 100644 --- a/pkg/linter/lib/src/rules/use_function_type_syntax_for_parameters.dart +++ b/pkg/linter/lib/src/rules/use_function_type_syntax_for_parameters.dart @@ -11,10 +11,10 @@ const _desc = r'Use generic function type syntax for parameters.'; class UseFunctionTypeSyntaxForParameters extends LintRule { UseFunctionTypeSyntaxForParameters() - : super( - name: LintNames.use_function_type_syntax_for_parameters, - description: _desc, - ); + : super( + name: LintNames.use_function_type_syntax_for_parameters, + description: _desc, + ); @override bool get canUseParsedResult => true; @@ -25,7 +25,9 @@ class UseFunctionTypeSyntaxForParameters extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addFunctionTypedFormalParameter(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_if_null_to_convert_nulls_to_bools.dart b/pkg/linter/lib/src/rules/use_if_null_to_convert_nulls_to_bools.dart index aeb5efc242c9..aa603deff5f5 100644 --- a/pkg/linter/lib/src/rules/use_if_null_to_convert_nulls_to_bools.dart +++ b/pkg/linter/lib/src/rules/use_if_null_to_convert_nulls_to_bools.dart @@ -13,17 +13,19 @@ const _desc = r'Use `??` operators to convert `null`s to `bool`s.'; class UseIfNullToConvertNullsToBools extends LintRule { UseIfNullToConvertNullsToBools() - : super( - name: LintNames.use_if_null_to_convert_nulls_to_bools, - description: _desc, - ); + : super( + name: LintNames.use_if_null_to_convert_nulls_to_bools, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.use_if_null_to_convert_nulls_to_bools; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addBinaryExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_is_even_rather_than_modulo.dart b/pkg/linter/lib/src/rules/use_is_even_rather_than_modulo.dart index b6dc3134eb04..6ce47858c58d 100644 --- a/pkg/linter/lib/src/rules/use_is_even_rather_than_modulo.dart +++ b/pkg/linter/lib/src/rules/use_is_even_rather_than_modulo.dart @@ -13,17 +13,16 @@ const _desc = class UseIsEvenRatherThanModulo extends LintRule { UseIsEvenRatherThanModulo() - : super( - name: LintNames.use_is_even_rather_than_modulo, - description: _desc, - ); + : super(name: LintNames.use_is_even_rather_than_modulo, description: _desc); @override LintCode get lintCode => LinterLintCode.use_is_even_rather_than_modulo; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBinaryExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_key_in_widget_constructors.dart b/pkg/linter/lib/src/rules/use_key_in_widget_constructors.dart index 3c9da8ac798f..a4bd6d971652 100644 --- a/pkg/linter/lib/src/rules/use_key_in_widget_constructors.dart +++ b/pkg/linter/lib/src/rules/use_key_in_widget_constructors.dart @@ -15,17 +15,16 @@ const _desc = r'Use key in widget constructors.'; class UseKeyInWidgetConstructors extends LintRule { UseKeyInWidgetConstructors() - : super( - name: LintNames.use_key_in_widget_constructors, - description: _desc, - ); + : super(name: LintNames.use_key_in_widget_constructors, description: _desc); @override LintCode get lintCode => LinterLintCode.use_key_in_widget_constructors; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); registry.addConstructorDeclaration(this, visitor); @@ -88,9 +87,9 @@ class _Visitor extends SimpleAstVisitor { bool _defineKeyArgument(ArgumentList argumentList) => argumentList.arguments .any((a) => a.correspondingParameter?.name3 == 'key'); - bool _defineKeyParameter(ConstructorElement2 element) => - element.formalParameters - .any((e) => e.name3 == 'key' && _isKeyType(e.type)); + bool _defineKeyParameter(ConstructorElement2 element) => element + .formalParameters + .any((e) => e.name3 == 'key' && _isKeyType(e.type)); bool _hasKeySuperParameterInitializerArg(ConstructorDeclaration node) { for (var parameter in node.parameters.parameterFragments) { diff --git a/pkg/linter/lib/src/rules/use_late_for_private_fields_and_variables.dart b/pkg/linter/lib/src/rules/use_late_for_private_fields_and_variables.dart index e3573f687919..e3a23489da4c 100644 --- a/pkg/linter/lib/src/rules/use_late_for_private_fields_and_variables.dart +++ b/pkg/linter/lib/src/rules/use_late_for_private_fields_and_variables.dart @@ -23,11 +23,11 @@ bool _isPrivateExtension(AstNode parent) { class UseLateForPrivateFieldsAndVariables extends LintRule { UseLateForPrivateFieldsAndVariables() - : super( - name: LintNames.use_late_for_private_fields_and_variables, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.use_late_for_private_fields_and_variables, + description: _desc, + state: const State.experimental(), + ); @override LintCode get lintCode => @@ -35,7 +35,9 @@ class UseLateForPrivateFieldsAndVariables extends LintRule { @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); registry.afterLibrary(this, () => visitor.afterLibrary()); @@ -66,7 +68,8 @@ class _Visitor extends RecursiveAstVisitor { var variableElement = variable.declaredFragment?.element; if (!nullableAccess.contains(variableElement)) { var contextUnit = context.allUnits.firstWhereOrNull( - (u) => u.unit.declaredFragment == libraryFragment); + (u) => u.unit.declaredFragment == libraryFragment, + ); if (contextUnit == null) continue; contextUnit.errorReporter.atNode(variable, rule.lintCode); } @@ -186,7 +189,9 @@ class _Visitor extends RecursiveAstVisitor { /// Checks whether [expression], which must be an [Identifier] or /// [PropertyAccess], and its [canonicalElement], represent a nullable access. void _visitIdentifierOrPropertyAccess( - Expression expression, Element2? canonicalElement) { + Expression expression, + Element2? canonicalElement, + ) { assert(expression is Identifier || expression is PropertyAccess); if (canonicalElement == null) return; diff --git a/pkg/linter/lib/src/rules/use_named_constants.dart b/pkg/linter/lib/src/rules/use_named_constants.dart index b8fef00c14d5..08b1bfdc98f1 100644 --- a/pkg/linter/lib/src/rules/use_named_constants.dart +++ b/pkg/linter/lib/src/rules/use_named_constants.dart @@ -14,17 +14,16 @@ const _desc = r'Use predefined named constants.'; class UseNamedConstants extends LintRule { UseNamedConstants() - : super( - name: LintNames.use_named_constants, - description: _desc, - ); + : super(name: LintNames.use_named_constants, description: _desc); @override LintCode get lintCode => LinterLintCode.use_named_constants; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } @@ -42,10 +41,11 @@ class _Visitor extends SimpleAstVisitor { if (type is! InterfaceType) return; var element = type.element3; if (element is ClassElement2) { - var nodeField = node - .thisOrAncestorOfType() - ?.declaredFragment - ?.element; + var nodeField = + node + .thisOrAncestorOfType() + ?.declaredFragment + ?.element; // avoid diagnostic for fields in the same class having the same value // class A { @@ -59,12 +59,15 @@ class _Visitor extends SimpleAstVisitor { (node.root as CompilationUnit).declaredFragment?.element.library2; if (library == null) return; var value = node.computeConstantValue().value; - for (var field - in element.fields2.where((e) => e.isStatic && e.isConst)) { + for (var field in element.fields2.where( + (e) => e.isStatic && e.isConst, + )) { if (field.isAccessibleIn2(library) && field.computeConstantValue() == value) { - rule.reportLint(node, - arguments: ['${element.name3}.${field.name3}']); + rule.reportLint( + node, + arguments: ['${element.name3}.${field.name3}'], + ); return; } } diff --git a/pkg/linter/lib/src/rules/use_raw_strings.dart b/pkg/linter/lib/src/rules/use_raw_strings.dart index 6cf5b5e3f495..2a9ae38050e9 100644 --- a/pkg/linter/lib/src/rules/use_raw_strings.dart +++ b/pkg/linter/lib/src/rules/use_raw_strings.dart @@ -10,18 +10,16 @@ import '../analyzer.dart'; const _desc = r'Use raw string to avoid escapes.'; class UseRawStrings extends LintRule { - UseRawStrings() - : super( - name: LintNames.use_raw_strings, - description: _desc, - ); + UseRawStrings() : super(name: LintNames.use_raw_strings, description: _desc); @override LintCode get lintCode => LinterLintCode.use_raw_strings; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addSimpleStringLiteral(this, visitor); } @@ -37,8 +35,9 @@ class _Visitor extends SimpleAstVisitor { if (node.isRaw) return; var lexeme = node.literal.lexeme.substring( - node.contentsOffset - node.literal.offset, - node.contentsEnd - node.literal.offset); + node.contentsOffset - node.literal.offset, + node.contentsEnd - node.literal.offset, + ); var hasEscape = false; for (var i = 0; i < lexeme.length - 1; i++) { var current = lexeme[i]; diff --git a/pkg/linter/lib/src/rules/use_rethrow_when_possible.dart b/pkg/linter/lib/src/rules/use_rethrow_when_possible.dart index a7010754c86e..daf52caab636 100644 --- a/pkg/linter/lib/src/rules/use_rethrow_when_possible.dart +++ b/pkg/linter/lib/src/rules/use_rethrow_when_possible.dart @@ -12,17 +12,16 @@ const _desc = r'Use rethrow to rethrow a caught exception.'; class UseRethrowWhenPossible extends LintRule { UseRethrowWhenPossible() - : super( - name: LintNames.use_rethrow_when_possible, - description: _desc, - ); + : super(name: LintNames.use_rethrow_when_possible, description: _desc); @override LintCode get lintCode => LinterLintCode.use_rethrow_when_possible; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addThrowExpression(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_setters_to_change_properties.dart b/pkg/linter/lib/src/rules/use_setters_to_change_properties.dart index 77b456261fdd..316e60457edf 100644 --- a/pkg/linter/lib/src/rules/use_setters_to_change_properties.dart +++ b/pkg/linter/lib/src/rules/use_setters_to_change_properties.dart @@ -16,17 +16,19 @@ const _desc = class UseSettersToChangeProperties extends LintRule { UseSettersToChangeProperties() - : super( - name: LintNames.use_setters_to_change_properties, - description: _desc, - ); + : super( + name: LintNames.use_setters_to_change_properties, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.use_setters_to_change_properties; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_string_buffers.dart b/pkg/linter/lib/src/rules/use_string_buffers.dart index 2badbe85c225..1fd1b8eb97e5 100644 --- a/pkg/linter/lib/src/rules/use_string_buffers.dart +++ b/pkg/linter/lib/src/rules/use_string_buffers.dart @@ -23,17 +23,16 @@ bool _isEmptyInterpolationString(AstNode node) => /// so the bad case is N times slower than the good case. class UseStringBuffers extends LintRule { UseStringBuffers() - : super( - name: LintNames.use_string_buffers, - description: _desc, - ); + : super(name: LintNames.use_string_buffers, description: _desc); @override LintCode get lintCode => LinterLintCode.use_string_buffers; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addDoStatement(this, visitor); registry.addForStatement(this, visitor); diff --git a/pkg/linter/lib/src/rules/use_string_in_part_of_directives.dart b/pkg/linter/lib/src/rules/use_string_in_part_of_directives.dart index fe7b2d511bde..2b88e9294d03 100644 --- a/pkg/linter/lib/src/rules/use_string_in_part_of_directives.dart +++ b/pkg/linter/lib/src/rules/use_string_in_part_of_directives.dart @@ -14,10 +14,10 @@ const _desc = r'Use string in part of directives.'; class UseStringInPartOfDirectives extends LintRule { UseStringInPartOfDirectives() - : super( - name: LintNames.use_string_in_part_of_directives, - description: _desc, - ); + : super( + name: LintNames.use_string_in_part_of_directives, + description: _desc, + ); @override LintCode get lintCode => LinterLintCode.use_string_in_part_of_directives; diff --git a/pkg/linter/lib/src/rules/use_super_parameters.dart b/pkg/linter/lib/src/rules/use_super_parameters.dart index 833baf2c7e42..d2effedec397 100644 --- a/pkg/linter/lib/src/rules/use_super_parameters.dart +++ b/pkg/linter/lib/src/rules/use_super_parameters.dart @@ -16,7 +16,8 @@ const _desc = r'Use super-initializer parameters where possible.'; /// Return a set containing the elements of all of the parameters that are /// referenced in the body of the [constructor]. Set _referencedParameters( - ConstructorDeclaration constructor) { + ConstructorDeclaration constructor, +) { var collector = _ReferencedParameterCollector(); constructor.body.accept(collector); return collector.foundParameters; @@ -24,21 +25,23 @@ Set _referencedParameters( class UseSuperParameters extends LintRule { UseSuperParameters() - : super( - name: LintNames.use_super_parameters, - description: _desc, - state: const State.experimental(), - ); + : super( + name: LintNames.use_super_parameters, + description: _desc, + state: const State.experimental(), + ); @override List get lintCodes => [ - LinterLintCode.use_super_parameters_multiple, - LinterLintCode.use_super_parameters_single - ]; + LinterLintCode.use_super_parameters_multiple, + LinterLintCode.use_super_parameters_single, + ]; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (!context.isEnabled(Feature.super_parameters)) return; var visitor = _Visitor(this, context); @@ -65,9 +68,10 @@ class _Visitor extends SimpleAstVisitor { _Visitor(this.rule, this.context); void check( - ConstructorDeclaration node, - SuperConstructorInvocation superInvocation, - FormalParameterList parameters) { + ConstructorDeclaration node, + SuperConstructorInvocation superInvocation, + FormalParameterList parameters, + ) { var constructorElement = superInvocation.element; if (constructorElement == null) return; @@ -77,7 +81,11 @@ class _Visitor extends SimpleAstVisitor { var referencedParameters = _referencedParameters(node); var identifiers = _checkForConvertiblePositionalParams( - constructorElement, superInvocation, parameters, referencedParameters); + constructorElement, + superInvocation, + parameters, + referencedParameters, + ); // Bail if there are positional params that can't be converted. if (identifiers == null) return; @@ -89,7 +97,11 @@ class _Visitor extends SimpleAstVisitor { if (parameterElement.isNamed && !referencedParameters.contains(parameterElement)) { if (_checkNamedParameter( - parameter, parameterElement, constructorElement, superInvocation)) { + parameter, + parameterElement, + constructorElement, + superInvocation, + )) { var identifier = parameter.name?.lexeme; if (identifier != null) { identifiers.add(identifier); @@ -116,10 +128,11 @@ class _Visitor extends SimpleAstVisitor { /// there are parameters that can't be converted since this will short-circuit /// the lint. List? _checkForConvertiblePositionalParams( - ConstructorElement2 constructorElement, - SuperConstructorInvocation superInvocation, - FormalParameterList parameters, - Set referencedParameters) { + ConstructorElement2 constructorElement, + SuperConstructorInvocation superInvocation, + FormalParameterList parameters, + Set referencedParameters, + ) { var positionalSuperArgs = []; for (var arg in superInvocation.argumentList.arguments) { if (arg is SimpleIdentifier) { @@ -181,12 +194,15 @@ class _Visitor extends SimpleAstVisitor { /// Return `true` if the named [parameter] can be converted into a super /// initializing formal parameter. bool _checkNamedParameter( - FormalParameter parameter, - FormalParameterElement parameterElement, - ConstructorElement2 superConstructor, - SuperConstructorInvocation superInvocation) { - var superParameter = - _correspondingNamedParameter(superConstructor, parameterElement); + FormalParameter parameter, + FormalParameterElement parameterElement, + ConstructorElement2 superConstructor, + SuperConstructorInvocation superInvocation, + ) { + var superParameter = _correspondingNamedParameter( + superConstructor, + parameterElement, + ); if (superParameter == null) return false; bool matchingArgument = false; @@ -221,8 +237,9 @@ class _Visitor extends SimpleAstVisitor { } FormalParameterElement? _correspondingNamedParameter( - ConstructorElement2 superConstructor, - FormalParameterElement thisParameter) { + ConstructorElement2 superConstructor, + FormalParameterElement thisParameter, + ) { for (var superParameter in superConstructor.formalParameters) { if (superParameter.isNamed && superParameter.name3 == thisParameter.name3) { @@ -237,13 +254,19 @@ class _Visitor extends SimpleAstVisitor { var target = node.name ?? node.returnType; if (identifiers.length > 1) { var msg = identifiers.quotedAndCommaSeparatedWithAnd; - rule.reportLintForOffset(target.offset, target.length, - errorCode: LinterLintCode.use_super_parameters_multiple, - arguments: [msg]); + rule.reportLintForOffset( + target.offset, + target.length, + errorCode: LinterLintCode.use_super_parameters_multiple, + arguments: [msg], + ); } else { - rule.reportLintForOffset(target.offset, target.length, - errorCode: LinterLintCode.use_super_parameters_single, - arguments: [identifiers.first]); + rule.reportLintForOffset( + target.offset, + target.length, + errorCode: LinterLintCode.use_super_parameters_single, + arguments: [identifiers.first], + ); } } } diff --git a/pkg/linter/lib/src/rules/use_test_throws_matchers.dart b/pkg/linter/lib/src/rules/use_test_throws_matchers.dart index 221d861b87d2..985b3fb69c0a 100644 --- a/pkg/linter/lib/src/rules/use_test_throws_matchers.dart +++ b/pkg/linter/lib/src/rules/use_test_throws_matchers.dart @@ -12,17 +12,16 @@ const _desc = r'Use throwsA matcher instead of fail().'; class UseTestThrowsMatchers extends LintRule { UseTestThrowsMatchers() - : super( - name: LintNames.use_test_throws_matchers, - description: _desc, - ); + : super(name: LintNames.use_test_throws_matchers, description: _desc); @override LintCode get lintCode => LinterLintCode.use_test_throws_matchers; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addTryStatement(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_to_and_as_if_applicable.dart b/pkg/linter/lib/src/rules/use_to_and_as_if_applicable.dart index a1466f3ad677..5ebece9c635e 100644 --- a/pkg/linter/lib/src/rules/use_to_and_as_if_applicable.dart +++ b/pkg/linter/lib/src/rules/use_to_and_as_if_applicable.dart @@ -22,17 +22,16 @@ bool _isVoid(TypeAnnotation? returnType) => class UseToAndAsIfApplicable extends LintRule { UseToAndAsIfApplicable() - : super( - name: LintNames.use_to_and_as_if_applicable, - description: _desc, - ); + : super(name: LintNames.use_to_and_as_if_applicable, description: _desc); @override LintCode get lintCode => LinterLintCode.use_to_and_as_if_applicable; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addMethodDeclaration(this, visitor); } diff --git a/pkg/linter/lib/src/rules/use_truncating_division.dart b/pkg/linter/lib/src/rules/use_truncating_division.dart index 8fd898820f43..a25c53d06565 100644 --- a/pkg/linter/lib/src/rules/use_truncating_division.dart +++ b/pkg/linter/lib/src/rules/use_truncating_division.dart @@ -12,17 +12,16 @@ const _desc = r'Use truncating division.'; class UseTruncatingDivision extends LintRule { UseTruncatingDivision() - : super( - name: LintNames.use_truncating_division, - description: _desc, - ); + : super(name: LintNames.use_truncating_division, description: _desc); @override LintCode get lintCode => LinterLintCode.use_truncating_division; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addBinaryExpression(this, visitor); } @@ -55,9 +54,11 @@ class _Visitor extends SimpleAstVisitor { var parent = node.parent; if (parent is! ParenthesizedExpression) return; - var outermostParentheses = parent.thisOrAncestorMatching( - (e) => e.parent is! ParenthesizedExpression)! - as ParenthesizedExpression; + var outermostParentheses = + parent.thisOrAncestorMatching( + (e) => e.parent is! ParenthesizedExpression, + )! + as ParenthesizedExpression; var grandParent = outermostParentheses.parent; if (grandParent is MethodInvocation && grandParent.methodName.name == 'toInt' && diff --git a/pkg/linter/lib/src/rules/valid_regexps.dart b/pkg/linter/lib/src/rules/valid_regexps.dart index c208676e5528..33d25ae0bf74 100644 --- a/pkg/linter/lib/src/rules/valid_regexps.dart +++ b/pkg/linter/lib/src/rules/valid_regexps.dart @@ -10,18 +10,16 @@ import '../analyzer.dart'; const _desc = r'Use valid regular expression syntax.'; class ValidRegexps extends LintRule { - ValidRegexps() - : super( - name: LintNames.valid_regexps, - description: _desc, - ); + ValidRegexps() : super(name: LintNames.valid_regexps, description: _desc); @override LintCode get lintCode => LinterLintCode.valid_regexps; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } @@ -43,10 +41,12 @@ class _Visitor extends SimpleAstVisitor { bool isTrue(Expression e) => e is BooleanLiteral && e.value; - var unicode = args.any((arg) => - arg is NamedExpression && - arg.name.label.name == 'unicode' && - isTrue(arg.expression)); + var unicode = args.any( + (arg) => + arg is NamedExpression && + arg.name.label.name == 'unicode' && + isTrue(arg.expression), + ); var sourceExpression = args.first; if (sourceExpression is StringLiteral) { diff --git a/pkg/linter/lib/src/rules/void_checks.dart b/pkg/linter/lib/src/rules/void_checks.dart index 1f32fe3d4913..a0bc2f8137f7 100644 --- a/pkg/linter/lib/src/rules/void_checks.dart +++ b/pkg/linter/lib/src/rules/void_checks.dart @@ -12,18 +12,16 @@ import '../analyzer.dart'; const _desc = r"Don't assign to `void`."; class VoidChecks extends LintRule { - VoidChecks() - : super( - name: LintNames.void_checks, - description: _desc, - ); + VoidChecks() : super(name: LintNames.void_checks, description: _desc); @override LintCode get lintCode => LinterLintCode.void_checks; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context); registry.addAssignedVariablePattern(this, visitor); registry.addAssignmentExpression(this, visitor); @@ -47,7 +45,8 @@ class _Visitor extends SimpleAstVisitor { type.isDartAsyncFuture && type is InterfaceType && isTypeAcceptableWhenExpectingFutureOrVoid( - type.typeArguments.first)) { + type.typeArguments.first, + )) { return true; } @@ -77,8 +76,12 @@ class _Visitor extends SimpleAstVisitor { @override void visitAssignmentExpression(AssignmentExpression node) { var type = node.writeType; - _check(type, node.rightHandSide.staticType, node, - checkedNode: node.rightHandSide); + _check( + type, + node.rightHandSide.staticType, + node, + checkedNode: node.rightHandSide, + ); } @override @@ -102,29 +105,46 @@ class _Visitor extends SimpleAstVisitor { @override void visitReturnStatement(ReturnStatement node) { - var parent = node.thisOrAncestorMatching((e) => - e is FunctionExpression || - e is MethodDeclaration || - e is FunctionDeclaration); + var parent = node.thisOrAncestorMatching( + (e) => + e is FunctionExpression || + e is MethodDeclaration || + e is FunctionDeclaration, + ); if (parent is FunctionExpression) { var type = parent.staticType; if (type is FunctionType) { - _check(type.returnType, node.expression?.staticType, node, - checkedNode: node.expression); + _check( + type.returnType, + node.expression?.staticType, + node, + checkedNode: node.expression, + ); } } else if (parent is MethodDeclaration) { - _check(parent.declaredFragment?.element.returnType, - node.expression?.staticType, node, - checkedNode: node.expression); + _check( + parent.declaredFragment?.element.returnType, + node.expression?.staticType, + node, + checkedNode: node.expression, + ); } else if (parent is FunctionDeclaration) { var parentElement = parent.declaredFragment?.element; - _check(parentElement?.returnType, node.expression?.staticType, node, - checkedNode: node.expression); + _check( + parentElement?.returnType, + node.expression?.staticType, + node, + checkedNode: node.expression, + ); } } - void _check(DartType? expectedType, DartType? type, AstNode node, - {AstNode? checkedNode}) { + void _check( + DartType? expectedType, + DartType? type, + AstNode node, { + AstNode? checkedNode, + }) { checkedNode ??= node; if (expectedType == null || type == null) { return; @@ -144,13 +164,19 @@ class _Visitor extends SimpleAstVisitor { checkedNode.body is! ExpressionFunctionBody && expectedType is FunctionType && type is FunctionType) { - _check(expectedType.returnType, type.returnType, node, - checkedNode: checkedNode); + _check( + expectedType.returnType, + type.returnType, + node, + checkedNode: checkedNode, + ); } } void _checkArgs( - NodeList args, List parameters) { + NodeList args, + List parameters, + ) { for (var arg in args) { var parameterElement = arg.correspondingParameter; if (parameterElement != null) { diff --git a/pkg/linter/lib/src/test_utilities/lint_driver.dart b/pkg/linter/lib/src/test_utilities/lint_driver.dart index ae329f200bf7..72c9e1e7e03d 100644 --- a/pkg/linter/lib/src/test_utilities/lint_driver.dart +++ b/pkg/linter/lib/src/test_utilities/lint_driver.dart @@ -45,8 +45,9 @@ class LintDriver { }) { analysisOptions.lint = true; analysisOptions.warning = false; - analysisOptions.lintRules = - _options.enabledRules.toList(growable: false); + analysisOptions.lintRules = _options.enabledRules.toList( + growable: false, + ); }, enableLintRuleTiming: _options.enableTiming, ); diff --git a/pkg/linter/lib/src/test_utilities/linter_options.dart b/pkg/linter/lib/src/test_utilities/linter_options.dart index 94ce57c9887d..c957c4ea1a35 100644 --- a/pkg/linter/lib/src/test_utilities/linter_options.dart +++ b/pkg/linter/lib/src/test_utilities/linter_options.dart @@ -16,7 +16,6 @@ class LinterOptions { /// Whether to gather timing data during analysis. bool enableTiming = false; - LinterOptions({ - Iterable? enabledRules, - }) : enabledRules = enabledRules ?? Registry.ruleRegistry; + LinterOptions({Iterable? enabledRules}) + : enabledRules = enabledRules ?? Registry.ruleRegistry; } diff --git a/pkg/linter/lib/src/test_utilities/test_linter.dart b/pkg/linter/lib/src/test_utilities/test_linter.dart index 381c74af80a8..0ef98a132b5b 100644 --- a/pkg/linter/lib/src/test_utilities/test_linter.dart +++ b/pkg/linter/lib/src/test_utilities/test_linter.dart @@ -34,11 +34,9 @@ class TestLinter implements AnalysisErrorListener { final LinterOptions options; final file_system.ResourceProvider _resourceProvider; - TestLinter( - this.options, { - file_system.ResourceProvider? resourceProvider, - }) : _resourceProvider = - resourceProvider ?? file_system.PhysicalResourceProvider.INSTANCE; + TestLinter(this.options, {file_system.ResourceProvider? resourceProvider}) + : _resourceProvider = + resourceProvider ?? file_system.PhysicalResourceProvider.INSTANCE; Future> lintFiles(List files) async { var errors = []; diff --git a/pkg/linter/lib/src/util/dart_type_utilities.dart b/pkg/linter/lib/src/util/dart_type_utilities.dart index 03515823af35..390b804b0c01 100644 --- a/pkg/linter/lib/src/util/dart_type_utilities.dart +++ b/pkg/linter/lib/src/util/dart_type_utilities.dart @@ -12,7 +12,9 @@ import '../ast.dart'; import '../extensions.dart'; bool argumentsMatchParameters( - NodeList arguments, NodeList parameters) { + NodeList arguments, + NodeList parameters, +) { var namedParameters = {}; var namedArguments = {}; var positionalParameters = []; @@ -93,7 +95,9 @@ bool canonicalElementsAreEqual(Element2? element1, Element2? element2) => /// and 3 are considered to be equal, even though `A.b` may have side effects /// which alter the returned value. bool canonicalElementsFromIdentifiersAreEqual( - Expression? rawExpression1, Expression? rawExpression2) { + Expression? rawExpression1, + Expression? rawExpression2, +) { if (rawExpression1 == null || rawExpression2 == null) return false; var expression1 = rawExpression1.unParenthesized; @@ -101,16 +105,22 @@ bool canonicalElementsFromIdentifiersAreEqual( if (expression1 is SimpleIdentifier) { return expression2 is SimpleIdentifier && - canonicalElementsAreEqual(getWriteOrReadElement(expression1), - getWriteOrReadElement(expression2)); + canonicalElementsAreEqual( + getWriteOrReadElement(expression1), + getWriteOrReadElement(expression2), + ); } if (expression1 is PrefixedIdentifier) { return expression2 is PrefixedIdentifier && canonicalElementsAreEqual( - expression1.prefix.element, expression2.prefix.element) && - canonicalElementsAreEqual(getWriteOrReadElement(expression1.identifier), - getWriteOrReadElement(expression2.identifier)); + expression1.prefix.element, + expression2.prefix.element, + ) && + canonicalElementsAreEqual( + getWriteOrReadElement(expression1.identifier), + getWriteOrReadElement(expression2.identifier), + ); } if (expression1 is PropertyAccess && expression2 is PropertyAccess) { @@ -118,8 +128,9 @@ bool canonicalElementsFromIdentifiersAreEqual( var target2 = expression2.target; return canonicalElementsFromIdentifiersAreEqual(target1, target2) && canonicalElementsAreEqual( - getWriteOrReadElement(expression1.propertyName), - getWriteOrReadElement(expression2.propertyName)); + getWriteOrReadElement(expression1.propertyName), + getWriteOrReadElement(expression2.propertyName), + ); } return false; @@ -172,11 +183,16 @@ bool typesAreUnrelated( } if (promotedLeftType is InterfaceType && promotedRightType is InterfaceType) { return typeSystem.interfaceTypesAreUnrelated( - promotedLeftType, promotedRightType); + promotedLeftType, + promotedRightType, + ); } else if (promotedLeftType is TypeParameterType && promotedRightType is TypeParameterType) { - return typesAreUnrelated(typeSystem, promotedLeftType.element3.bound, - promotedRightType.element3.bound); + return typesAreUnrelated( + typeSystem, + promotedLeftType.element3.bound, + promotedRightType.element3.bound, + ); } else if (promotedLeftType is FunctionType) { if (_isFunctionTypeUnrelatedToType(promotedLeftType, promotedRightType)) { return true; @@ -200,8 +216,11 @@ bool _isFunctionTypeUnrelatedToType(FunctionType type1, DartType type2) { if (type2 is InterfaceType) { var element2 = type2.element3; if (element2 is ClassElement2 && - element2.thisType - .lookUpMethod3('call', element2.library2, concrete: true) != + element2.thisType.lookUpMethod3( + 'call', + element2.library2, + concrete: true, + ) != null) { return false; } @@ -233,7 +252,9 @@ class InterfaceTypeDefinition { extension on TypeSystem { bool interfaceTypesAreUnrelated( - InterfaceType leftType, InterfaceType rightType) { + InterfaceType leftType, + InterfaceType rightType, + ) { var leftElement = leftType.element3; var rightElement = rightType.element3; if (leftElement == rightElement) { @@ -251,7 +272,10 @@ extension on TypeSystem { // If any of the pair-wise type arguments are unrelated, then // [leftType] and [rightType] are unrelated. if (typesAreUnrelated( - this, leftTypeArguments[i], rightTypeArguments[i])) { + this, + leftTypeArguments[i], + rightTypeArguments[i], + )) { return true; } } diff --git a/pkg/linter/lib/src/util/flutter_utils.dart b/pkg/linter/lib/src/util/flutter_utils.dart index 3ac5bbefcd44..f6b49aa528fd 100644 --- a/pkg/linter/lib/src/util/flutter_utils.dart +++ b/pkg/linter/lib/src/util/flutter_utils.dart @@ -81,14 +81,16 @@ class _Flutter { final Uri _uriFoundation; _Flutter(this.packageName, String uriPrefix) - : widgetsUri = '$uriPrefix/widgets.dart', - _uriBasic = Uri.parse('$uriPrefix/src/widgets/basic.dart'), - _uriContainer = Uri.parse('$uriPrefix/src/widgets/container.dart'), - _uriFramework = Uri.parse('$uriPrefix/src/widgets/framework.dart'), - _uriFoundation = Uri.parse('$uriPrefix/src/foundation/constants.dart'); - - bool hasWidgetAsAscendant(InterfaceElement2? element, - [Set? alreadySeen]) { + : widgetsUri = '$uriPrefix/widgets.dart', + _uriBasic = Uri.parse('$uriPrefix/src/widgets/basic.dart'), + _uriContainer = Uri.parse('$uriPrefix/src/widgets/container.dart'), + _uriFramework = Uri.parse('$uriPrefix/src/widgets/framework.dart'), + _uriFoundation = Uri.parse('$uriPrefix/src/foundation/constants.dart'); + + bool hasWidgetAsAscendant( + InterfaceElement2? element, [ + Set? alreadySeen, + ]) { if (element == null) return false; if (isExactly(element, _nameWidget, _uriFramework)) return true; @@ -96,9 +98,10 @@ class _Flutter { alreadySeen ??= {}; if (!alreadySeen.add(element)) return false; - var type = element.firstFragment.isAugmentation - ? element.thisType - : element.supertype; + var type = + element.firstFragment.isAugmentation + ? element.thisType + : element.supertype; return hasWidgetAsAscendant(type?.element3, alreadySeen); } @@ -134,13 +137,15 @@ class _Flutter { bool isState(InterfaceElement2 element) => isExactly(element, _nameState, _uriFramework) || - element.allSupertypes - .any((type) => isExactly(type.element3, _nameState, _uriFramework)); + element.allSupertypes.any( + (type) => isExactly(type.element3, _nameState, _uriFramework), + ); bool isStatefulWidget(ClassElement2 element) => isExactly(element, _nameStatefulWidget, _uriFramework) || - element.allSupertypes.any((type) => - isExactly(type.element3, _nameStatefulWidget, _uriFramework)); + element.allSupertypes.any( + (type) => isExactly(type.element3, _nameStatefulWidget, _uriFramework), + ); bool isWidget(InterfaceElement2 element) { if (isExactly(element, _nameWidget, _uriFramework)) { @@ -171,8 +176,9 @@ extension InterfaceElementExtension2 on InterfaceElement2? { if (isExactlyWidget) return true; - return self.allSupertypes - .any((type) => type.element3._isExactly(_nameWidget, _uriFramework)); + return self.allSupertypes.any( + (type) => type.element3._isExactly(_nameWidget, _uriFramework), + ); } /// Whether this is the exact [type] defined in the file with the given [uri]. @@ -184,7 +190,9 @@ extension InterfaceElementExtension2 on InterfaceElement2? { } static bool _hasWidgetAsAscendant( - InterfaceElement2? element, Set alreadySeen) { + InterfaceElement2? element, + Set alreadySeen, + ) { if (element == null) return false; if (element.isExactlyWidget) return true; diff --git a/pkg/linter/lib/src/util/leak_detector_visitor.dart b/pkg/linter/lib/src/util/leak_detector_visitor.dart index 6ae978f8553e..31608628947a 100644 --- a/pkg/linter/lib/src/util/leak_detector_visitor.dart +++ b/pkg/linter/lib/src/util/leak_detector_visitor.dart @@ -18,50 +18,54 @@ _VisitVariableDeclaration _buildVariableReporter( LintRule rule, Map predicates, { required _VariableType variableType, -}) => - (VariableDeclaration variable) { - if (variable.equals != null && variable.initializer is SimpleIdentifier) { - return; - } +}) => (VariableDeclaration variable) { + if (variable.equals != null && variable.initializer is SimpleIdentifier) { + return; + } - var variableElement = variable.declaredFragment?.element; - if (variableElement == null) { - return; - } + var variableElement = variable.declaredFragment?.element; + if (variableElement == null) { + return; + } - if (!predicates.keys - .any((DartTypePredicate p) => p(variableElement.type))) { - return; - } + if (!predicates.keys.any((DartTypePredicate p) => p(variableElement.type))) { + return; + } - var visitor = _ValidUseVisitor( - variable, - variableElement, - predicates, - variableType: variableType, - ); - container.accept(visitor); + var visitor = _ValidUseVisitor( + variable, + variableElement, + predicates, + variableType: variableType, + ); + container.accept(visitor); - if (visitor.containsValidUse) { - return; - } + if (visitor.containsValidUse) { + return; + } - rule.reportLint(variable); - }; + rule.reportLint(variable); +}; /// Whether any of the [predicates] applies to [methodName] and holds true for /// [type]. -bool _hasMatch(Map predicates, DartType type, - String methodName) => - predicates.keys.any((p) => predicates[p] == methodName && p(type)); +bool _hasMatch( + Map predicates, + DartType type, + String methodName, +) => predicates.keys.any((p) => predicates[p] == methodName && p(type)); bool _isElementEqualToVariable( - Element2? propertyElement, VariableElement2? variableElement) => + Element2? propertyElement, + VariableElement2? variableElement, +) => propertyElement == variableElement || propertyElement.matches(variableElement); bool _isInvocationThroughCascadeExpression( - MethodInvocation invocation, VariableElement2 variableElement) { + MethodInvocation invocation, + VariableElement2 variableElement, +) { if (invocation.realTarget is! SimpleIdentifier) { return false; } @@ -74,7 +78,9 @@ bool _isInvocationThroughCascadeExpression( } bool _isPostfixExpressionOperandEqualToVariable( - AstNode? n, VariableElement2 variableElement) { + AstNode? n, + VariableElement2 variableElement, +) { if (n is PostfixExpression) { var operand = n.operand; return operand is SimpleIdentifier && @@ -84,7 +90,9 @@ bool _isPostfixExpressionOperandEqualToVariable( } bool _isPropertyAccessThroughThis( - Expression? n, VariableElement2 variableElement) { + Expression? n, + VariableElement2 variableElement, +) { if (n is! PropertyAccess) { return false; } @@ -99,7 +107,9 @@ bool _isPropertyAccessThroughThis( } bool _isSimpleIdentifierElementEqualToVariable( - AstNode? n, VariableElement2 variableElement) => + AstNode? n, + VariableElement2 variableElement, +) => n is SimpleIdentifier && _isElementEqualToVariable(n.element, variableElement); @@ -121,12 +131,14 @@ abstract class LeakDetectorProcessors extends SimpleAstVisitor { if (unit != null) { // When visiting a field declaration, we want to check tree under the // containing unit for ConstructorFieldInitializers and FieldFormalParameters. - node.fields.variables.forEach(_buildVariableReporter( - unit, - rule, - predicates, - variableType: _VariableType.field, - )); + node.fields.variables.forEach( + _buildVariableReporter( + unit, + rule, + predicates, + variableType: _VariableType.field, + ), + ); } } @@ -137,12 +149,14 @@ abstract class LeakDetectorProcessors extends SimpleAstVisitor { // When visiting a variable declaration, we want to check tree under the // containing function for ReturnStatements. If an interesting variable // is returned, don't report it. - node.variables.variables.forEach(_buildVariableReporter( - function, - rule, - predicates, - variableType: _VariableType.local, - )); + node.variables.variables.forEach( + _buildVariableReporter( + function, + rule, + predicates, + variableType: _VariableType.local, + ), + ); } } } @@ -186,7 +200,9 @@ class _ValidUseVisitor extends RecursiveAstVisitor { // Being assigned another reference. if (node.rightHandSide is SimpleIdentifier) { if (_isElementEqualToVariable( - node.writeElement2, variable.declaredFragment?.element)) { + node.writeElement2, + variable.declaredFragment?.element, + )) { containsValidUse = true; return; } @@ -227,9 +243,13 @@ class _ValidUseVisitor extends RecursiveAstVisitor { void visitMethodInvocation(MethodInvocation node) { if (_hasMatch(predicates, variableElement.type, node.methodName.name) && (_isSimpleIdentifierElementEqualToVariable( - node.realTarget, variableElement) || + node.realTarget, + variableElement, + ) || _isPostfixExpressionOperandEqualToVariable( - node.realTarget, variableElement) || + node.realTarget, + variableElement, + ) || _isPropertyAccessThroughThis(node.realTarget, variableElement) || (node.thisOrAncestorMatching((a) => a == variable) != null))) { containsValidUse = true; @@ -262,7 +282,10 @@ class _ValidUseVisitor extends RecursiveAstVisitor { void visitPrefixedIdentifier(PrefixedIdentifier node) { if (node.prefix.element == variableElement && _hasMatch( - predicates, variableElement.type, node.identifier.token.lexeme)) { + predicates, + variableElement.type, + node.identifier.token.lexeme, + )) { containsValidUse = true; return; } @@ -284,14 +307,11 @@ class _ValidUseVisitor extends RecursiveAstVisitor { } /// The type of variable being assessed. -enum _VariableType { - field, - local; -} +enum _VariableType { field, local } extension on Element2? { bool matches(VariableElement2? variable) => switch (this) { - PropertyAccessorElement2(:var variable3) => variable3 == variable, - _ => false, - }; + PropertyAccessorElement2(:var variable3) => variable3 == variable, + _ => false, + }; } diff --git a/pkg/linter/lib/src/util/obvious_types.dart b/pkg/linter/lib/src/util/obvious_types.dart index 66928b6325c1..590209f12416 100644 --- a/pkg/linter/lib/src/util/obvious_types.dart +++ b/pkg/linter/lib/src/util/obvious_types.dart @@ -81,8 +81,9 @@ extension DartTypeExtensions on DartType? { var self = this; // Enable promotion. if (self == null) return null; if (self is InterfaceType) { - var iterableInterfaces = - self.implementedInterfaces.where((type) => type.isDartCoreIterable); + var iterableInterfaces = self.implementedInterfaces.where( + (type) => type.isDartCoreIterable, + ); if (iterableInterfaces.length == 1) { return iterableInterfaces.first.typeArguments.first; } @@ -94,8 +95,9 @@ extension DartTypeExtensions on DartType? { var self = this; // Enable promotion. if (self == null) return null; if (self is InterfaceType) { - var mapInterfaces = - self.implementedInterfaces.where((type) => type.isDartCoreMap); + var mapInterfaces = self.implementedInterfaces.where( + (type) => type.isDartCoreMap, + ); if (mapInterfaces.length == 1) { var [key, value] = mapInterfaces.first.typeArguments; return (key: key, value: value); @@ -118,7 +120,7 @@ extension ExpressionExtensions on Expression { DartType? theObviousType, theObviousKeyType, theObviousValueType; NodeList elements = switch (self) { ListLiteral() => self.elements, - SetOrMapLiteral() => self.elements + SetOrMapLiteral() => self.elements, }; for (var element in elements) { if (element.hasObviousType) { diff --git a/pkg/linter/lib/src/util/scope.dart b/pkg/linter/lib/src/util/scope.dart index d1e613d4d7ac..6e6b891285a8 100644 --- a/pkg/linter/lib/src/util/scope.dart +++ b/pkg/linter/lib/src/util/scope.dart @@ -48,14 +48,14 @@ class LinterNameInScopeResolutionResult { final _LinterNameInScopeResolutionResultState _state; const LinterNameInScopeResolutionResult._differentName(this.element) - : _state = _LinterNameInScopeResolutionResultState.differentName; + : _state = _LinterNameInScopeResolutionResultState.differentName; const LinterNameInScopeResolutionResult._none() - : element = null, - _state = _LinterNameInScopeResolutionResultState.none; + : element = null, + _state = _LinterNameInScopeResolutionResultState.none; const LinterNameInScopeResolutionResult._requestedName(this.element) - : _state = _LinterNameInScopeResolutionResultState.requestedName; + : _state = _LinterNameInScopeResolutionResultState.requestedName; bool get isDifferentName => _state == _LinterNameInScopeResolutionResultState.differentName; @@ -79,5 +79,5 @@ enum _LinterNameInScopeResolutionResultState { /// Indicates that an element with the same basename, but different name /// was found. - differentName + differentName, } diff --git a/pkg/linter/lib/src/util/variance_checker.dart b/pkg/linter/lib/src/util/variance_checker.dart index 57b3e85024f7..2cd17e5098b6 100644 --- a/pkg/linter/lib/src/util/variance_checker.dart +++ b/pkg/linter/lib/src/util/variance_checker.dart @@ -20,10 +20,10 @@ enum Variance { inout; Variance get inverse => switch (this) { - out => in_, - in_ => out, - inout => inout, - }; + out => in_, + in_ => out, + inout => inout, + }; } /// Iterate over a type annotation, keeping track of variance. @@ -117,7 +117,9 @@ abstract class VarianceChecker { /// Check [formalParameter], using [variance] as the initial variance. void checkFormalParameter( - Variance variance, FormalParameter formalParameter) { + Variance variance, + FormalParameter formalParameter, + ) { if (!formalParameter.isExplicitlyTyped) return; switch (formalParameter) { case SuperFormalParameter(:var type): @@ -125,10 +127,10 @@ abstract class VarianceChecker { case SimpleFormalParameter(:var type): check(variance, type); case FunctionTypedFormalParameter( - :var returnType, - :var parameters, - :var typeParameters - ): + :var returnType, + :var parameters, + :var typeParameters, + ): check(variance, returnType); typeParameters?.typeParameters.forEach(checkBound); for (var parameter in parameters.parameters) { diff --git a/pkg/linter/lib/src/utils.dart b/pkg/linter/lib/src/utils.dart index 68a1bacbfa28..e5192b8b65b8 100644 --- a/pkg/linter/lib/src/utils.dart +++ b/pkg/linter/lib/src/utils.dart @@ -20,8 +20,9 @@ final _identifier = RegExp(r'^[_$a-z]+(\d[_a-z\d]*)?$', caseSensitive: false); // * an upper case letter followed by a word tail, or // * an underscore and then a digit followed by a word tail. // * and potentially ended by a single optional underscore. -final _lowerCamelCase = - RegExp(r'^_*[?$a-z][a-z\d?$]*(?:(?:[A-Z]|_\d)[a-z\d?$]*)*_?$'); +final _lowerCamelCase = RegExp( + r'^_*[?$a-z][a-z\d?$]*(?:(?:[A-Z]|_\d)[a-z\d?$]*)*_?$', +); // A lower-case underscore (snake-case) is here defined as: // * A sequence of lower-case letters, digits and underscores, @@ -31,16 +32,18 @@ final _lowerCamelCase = final _lowerCaseUnderScore = RegExp(r'^[a-z](?:_?[a-z\d])*$'); @Deprecated('Prefer: ascii_utils.isValidFileName') -final _lowerCaseUnderScoreWithDots = - RegExp(r'^_?[_a-z\d]*(?:\.[a-z][_a-z\d]*)*$'); +final _lowerCaseUnderScoreWithDots = RegExp( + r'^_?[_a-z\d]*(?:\.[a-z][_a-z\d]*)*$', +); // A lower-case underscored (snake-case) with leading underscores is defined as // * An optional leading sequence of any number of underscores, // * followed by a sequence of lower-case letters, digits and underscores, // * with no two adjacent underscores, // * and not ending in an underscore. -final _lowerCaseUnderScoreWithLeadingUnderscores = - RegExp(r'^_*[a-z](?:_?[a-z\d])*$'); +final _lowerCaseUnderScoreWithLeadingUnderscores = RegExp( + r'^_*[a-z](?:_?[a-z\d])*$', +); final _pubspec = RegExp(r'^_?pubspec\.yaml$'); @@ -75,8 +78,8 @@ bool isLowerCaseUnderScore(String id) => _lowerCaseUnderScore.hasMatch(id); /// Returns `true` if this [id] is `lower_camel_case_with_underscores_or.dots`. bool isLowerCaseUnderScoreWithDots(String id) => - // ignore: deprecated_member_use_from_same_package - _lowerCaseUnderScoreWithDots.hasMatch(id); +// ignore: deprecated_member_use_from_same_package +_lowerCaseUnderScoreWithDots.hasMatch(id); /// Returns `true` if this [fileName] is a Pubspec file. bool isPubspecFileName(String fileName) => _pubspec.hasMatch(fileName); diff --git a/pkg/linter/pubspec.yaml b/pkg/linter/pubspec.yaml index 892aaea06729..4db335d6ddd4 100644 --- a/pkg/linter/pubspec.yaml +++ b/pkg/linter/pubspec.yaml @@ -7,7 +7,7 @@ description: >- This package is not intended to be used directly. environment: - sdk: ^3.3.0 + sdk: '>=3.7.0-edge <4.0.0' # Use 'any' constraints here; we get our versions from the DEPS file. dependencies: diff --git a/pkg/linter/test/ascii_utils_test.dart b/pkg/linter/test/ascii_utils_test.dart index e9536be3b627..318889c651fe 100644 --- a/pkg/linter/test/ascii_utils_test.dart +++ b/pkg/linter/test/ascii_utils_test.dart @@ -25,20 +25,11 @@ void main() { }); group('isJustUnderscores', () { - test( - 'empty is not', - () => expect(''.isJustUnderscores, isFalse), - ); + test('empty is not', () => expect(''.isJustUnderscores, isFalse)); - test( - 'non-underscore is not', - () => expect('A'.isJustUnderscores, isFalse), - ); + test('non-underscore is not', () => expect('A'.isJustUnderscores, isFalse)); - test( - 'one underscore is', - () => expect('_'.isJustUnderscores, isTrue), - ); + test('one underscore is', () => expect('_'.isJustUnderscores, isTrue)); test( 'multiple underscores is', diff --git a/pkg/linter/test/engine_test.dart b/pkg/linter/test/engine_test.dart index c543f0364c33..b043ac0d8a12 100644 --- a/pkg/linter/test/engine_test.dart +++ b/pkg/linter/test/engine_test.dart @@ -22,8 +22,10 @@ void defineLinterEngineTests() { expect(CamelCaseString('Foo').humanized, 'Foo'); }); test('validation', () { - expect(() => CamelCaseString('foo'), - throwsA(TypeMatcher())); + expect( + () => CamelCaseString('foo'), + throwsA(TypeMatcher()), + ); }); test('toString', () { expect(CamelCaseString('FooBar').toString(), 'FooBar'); diff --git a/pkg/linter/test/formatter_test.dart b/pkg/linter/test/formatter_test.dart index 7535ac3b65e1..0569f3aa31d7 100644 --- a/pkg/linter/test/formatter_test.dart +++ b/pkg/linter/test/formatter_test.dart @@ -47,7 +47,11 @@ var z = 33; var source = MockSource(sourcePath); var error = AnalysisError.tmp( - source: source, offset: 10, length: 3, errorCode: code); + source: source, + offset: 10, + length: 3, + errorCode: code, + ); info = AnalysisErrorInfo([error], lineInfo); out = StringBuffer(); @@ -69,12 +73,15 @@ files analyzed, 1 issue found.'''); test('stats', () { out.clear(); ReportFormatter([info], out).write(); - expect(out.toString(), startsWith('''$sourcePath 3:2 [test] MSG + expect( + out.toString(), + startsWith('''$sourcePath 3:2 [test] MSG var z = 33; ^^^ files analyzed, 1 issue found. -''')); +'''), + ); }); }); }); diff --git a/pkg/linter/test/lint_code_test.dart b/pkg/linter/test/lint_code_test.dart index 4c76a35182b2..2f76b0e1bd30 100644 --- a/pkg/linter/test/lint_code_test.dart +++ b/pkg/linter/test/lint_code_test.dart @@ -11,22 +11,31 @@ void main() { group('lint code', () { group('creation', () { test('without published diagnostic docs', () { - expect(_customCode.url, - equals('https://dart.dev/lints/${_customCode.name}')); + expect( + _customCode.url, + equals('https://dart.dev/lints/${_customCode.name}'), + ); }); test('with published diagnostic docs', () { - expect(_customCodeWithDocs.url, - equals('https://dart.dev/diagnostics/${_customCodeWithDocs.name}')); + expect( + _customCodeWithDocs.url, + equals('https://dart.dev/diagnostics/${_customCodeWithDocs.name}'), + ); }); }); }); } const LintCode _customCode = LinterLintCode( - 'hash_and_equals', 'Override `==` if overriding `hashCode`.', - correctionMessage: 'Implement `==`.'); + 'hash_and_equals', + 'Override `==` if overriding `hashCode`.', + correctionMessage: 'Implement `==`.', +); const LintCode _customCodeWithDocs = LinterLintCode( - 'hash_and_equals', 'Override `==` if overriding `hashCode`.', - correctionMessage: 'Implement `==`.', hasPublishedDocs: true); + 'hash_and_equals', + 'Override `==` if overriding `hashCode`.', + correctionMessage: 'Implement `==`.', + hasPublishedDocs: true, +); diff --git a/pkg/linter/test/mocks.dart b/pkg/linter/test/mocks.dart index bf0fd2381efb..66e8048b9c29 100644 --- a/pkg/linter/test/mocks.dart +++ b/pkg/linter/test/mocks.dart @@ -88,9 +88,9 @@ class TestErrorCode extends ErrorCode { late ErrorType type; TestErrorCode(String name, String message) - : super( - problemMessage: message, - name: name, - uniqueName: 'TestErrorCode.$name', - ); + : super( + problemMessage: message, + name: name, + uniqueName: 'TestErrorCode.$name', + ); } diff --git a/pkg/linter/test/rule_test.dart b/pkg/linter/test/rule_test.dart index b028f23771f1..d2150c933b9a 100644 --- a/pkg/linter/test/rule_test.dart +++ b/pkg/linter/test/rule_test.dart @@ -32,7 +32,7 @@ void defineRuleUnitTests() { 'foo_bar', '\$foo', 'foo\$Bar', - 'foo\$' + 'foo\$', ]; testEach(good, isValidDartIdentifier, isTrue); var bad = ['if', '42', '3', '2f']; diff --git a/pkg/linter/test/rule_test_support.dart b/pkg/linter/test/rule_test_support.dart index 4da92f3ce694..d61bd513761d 100644 --- a/pkg/linter/test/rule_test_support.dart +++ b/pkg/linter/test/rule_test_support.dart @@ -51,9 +51,7 @@ String analysisOptionsContent({ } buffer.writeln(' optional-checks:'); - buffer.writeln( - ' propagate-linter-exceptions: true', - ); + buffer.writeln(' propagate-linter-exceptions: true'); buffer.writeln('linter:'); buffer.writeln(' rules:'); @@ -64,9 +62,12 @@ String analysisOptionsContent({ return buffer.toString(); } -ExpectedDiagnostic error(ErrorCode code, int offset, int length, - {Pattern? messageContains}) => - _ExpectedError(code, offset, length, messageContains: messageContains); +ExpectedDiagnostic error( + ErrorCode code, + int offset, + int length, { + Pattern? messageContains, +}) => _ExpectedError(code, offset, length, messageContains: messageContains); // TODO(srawlins): This is duplicate with // pkg/analyzer/test/src/dart/resolution/context_collection_resolution.dart. @@ -109,8 +110,8 @@ class ExpectedDiagnostic { this._length, { Pattern? messageContains, Pattern? correctionContains, - }) : _messageContains = messageContains, - _correctionContains = correctionContains; + }) : _messageContains = messageContains, + _correctionContains = correctionContains; /// Whether the [error] matches this description of what it's expected to be. bool matches(AnalysisError error) { @@ -153,14 +154,13 @@ abstract class LintRuleTest extends PubPackageResolutionTest { int length, { Pattern? messageContains, Pattern? correctionContains, - }) => - _ExpectedLint( - lintRule, - offset, - length, - messageContains: messageContains, - correctionContains: correctionContains, - ); + }) => _ExpectedLint( + lintRule, + offset, + length, + messageContains: messageContains, + correctionContains: correctionContains, + ); } class PubPackageResolutionTest extends _ContextResolutionTest { @@ -204,7 +204,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { /// /// The order in which the diagnostics were gathered is ignored. Future assertDiagnostics( - String content, List expectedDiagnostics) async { + String content, + List expectedDiagnostics, + ) async { addTestFile(content); await resolveTestFile(); await _assertDiagnosticsIn(_errors, expectedDiagnostics); @@ -216,7 +218,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { /// /// The order in which the diagnostics were gathered is ignored. Future assertDiagnosticsInFile( - String path, List expectedDiagnostics) async { + String path, + List expectedDiagnostics, + ) async { await _resolveFile(path); await _assertDiagnosticsIn(_errors, expectedDiagnostics); } @@ -227,8 +231,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { /// The unit at each path needs to have already been written to the file /// system before calling this method. Future assertDiagnosticsInUnits( - List<(String path, List expectedDiagnostics)> - unitsAndDiagnostics) async { + List<(String path, List expectedDiagnostics)> + unitsAndDiagnostics, + ) async { for (var (path, expectedDiagnostics) in unitsAndDiagnostics) { result = await resolveFile(convertPath(path)); await _assertDiagnosticsIn(result.errors, expectedDiagnostics); @@ -252,7 +257,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { /// Asserts that [expectedDiagnostics] are reported when resolving [content]. Future assertPubspecDiagnostics( - String content, List expectedDiagnostics) async { + String content, + List expectedDiagnostics, + ) async { newFile(testPackagePubspecPath, content); var errors = await _resolvePubspecFile(content); await _assertDiagnosticsIn(errors, expectedDiagnostics); @@ -266,8 +273,10 @@ class PubPackageResolutionTest extends _ContextResolutionTest { for (var experiment in experiments) { var feature = ExperimentStatus.knownFeatures[experiment]; if (feature?.isEnabledByDefault ?? false) { - fail("The '$experiment' experiment is enabled by default, " - 'try removing it from `experiments`.'); + fail( + "The '$experiment' experiment is enabled by default, " + 'try removing it from `experiments`.', + ); } } @@ -275,19 +284,12 @@ class PubPackageResolutionTest extends _ContextResolutionTest { testPackageRootPath, analysisOptionsContent(experiments: experiments, rules: _lintRules), ); - writeTestPackageConfig( - PackageConfigFileBuilder(), - ); + writeTestPackageConfig(PackageConfigFileBuilder()); _writeTestPackagePubspecYamlFile(pubspecYamlContent(name: 'test')); } void writePackageConfig(String path, PackageConfigFileBuilder config) { - newFile( - path, - config.toContent( - toUriStr: toUriStr, - ), - ); + newFile(path, config.toContent(toUriStr: toUriStr)); } void writeTestPackageConfig(PackageConfigFileBuilder config) { @@ -332,8 +334,10 @@ class PubPackageResolutionTest extends _ContextResolutionTest { } /// Asserts that the diagnostics in [errors] match [expectedDiagnostics]. - Future _assertDiagnosticsIn(List errors, - List expectedDiagnostics) async { + Future _assertDiagnosticsIn( + List errors, + List expectedDiagnostics, + ) async { // // Match actual diagnostics to expected diagnostics. // @@ -344,8 +348,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { var matchFound = false; var expectedIndex = 0; while (expectedIndex < unmatchedExpected.length) { - if (unmatchedExpected[expectedIndex] - .matches(unmatchedActual[actualIndex])) { + if (unmatchedExpected[expectedIndex].matches( + unmatchedActual[actualIndex], + )) { matchFound = true; unmatchedActual.removeAt(actualIndex); unmatchedExpected.removeAt(expectedIndex); @@ -437,9 +442,11 @@ class PubPackageResolutionTest extends _ContextResolutionTest { try { var astSink = StringBuffer(); - StringSpelunker(result.unit.toSource(), - sink: astSink, featureSet: result.unit.featureSet) - .spelunk(); + StringSpelunker( + result.unit.toSource(), + sink: astSink, + featureSet: result.unit.featureSet, + ).spelunk(); buffer.write(astSink); buffer.writeln(); // I hereby choose to catch this type. @@ -456,8 +463,9 @@ class PubPackageResolutionTest extends _ContextResolutionTest { Future> _resolvePubspecFile(String content) async { var path = convertPath(testPackagePubspecPath); var pubspecRules = >{}; - for (var rule in Registry.ruleRegistry - .where((rule) => _lintRules.contains(rule.name))) { + for (var rule in Registry.ruleRegistry.where( + (rule) => _lintRules.contains(rule.name), + )) { var visitor = rule.getPubspecVisitor(); if (visitor != null) { pubspecRules[rule] = visitor; @@ -466,19 +474,20 @@ class PubPackageResolutionTest extends _ContextResolutionTest { if (pubspecRules.isEmpty) { throw UnsupportedError( - 'Resolving pubspec files only supported with rules with ' - 'PubspecVisitors.'); + 'Resolving pubspec files only supported with rules with ' + 'PubspecVisitors.', + ); } var sourceUri = resourceProvider.pathContext.toUri(path); - var pubspecAst = Pubspec.parse(content, - sourceUrl: sourceUri, resourceProvider: resourceProvider); + var pubspecAst = Pubspec.parse( + content, + sourceUrl: sourceUri, + resourceProvider: resourceProvider, + ); var listener = RecordingErrorListener(); var file = resourceProvider.getFile(path); - var reporter = ErrorReporter( - listener, - FileSource(file, sourceUri), - ); + var reporter = ErrorReporter(listener, FileSource(file, sourceUri)); for (var entry in pubspecRules.entries) { entry.key.reporter = reporter; pubspecAst.accept(entry.value); @@ -519,9 +528,10 @@ abstract class _ContextResolutionTest List get _collectionIncludedPaths; /// The analysis errors that were computed during analysis. - List get _errors => result.errors - .whereNot((e) => ignoredErrorCodes.any((c) => e.errorCode == c)) - .toList(); + List get _errors => + result.errors + .whereNot((e) => ignoredErrorCodes.any((c) => e.errorCode == c)) + .toList(); Folder get _sdkRoot => newFolder('/sdk'); @@ -556,10 +566,7 @@ abstract class _ContextResolutionTest _lintRulesAreRegistered = true; } - createMockSdk( - resourceProvider: resourceProvider, - root: _sdkRoot, - ); + createMockSdk(resourceProvider: resourceProvider, root: _sdkRoot); } @mustCallSuper @@ -604,8 +611,12 @@ final class _ExpectedError extends ExpectedDiagnostic { final ErrorCode _code; _ExpectedError(this._code, int offset, int length, {Pattern? messageContains}) - : super((error) => error.errorCode == _code, offset, length, - messageContains: messageContains); + : super( + (error) => error.errorCode == _code, + offset, + length, + messageContains: messageContains, + ); } /// A description of an expected lint rule violation. @@ -618,9 +629,5 @@ final class _ExpectedLint extends ExpectedDiagnostic { int length, { super.messageContains, super.correctionContains, - }) : super( - (error) => error.errorCode.name == _lintName, - offset, - length, - ); + }) : super((error) => error.errorCode.name == _lintName, offset, length); } diff --git a/pkg/linter/test/rules/always_declare_return_types_test.dart b/pkg/linter/test/rules/always_declare_return_types_test.dart index bfb4025937f7..70bba6bdd68c 100644 --- a/pkg/linter/test/rules/always_declare_return_types_test.dart +++ b/pkg/linter/test/rules/always_declare_return_types_test.dart @@ -33,9 +33,7 @@ augment class A { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(39, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(39, 1)]); } test_augmentationTopLevelFunction() async { @@ -50,9 +48,7 @@ f() { } '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(19, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(19, 1)]); } /// Augmentation target chain variations tested in @@ -74,9 +70,7 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(28, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(28, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -93,9 +87,7 @@ part of 'a.dart'; augment f() { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(16, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(16, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -113,20 +105,19 @@ augment dynamic f() { } augment f() { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(16, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(16, 1)]); await assertNoDiagnosticsInFile(b.path); } test_extensionMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { f() {} } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_instanceSetter() async { @@ -138,13 +129,14 @@ class C { } test_method_expressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { f() => 42; } -''', [ - lint(12, 1), - ]); +''', + [lint(12, 1)], + ); } test_method_testUnderscore_notInPubPackageTest_hasReturnType() async { @@ -156,13 +148,14 @@ class A { } test_method_testUnderscore_notInPubPackageTest_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { test_foo() {} } -''', [ - lint(12, 8), - ]); +''', + [lint(12, 8)], + ); } test_method_withReturnType() async { @@ -199,9 +192,7 @@ class MyTest { } '''); - await assertDiagnosticsInFile(file.path, [ - lint(17, 3), - ]); + await assertDiagnosticsInFile(file.path, [lint(17, 3)]); } test_pubPackageTest_method_soloTest_noReturnType() async { @@ -249,11 +240,12 @@ int f() => 7; } test_topLevelFunction_expressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() => 7; -''', [ - lint(0, 1), - ]); +''', + [lint(0, 1)], + ); } test_topLevelFunction_expressionBody_withReturnType() async { @@ -263,11 +255,12 @@ void f() { } } test_topLevelFunction_noReturn() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() {} -''', [ - lint(0, 1), - ]); +''', + [lint(0, 1)], + ); } test_topLevelSetter() async { @@ -277,11 +270,12 @@ set f(int p) {} } test_typedef_oldStyle() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef t(int x); -''', [ - lint(8, 1), - ]); +''', + [lint(8, 1)], + ); } test_typedef_oldStyle_withReturnType() async { diff --git a/pkg/linter/test/rules/always_put_control_body_on_new_line_test.dart b/pkg/linter/test/rules/always_put_control_body_on_new_line_test.dart index e8e13896057e..6390f6e8f2b9 100644 --- a/pkg/linter/test/rules/always_put_control_body_on_new_line_test.dart +++ b/pkg/linter/test/rules/always_put_control_body_on_new_line_test.dart @@ -17,22 +17,23 @@ main() { class AlwaysPutControlBodyOnNewLineTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.DEAD_CODE, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.DEAD_CODE, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.always_put_control_body_on_new_line; test_doWhile_bodyAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do print(''); while (true); } -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_doWhile_bodyOnNewline() async { @@ -54,13 +55,14 @@ void f() { } test_forEachLoop_bodyAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i in []) return; } -''', [ - lint(31, 6), - ]); +''', + [lint(31, 6)], + ); } test_forEachLoop_bodyOnNewline() async { @@ -81,13 +83,14 @@ void f() { } test_forLoop_bodyAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (;;) return; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_forLoop_bodyOnNewline() async { @@ -131,15 +134,16 @@ void f() { } test_ifStatement_elseAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (false) return; else return; } -''', [ - lint(43, 6), - ]); +''', + [lint(43, 6)], + ); } test_ifStatement_elseOnNewline() async { @@ -155,36 +159,39 @@ void f() { } test_ifStatement_thenAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (false) return; } -''', [ - lint(24, 6), - ]); +''', + [lint(24, 6)], + ); } test_ifStatement_thenAdjacent_multiline() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (false) print( 'text' 'text'); } -''', [ - lint(24, 5), - ]); +''', + [lint(24, 5)], + ); } test_ifStatement_thenIsBlock_adjacentStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (false) { print(''); } } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_ifStatement_thenIsEmpty() async { @@ -213,13 +220,14 @@ void f() { } test_whileLoop_bodyAdjacent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { while (true) return; } -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_whileLoop_bodyOnNewline() async { diff --git a/pkg/linter/test/rules/always_put_required_named_parameters_first_test.dart b/pkg/linter/test/rules/always_put_required_named_parameters_first_test.dart index d46844135348..1a9312467074 100644 --- a/pkg/linter/test/rules/always_put_required_named_parameters_first_test.dart +++ b/pkg/linter/test/rules/always_put_required_named_parameters_first_test.dart @@ -27,16 +27,17 @@ class AlwaysPutRequiredNamedParametersFirstTest extends LintRuleTest { String get lintRule => LintNames.always_put_required_named_parameters_first; test_constructor_requiredAfterOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.f({ int? a, required int? b, }); } -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_constructor_requiredAfterRequired() async { @@ -51,7 +52,8 @@ class C { } test_constructor_requiredAnnotationAfterOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; class C { C.f({ @@ -59,9 +61,9 @@ class C { @required int? b, }); } -''', [ - lint(82, 1), - ]); +''', + [lint(82, 1)], + ); } test_constructor_requiredAnnotationAfterRequiredAnnotation() async { @@ -77,14 +79,15 @@ class C { } test_topLevelFunction_requiredAfterOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({ int? a, required int? b, }) {} -''', [ - lint(35, 1), - ]); +''', + [lint(35, 1)], + ); } test_topLevelFunction_requiredAfterRequired() async { @@ -97,15 +100,16 @@ void f({ } test_topLevelFunction_requiredAnnotationAfterOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; void f({ int? a, @required int? b, }) {} -''', [ - lint(69, 1), - ]); +''', + [lint(69, 1)], + ); } test_topLevelFunction_requiredAnnotationAfterRequiredAnnotation() async { diff --git a/pkg/linter/test/rules/always_specify_types_test.dart b/pkg/linter/test/rules/always_specify_types_test.dart index 40bd74d5984a..6635ef0d307e 100644 --- a/pkg/linter/test/rules/always_specify_types_test.dart +++ b/pkg/linter/test/rules/always_specify_types_test.dart @@ -55,14 +55,14 @@ void f() { } test_closureParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { ({final p1, required final p2}) {}; } -''', [ - lint(10, 5), - lint(29, 5), - ]); +''', + [lint(10, 5), lint(29, 5)], + ); } test_closureParameter_named_ok() async { @@ -74,26 +74,26 @@ f() { } test_closureParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { ({p1, required p2}) {}; } -''', [ - lint(10, 2), - lint(14, 11), - ]); +''', + [lint(10, 2), lint(14, 11)], + ); } test_closureParameter_named_passed_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function({int? p1, required int p2}) f) {} f() { m(({final p1, required final p2}) {}); } -''', [ - lint(62, 5), - lint(81, 5), - ]); +''', + [lint(62, 5), lint(81, 5)], + ); } test_closureParameter_named_passed_ok() async { @@ -106,49 +106,49 @@ f() { } test_closureParameter_named_passed_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function({int? p1, required int p2}) f) {} f() { m(({p1, required p2}) {}); } -''', [ - lint(62, 2), - lint(66, 11), - ]); +''', + [lint(62, 2), lint(66, 11)], + ); } test_closureParameter_named_passed_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function({int? p1, required int p2}) f) {} f() { m(({var p1, required var p2}) {}); } -''', [ - lint(62, 3), - lint(79, 3), - ]); +''', + [lint(62, 3), lint(79, 3)], + ); } test_closureParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { ({var p1, required var p2}) {}; } -''', [ - lint(10, 3), - lint(27, 3), - ]); +''', + [lint(10, 3), lint(27, 3)], + ); } test_closureParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { (final p1, [final p2]) {}; } -''', [ - lint(9, 5), - lint(20, 5), - ]); +''', + [lint(9, 5), lint(20, 5)], + ); } test_closureParameter_positional_ok() async { @@ -160,26 +160,26 @@ f() { } test_closureParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { (p1, [p2]) {}; } -''', [ - lint(9, 2), - lint(14, 2), - ]); +''', + [lint(9, 2), lint(14, 2)], + ); } test_closureParameter_positional_passed_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function(int, [int?]) f) {} f() { m((final p1, [final p2]) {}); } -''', [ - lint(46, 5), - lint(57, 5), - ]); +''', + [lint(46, 5), lint(57, 5)], + ); } test_closureParameter_positional_passed_ok() async { @@ -192,49 +192,49 @@ f() { } test_closureParameter_positional_passed_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function(int, [int?]) f) {} f() { m((p1, [p2]) {}); } -''', [ - lint(46, 2), - lint(51, 2), - ]); +''', + [lint(46, 2), lint(51, 2)], + ); } test_closureParameter_positional_passed_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(void Function(int, [int?]) f) {} f() { m((var p1, [var p2]) {}); } -''', [ - lint(46, 3), - lint(55, 3), - ]); +''', + [lint(46, 3), lint(55, 3)], + ); } test_closureParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { (var p1, [var p2]) {}; } -''', [ - lint(9, 3), - lint(18, 3), - ]); +''', + [lint(9, 3), lint(18, 3)], + ); } test_constructorParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({final p1, required final p2}); } -''', [ - lint(15, 5), - lint(34, 5), - ]); +''', + [lint(15, 5), lint(34, 5)], + ); } test_constructorParameter_named_initializingFormal() async { @@ -256,14 +256,14 @@ class C { } test_constructorParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({p1, required p2}) {} } -''', [ - lint(15, 2), - lint(19, 11), - ]); +''', + [lint(15, 2), lint(19, 11)], + ); } test_constructorParameter_named_superParameter() async { @@ -278,25 +278,25 @@ class C extends S { } test_constructorParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({var p1, required var p2}); } -''', [ - lint(15, 3), - lint(32, 3), - ]); +''', + [lint(15, 3), lint(32, 3)], + ); } test_constructorParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(final p1, [final p2]); } -''', [ - lint(14, 5), - lint(25, 5), - ]); +''', + [lint(14, 5), lint(25, 5)], + ); } test_constructorParameter_positional_initializingFormal() async { @@ -318,14 +318,14 @@ class C { } test_constructorParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(p1, [p2]); } -''', [ - lint(14, 2), - lint(19, 2), - ]); +''', + [lint(14, 2), lint(19, 2)], + ); } test_constructorParameter_positional_superParameter() async { @@ -340,14 +340,14 @@ class C extends S { } test_constructorParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(var p1, [var p2]); } -''', [ - lint(14, 3), - lint(23, 3), - ]); +''', + [lint(14, 3), lint(23, 3)], + ); } test_constructorTearoff_keptGeneric() async { @@ -359,31 +359,34 @@ void f() { } test_constructorTearoff_typeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { List.filled; } -''', [ - lint(18, 4), - ]); +''', + [lint(18, 4)], + ); } test_declaredVariable_genericTypeAlias() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef StringMap = Map; StringMap? x; -''', [ - lint(39, 10), - ]); +''', + [lint(39, 10)], + ); } test_declaredVariable_genericTypeAlias_inferredTypeArguments() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef StringMap = Map; StringMap x = StringMap(); -''', [ - lint(39, 9), - ]); +''', + [lint(39, 9)], + ); } test_extensionType_optionalTypeArgs() async { @@ -400,15 +403,16 @@ void f() { } test_extensionType_typeArgs_annotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { } void f() { E e = throw ''; } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_extensionType_typeArgs_annotation_ok() async { @@ -422,15 +426,16 @@ void f() { } test_extensionType_typeArgs_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { } f() { return E(1); } -''', [ - lint(47, 1), - ]); +''', + [lint(47, 1)], + ); } test_extensionType_typeArgs_new_ok() async { @@ -444,25 +449,27 @@ f() { } test_field_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var x; } -''', [ - lint(12, 3), - ]); +''', + [lint(12, 3)], + ); } test_forLoopVariableDeclaration_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i = 0; i < 10; ++i) { print(i); } } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } test_function_parameterType_explicit() async { @@ -472,37 +479,41 @@ void f(int x) {} } test_function_parameterType_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(final x) {} -''', [ - lint(7, 5), - ]); +''', + [lint(7, 5)], + ); } test_function_parameterType_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(p) {} -''', [ - lint(7, 1), - ]); +''', + [lint(7, 1)], + ); } test_function_parameterType_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(var p) {} -''', [ - lint(7, 3), - ]); +''', + [lint(7, 3)], + ); } test_functionExpression_parameterType_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List p) { p.forEach((s) => print(s)); } -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_functionExpression_parameterType_omitted_wildcard() async { @@ -514,13 +525,14 @@ void f(List p) { } test_functionExpression_parameterType_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List p) { p.forEach((s) => print(s)); } -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_genericFunctionTypedVariable_invocation_instantiated() async { @@ -554,79 +566,85 @@ f() { } test_instanceCreation_genericTypeAlias_implicitTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef StringMap = Map; StringMap x = StringMap(); -''', [ - lint(61, 9), - ]); +''', + [lint(61, 9)], + ); } test_instanceField_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final f = 0; } -''', [ - lint(12, 5), - ]); +''', + [lint(12, 5)], + ); } test_instanceField_final_overridden() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class I { int get f; } class C implements I { final f = 0; } -''', [ - lint(59, 5), - ]); +''', + [lint(59, 5)], + ); } test_instanceField_var_initialized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var f = 0; } -''', [ - lint(12, 3), - ]); +''', + [lint(12, 3)], + ); } test_instanceField_var_overridden() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class I { abstract int f; } class C implements I { var f = 0; } -''', [ - lint(64, 3), - ]); +''', + [lint(64, 3)], + ); } test_instanceField_var_uninitialized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var x; } -''', [ - lint(12, 3), - ]); +''', + [lint(12, 3)], + ); } test_instanceMethodParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m({final p1, required final p2}) {} } -''', [ - lint(15, 5), - lint(34, 5), - ]); +''', + [lint(15, 5), lint(34, 5)], + ); } test_instanceMethodParameter_named_ok() async { @@ -638,36 +656,36 @@ class C { } test_instanceMethodParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m({p1, required p2}) {} } -''', [ - lint(15, 2), - lint(19, 11), - ]); +''', + [lint(15, 2), lint(19, 11)], + ); } test_instanceMethodParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m({var p1, required var p2}) {} } -''', [ - lint(15, 3), - lint(32, 3), - ]); +''', + [lint(15, 3), lint(32, 3)], + ); } test_instanceMethodParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m(final p1, [final p2]) {} } -''', [ - lint(14, 5), - lint(25, 5), - ]); +''', + [lint(14, 5), lint(25, 5)], + ); } test_instanceMethodParameter_positional_ok() async { @@ -679,25 +697,25 @@ class C { } test_instanceMethodParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m(p1, [p2]) {} } -''', [ - lint(14, 2), - lint(19, 2), - ]); +''', + [lint(14, 2), lint(19, 2)], + ); } test_instanceMethodParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m(var p1, [var p2]) {} } -''', [ - lint(14, 3), - lint(23, 3), - ]); +''', + [lint(14, 3), lint(23, 3)], + ); } test_instanceStaticField_ok() async { @@ -732,15 +750,16 @@ void f() { } test_interfaceType_typeArgs_annotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { } void f() { C c = throw ''; } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_interfaceType_typeArgs_annotation_ok() async { @@ -754,15 +773,16 @@ void f() { } test_interfaceType_typeArgs_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { } f() { return C(); } -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_interfaceType_typeArgs_new_ok() async { @@ -784,21 +804,23 @@ void f(Object p) { } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { return [1]; } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_listLiteral_inferredTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List x = []; -''', [ - lint(17, 1), - ]); +''', + [lint(17, 1)], + ); } test_listLiteral_ok() async { @@ -810,13 +832,14 @@ f() { } test_listPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [a] = [1]; } -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_listPattern_destructured_ok() async { @@ -828,15 +851,15 @@ f() { } test_localFunctionParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m({final p1, required final p2}) {} m(p1: 0, p2: 0); } -''', [ - lint(11, 5), - lint(30, 5), - ]); +''', + [lint(11, 5), lint(30, 5)], + ); } test_localFunctionParameter_named_ok() async { @@ -849,39 +872,39 @@ f() { } test_localFunctionParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m({p1, required p2}) {} m(p1: 0, p2: 0); } -''', [ - lint(11, 2), - lint(15, 11), - ]); +''', + [lint(11, 2), lint(15, 11)], + ); } test_localFunctionParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m({var p1, required var p2}) {} m(p1: 0, p2: 0); } -''', [ - lint(11, 3), - lint(28, 3), - ]); +''', + [lint(11, 3), lint(28, 3)], + ); } test_localFunctionParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m(final p1, [final p2]) {} m(0, 0); } -''', [ - lint(10, 5), - lint(21, 5), - ]); +''', + [lint(10, 5), lint(21, 5)], + ); } test_localFunctionParameter_positional_ok() async { @@ -894,47 +917,49 @@ f() { } test_localFunctionParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m(p1, [p2]) {} m(0, 0); } -''', [ - lint(10, 2), - lint(15, 2), - ]); +''', + [lint(10, 2), lint(15, 2)], + ); } test_localFunctionParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { m(var p1, [var p2]) {} m(0, 0); } -''', [ - lint(10, 3), - lint(19, 3), - ]); +''', + [lint(10, 3), lint(19, 3)], + ); } test_localVariable_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m() { const f = 0; } -''', [ - lint(8, 5), - ]); +''', + [lint(8, 5)], + ); } test_localVariable_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m() { final f = 0; } -''', [ - lint(8, 5), - ]); +''', + [lint(8, 5)], + ); } test_localVariable_ok() async { @@ -948,53 +973,58 @@ m() { } test_localVariable_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m() { var f = 0; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_localVariableDeclaration_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = ''; } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_localVariableDeclaration_var_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = '', y = 1.2; } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_mapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { return {1: ''}; } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_mapLiteral_empty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { return {}; } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_mapLiteral_empty_ok() async { @@ -1006,11 +1036,12 @@ f() { } test_mapLiteral_inferredTypeArguments() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map x = {}; -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_mapLiteral_ok() async { @@ -1022,13 +1053,14 @@ f() { } test_mapPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var {'a': a} = {'a': 1}; } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_mapPattern_destructured_ok() async { @@ -1040,7 +1072,8 @@ f() { } test_objectPattern_switch_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -1051,9 +1084,9 @@ f() { case A(a: >0 && final b): } } -''', [ - lint(79, 5), - ]); +''', + [lint(79, 5)], + ); } test_objectPattern_switch_ok() async { @@ -1072,7 +1105,8 @@ f() { } test_objectPattern_switch_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -1083,22 +1117,22 @@ f() { case A(a: >0 && var b): } } -''', [ - lint(79, 3), - ]); +''', + [lint(79, 3)], + ); } test_recordPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ((1, 2)) { case (final a, var b): } } -''', [ - lint(36, 5), - lint(45, 3), - ]); +''', + [lint(36, 5), lint(45, 3)], + ); } test_recordPattern_switch_ok() async { @@ -1112,21 +1146,23 @@ f() { } test_setLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { return {1}; } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_setLiteral_inferredTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Set set = {}; -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_setLiteral_ok() async { @@ -1138,44 +1174,47 @@ f() { } test_staticField_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static const f = 0; } -''', [ - lint(19, 5), - ]); +''', + [lint(19, 5)], + ); } test_staticField_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static final f = 0; } -''', [ - lint(19, 5), - ]); +''', + [lint(19, 5)], + ); } test_staticField_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static var f = 0; } -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_staticMethodParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m({final p1, required final p2}) {} } -''', [ - lint(22, 5), - lint(41, 5), - ]); +''', + [lint(22, 5), lint(41, 5)], + ); } test_staticMethodParameter_named_ok() async { @@ -1187,36 +1226,36 @@ class C { } test_staticMethodParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m({p1, required p2}) {} } -''', [ - lint(22, 2), - lint(26, 11), - ]); +''', + [lint(22, 2), lint(26, 11)], + ); } test_staticMethodParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m({var p1, required var p2}) {} } -''', [ - lint(22, 3), - lint(39, 3), - ]); +''', + [lint(22, 3), lint(39, 3)], + ); } test_staticMethodParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m(final p1, [final p2]) {} } -''', [ - lint(21, 5), - lint(32, 5), - ]); +''', + [lint(21, 5), lint(32, 5)], + ); } test_staticMethodParameter_positional_ok() async { @@ -1228,41 +1267,43 @@ class C { } test_staticMethodParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m(p1, [p2]) {} } -''', [ - lint(21, 2), - lint(26, 2), - ]); +''', + [lint(21, 2), lint(26, 2)], + ); } test_staticMethodParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m(var p1, [var p2]) {} } -''', [ - lint(21, 3), - lint(30, 3), - ]); +''', + [lint(21, 3), lint(30, 3)], + ); } test_topLevelField_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const f = 0; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelField_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final f = 0; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelField_ok() async { @@ -1274,20 +1315,21 @@ const int f3 = 0; } test_topLevelField_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = 0; -''', [ - lint(0, 3), - ]); +''', + [lint(0, 3)], + ); } test_topLevelParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m({final p1, required final p2}) {} -''', [ - lint(3, 5), - lint(22, 5), - ]); +''', + [lint(3, 5), lint(22, 5)], + ); } test_topLevelParameter_named_ok() async { @@ -1297,30 +1339,30 @@ m({int? p1, final int? p2, required int p3, required final int p4}) {} } test_topLevelParameter_named_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m({p1, required p2}) {} -''', [ - lint(3, 2), - lint(7, 11), - ]); +''', + [lint(3, 2), lint(7, 11)], + ); } test_topLevelParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m({var p1, required var p2}) {} -''', [ - lint(3, 3), - lint(20, 3), - ]); +''', + [lint(3, 3), lint(20, 3)], + ); } test_topLevelParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(final p1, [final p2]) {} -''', [ - lint(2, 5), - lint(13, 5), - ]); +''', + [lint(2, 5), lint(13, 5)], + ); } test_topLevelParameter_positional_ok() async { @@ -1330,21 +1372,21 @@ m(int p1, final int p2, [int? p3, final int? p4]) {} } test_topLevelParameter_positional_omitted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(p1, [p2]) {} -''', [ - lint(2, 2), - lint(7, 2), - ]); +''', + [lint(2, 2), lint(7, 2)], + ); } test_topLevelParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m(var p1, [var p2]) {} -''', [ - lint(2, 3), - lint(11, 3), - ]); +''', + [lint(2, 3), lint(11, 3)], + ); } test_topLevelVariableDeclaration_explicitType() async { @@ -1354,68 +1396,76 @@ final int x = 3; } test_topLevelVariableDeclaration_implicitTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List? x; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelVariableDeclaration_missingType_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const x = 2; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelVariableDeclaration_missingType_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final x = 1; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelVariableDeclaration_missingType_final_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final x = 1, y = '', z = 1.2; -''', [ - lint(0, 5), - ]); +''', + [lint(0, 5)], + ); } test_topLevelVariableDeclaration_missingType_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = '', y = ''; -''', [ - lint(0, 3), - ]); +''', + [lint(0, 3)], + ); } test_topLevelVariableDeclaration_typeArgument_implicitTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List? x; -''', [ - lint(5, 4), - ]); +''', + [lint(5, 4)], + ); } test_topLevelVariableDeclaration_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x; -''', [ - lint(0, 3), - ]); +''', + [lint(0, 3)], + ); } test_typedef_aliased_typeArgument_withImplicitTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef StringMap = Map; typedef MapList = List; -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_typedef_typeArgument_withExplicitTypeArgument() async { @@ -1431,11 +1481,12 @@ typedef StringMap = Map; } test_typedef_withImplicitTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef RawList = List; -''', [ - lint(18, 4), - ]); +''', + [lint(18, 4)], + ); } test_typedefType_optionalTypeArgs() async { @@ -1454,16 +1505,17 @@ void f() { } test_typedefType_typeArgs_annotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { } typedef F = C; void f() { F f = throw ''; } -''', [ - lint(50, 1), - ]); +''', + [lint(50, 1)], + ); } test_typedefType_typeArgs_annotation_ok() async { @@ -1478,16 +1530,17 @@ void f() { } test_typedefType_typeArgs_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { } typedef F = C; f() { return F(); } -''', [ - lint(52, 1), - ]); +''', + [lint(52, 1)], + ); } test_typedefType_typeArgs_new_ok() async { diff --git a/pkg/linter/test/rules/always_use_package_imports_test.dart b/pkg/linter/test/rules/always_use_package_imports_test.dart index f7cbe65dfee1..4518bfdb45e0 100644 --- a/pkg/linter/test/rules/always_use_package_imports_test.dart +++ b/pkg/linter/test/rules/always_use_package_imports_test.dart @@ -77,12 +77,13 @@ import 'package:test/lib.dart'; newFile('$testPackageLibPath/lib.dart', r''' class C {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// This provides [C]. import 'lib.dart'; -''', [ - lint(30, 10), - ]); +''', + [lint(30, 10)], + ); } test_samePackage_relativeUri_inPart() async { @@ -94,13 +95,14 @@ class C {} part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; /// This provides [C]. import 'lib.dart'; -''', [ - lint(49, 10), - ]); +''', + [lint(49, 10)], + ); } } diff --git a/pkg/linter/test/rules/analyzer_use_new_elements_test.dart b/pkg/linter/test/rules/analyzer_use_new_elements_test.dart index 0f26fbd92ad8..894ffde5ab83 100644 --- a/pkg/linter/test/rules/analyzer_use_new_elements_test.dart +++ b/pkg/linter/test/rules/analyzer_use_new_elements_test.dart @@ -37,10 +37,7 @@ class AnalyzerUseNewElementsTest extends LintRuleTest { newPackageConfigJsonFileFromBuilder( testPackageRootPath, PackageConfigFileBuilder() - ..add( - name: 'analyzer', - rootPath: analyzerFolder.path, - ), + ..add(name: 'analyzer', rootPath: analyzerFolder.path), ); } @@ -78,51 +75,55 @@ import 'package:analyzer/dart/element/element.dart'; List getAllClasses() => []; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; void f() { getAllClasses(); } -''', [ - lint(31, 13), - ]); +''', + [lint(31, 13)], + ); } test_namedType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:analyzer/dart/element/element.dart'; ClassElement f() { throw 42; } -''', [ - lint(54, 12), - ]); +''', + [lint(54, 12)], + ); } test_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:analyzer/dart/ast/ast.dart'; void f(ClassDeclaration a) { a.declaredElement; } -''', [ - lint(79, 15), - ]); +''', + [lint(79, 15)], + ); } test_propertyAccess_declaredElement_src() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:analyzer/src/dart/ast/ast.dart'; void f(ClassDeclarationImpl a) { a.declaredElement; } -''', [ - lint(87, 15), - ]); +''', + [lint(87, 15)], + ); } test_propertyAccess_nestedType() async { @@ -132,14 +133,15 @@ import 'package:analyzer/dart/element/element.dart'; List get allClasses => []; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; void f() { allClasses; } -''', [ - lint(31, 10), - ]); +''', + [lint(31, 10)], + ); } } diff --git a/pkg/linter/test/rules/annotate_overrides_test.dart b/pkg/linter/test/rules/annotate_overrides_test.dart index 52acc337b373..c156cfcf4efb 100644 --- a/pkg/linter/test/rules/annotate_overrides_test.dart +++ b/pkg/linter/test/rules/annotate_overrides_test.dart @@ -55,15 +55,16 @@ class A { class B extends A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class B { void a() {} } -''', [ - lint(44, 1), - ]); +''', + [lint(44, 1)], + ); } test_augmentationMethodWithAnnotation() async { @@ -108,7 +109,8 @@ class B extends A { // Test setters and operators. test_class_fieldWithoutAnnotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int get x => 4; } @@ -116,9 +118,9 @@ class A { class B extends A { int x = 5; } -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_class_getterWithAnnotation() async { @@ -150,7 +152,8 @@ class B extends A { } test_class_getterWithoutAnnotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int get x => 4; } @@ -158,9 +161,9 @@ class A { class B extends A { int get x => 5; } -''', [ - lint(61, 1), - ]); +''', + [lint(61, 1)], + ); } test_class_methodWithAnnotation() async { @@ -177,7 +180,8 @@ class B extends A { } test_class_methodWithoutAnnotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void f() {} } @@ -185,9 +189,9 @@ class A { class B extends A { void f() {} } -''', [ - lint(54, 1), - ]); +''', + [lint(54, 1)], + ); } test_enum_fieldWithAnnotation() async { @@ -205,7 +209,8 @@ enum A implements O { } test_enum_fieldWithoutAnnotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class O { int get x => 0; } @@ -214,9 +219,9 @@ enum A implements O { a,b,c; int get x => 0; } -''', [ - lint(72, 1), - ]); +''', + [lint(72, 1)], + ); } test_enum_methodWithAnnotation() async { @@ -234,18 +239,20 @@ enum A implements O { } test_enum_methodWithoutAnnotation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; String toString() => ''; } -''', [ - lint(27, 8), - ]); +''', + [lint(27, 8)], + ); } test_extensionTypes_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int i = 0; } @@ -253,10 +260,16 @@ class A { extension type B(A a) implements A { int i = 0; } -''', [ - // No lint. - error(CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, 69, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, + 69, + 1, + ), + ], + ); } test_extensionTypes_getter() async { diff --git a/pkg/linter/test/rules/annotate_redeclares_test.dart b/pkg/linter/test/rules/annotate_redeclares_test.dart index 7d1aee77f2c0..04aec35b6ced 100644 --- a/pkg/linter/test/rules/annotate_redeclares_test.dart +++ b/pkg/linter/test/rules/annotate_redeclares_test.dart @@ -29,15 +29,16 @@ class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; extension type E(A a) implements A { void m() {} } -''', [ - lint(63, 1), - ]); +''', + [lint(63, 1)], + ); } test_augmentationMethodWithAnnotation() async { @@ -66,7 +67,8 @@ augment extension type E(A a) { } test_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m() {} } @@ -74,9 +76,9 @@ class A { extension type E(A a) implements A { void m() {} } -''', [ - lint(71, 1), - ]); +''', + [lint(71, 1)], + ); } test_method_annotated() async { @@ -94,7 +96,8 @@ extension type E(A a) implements A { } test_setter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int i = 0; } @@ -102,8 +105,8 @@ class A { extension type E(A a) implements A { set i(int i) {} } -''', [ - lint(69, 1), - ]); +''', + [lint(69, 1)], + ); } } diff --git a/pkg/linter/test/rules/avoid_annotating_with_dynamic_test.dart b/pkg/linter/test/rules/avoid_annotating_with_dynamic_test.dart index 9b0778c9cd91..d129eca5c732 100644 --- a/pkg/linter/test/rules/avoid_annotating_with_dynamic_test.dart +++ b/pkg/linter/test/rules/avoid_annotating_with_dynamic_test.dart @@ -33,9 +33,7 @@ augment class A { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(46, 9), - ]); + await assertDiagnosticsInFile(b.path, [lint(46, 9)]); } test_augmentationTopLevelFunction() async { @@ -50,9 +48,7 @@ void f(dynamic o) { } '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(26, 9), - ]); + await assertDiagnosticsInFile(b.path, [lint(26, 9)]); } test_augmentationTopLevelFunction_localDynamic() async { @@ -72,9 +68,7 @@ augment void f(int i) { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(54, 9), - ]); + await assertDiagnosticsInFile(b.path, [lint(54, 9)]); } test_augmentedMethod() async { @@ -94,9 +88,7 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(35, 9), - ]); + await assertDiagnosticsInFile(a.path, [lint(35, 9)]); await assertNoDiagnosticsInFile(b.path); } @@ -113,9 +105,7 @@ part of 'a.dart'; augment void f(dynamic o) { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(23, 9), - ]); + await assertDiagnosticsInFile(a.path, [lint(23, 9)]); await assertNoDiagnosticsInFile(b.path); } @@ -133,9 +123,7 @@ augment void f(dynamic o) { } augment void f(dynamic o) { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(23, 9), - ]); + await assertDiagnosticsInFile(a.path, [lint(23, 9)]); await assertNoDiagnosticsInFile(b.path); } @@ -145,14 +133,15 @@ augment void f(dynamic o) { } // Test parameter with a default value. test_fieldFormals() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var a; A(dynamic this.a); } -''', [ - lint(23, 14), - ]); +''', + [lint(23, 14)], + ); } test_implicitDynamic() async { @@ -162,27 +151,30 @@ void f(p) {} } test_optionalNamedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({dynamic p}) {} -''', [ - lint(8, 9), - ]); +''', + [lint(8, 9)], + ); } test_optionalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([dynamic p]) {} -''', [ - lint(8, 9), - ]); +''', + [lint(8, 9)], + ); } test_requiredParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) {} -''', [ - lint(7, 9), - ]); +''', + [lint(7, 9)], + ); } test_returnType() async { @@ -194,7 +186,8 @@ dynamic f() { } test_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var a; var b; @@ -203,9 +196,8 @@ class A { class B extends A { B(dynamic super.a, dynamic super.b); } -''', [ - lint(75, 15), - lint(92, 15), - ]); +''', + [lint(75, 15), lint(92, 15)], + ); } } diff --git a/pkg/linter/test/rules/avoid_bool_literals_in_conditional_expressions_test.dart b/pkg/linter/test/rules/avoid_bool_literals_in_conditional_expressions_test.dart index 415256fc456b..48eeb946705c 100644 --- a/pkg/linter/test/rules/avoid_bool_literals_in_conditional_expressions_test.dart +++ b/pkg/linter/test/rules/avoid_bool_literals_in_conditional_expressions_test.dart @@ -19,21 +19,23 @@ class AvoidBoolLiteralsInConditionalExpressionsTest extends LintRuleTest { LintNames.avoid_bool_literals_in_conditional_expressions; test_elseFalse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = true; var b = a ? a : false; -''', [ - lint(22, 13), - ]); +''', + [lint(22, 13)], + ); } test_elseTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = true; var b = a ? a : true; -''', [ - lint(22, 12), - ]); +''', + [lint(22, 12)], + ); } test_noLiterals() async { @@ -44,29 +46,32 @@ var b = a ? a : a; } test_thenFalse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = true; var b = a ? false : a; -''', [ - lint(22, 13), - ]); +''', + [lint(22, 13)], + ); } test_thenTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = true; var b = a ? true : a; -''', [ - lint(22, 12), - ]); +''', + [lint(22, 12)], + ); } test_thenTrue_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = true; var b = a ? (true) : a; -''', [ - lint(22, 14), - ]); +''', + [lint(22, 14)], + ); } } diff --git a/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart b/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart index d03842d50dbf..9dfcf730dcf1 100644 --- a/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart +++ b/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart @@ -19,8 +19,10 @@ class AvoidCatchesWithoutOnClausesTest extends LintRuleTest { bool get addFlutterPackageDep => true; @override - List get ignoredErrorCodes => - [WarningCode.UNUSED_ELEMENT, WarningCode.UNUSED_LOCAL_VARIABLE]; + List get ignoredErrorCodes => [ + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.avoid_catches_without_on_clauses; @@ -36,25 +38,27 @@ void f() { } test_missingOnClause() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e) {} } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_missingOnClause_nonRelevantUse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e) { print(e); } } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_missingOnClause_rethrow() async { @@ -68,7 +72,8 @@ void f() { } test_missingOnClause_unrelatedRethrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e) { try {} on Exception catch (e) { @@ -77,13 +82,14 @@ void f() { } } } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_missingOnClause_unrelatedRethrow_inNestedFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e) { void g() { @@ -94,9 +100,9 @@ void f() { } } } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_missingOnClause_usedInCompleter_completeError() async { diff --git a/pkg/linter/test/rules/avoid_catching_errors_test.dart b/pkg/linter/test/rules/avoid_catching_errors_test.dart index 16e18d22d875..5b4150da4c2b 100644 --- a/pkg/linter/test/rules/avoid_catching_errors_test.dart +++ b/pkg/linter/test/rules/avoid_catching_errors_test.dart @@ -26,13 +26,14 @@ void f() { } test_exactlyError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} on Error catch (_) {} } -''', [ - lint(20, 21), - ]); +''', + [lint(20, 21)], + ); } test_exactlyException() async { @@ -44,53 +45,57 @@ void f() { } test_typeExtendsError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} on C {} } class C extends Error {} class D extends C {} -''', [ - lint(20, 7), - ]); +''', + [lint(20, 7)], + ); } test_typeExtendsTypeThatExtendsError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} on D {} } class D extends C {} class C extends Error {} -''', [ - lint(20, 7), - ]); +''', + [lint(20, 7)], + ); } test_typeExtendsTypeThatImplementsError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} on B catch (_) {} } abstract class A implements Error {} abstract class B extends A {} -''', [ - lint(20, 17), - ]); +''', + [lint(20, 17)], + ); } test_typeImplementsError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} on A catch (_) {} } abstract class A implements Error {} -''', [ - lint(20, 17), - ]); +''', + [lint(20, 17)], + ); } } diff --git a/pkg/linter/test/rules/avoid_classes_with_only_static_members_test.dart b/pkg/linter/test/rules/avoid_classes_with_only_static_members_test.dart index ea86f703dceb..889601fadf89 100644 --- a/pkg/linter/test/rules/avoid_classes_with_only_static_members_test.dart +++ b/pkg/linter/test/rules/avoid_classes_with_only_static_members_test.dart @@ -54,9 +54,7 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(16, 10), - ]); + await assertDiagnosticsInFile(a.path, [lint(16, 10)]); await assertNoDiagnosticsInFile(b.path); } @@ -76,21 +74,20 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(16, 10), - ]); + await assertDiagnosticsInFile(a.path, [lint(16, 10)]); await assertNoDiagnosticsInFile(b.path); } test_basicClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void f() {} } -''', [ - lint(0, 32), - ]); +''', + [lint(0, 32)], + ); } test_class_empty() async { @@ -184,13 +181,14 @@ class C { } test_finalClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class C { static void f() {} } -''', [ - lint(0, 38), - ]); +''', + [lint(0, 38)], + ); } test_sealedClass() async { diff --git a/pkg/linter/test/rules/avoid_double_and_int_checks_test.dart b/pkg/linter/test/rules/avoid_double_and_int_checks_test.dart index 908e46e85819..f10cc64d3839 100644 --- a/pkg/linter/test/rules/avoid_double_and_int_checks_test.dart +++ b/pkg/linter/test/rules/avoid_double_and_int_checks_test.dart @@ -35,14 +35,15 @@ void f(m) { } test_checkingForIntAfterDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(m) { if (m is double) {} else if (m is int) {} } -''', [ - lint(45, 8), - ]); +''', + [lint(45, 8)], + ); } test_checkingForIntAfterDouble_getter() async { @@ -56,14 +57,15 @@ void f() { } test_checkingForIntAfterDouble_localVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var m; if (m is double) {} else if (m is int) {} } -''', [ - lint(53, 8), - ]); +''', + [lint(53, 8)], + ); } } diff --git a/pkg/linter/test/rules/avoid_dynamic_calls_test.dart b/pkg/linter/test/rules/avoid_dynamic_calls_test.dart index 95ac94f285fb..874c823fa6f6 100644 --- a/pkg/linter/test/rules/avoid_dynamic_calls_test.dart +++ b/pkg/linter/test/rules/avoid_dynamic_calls_test.dart @@ -26,13 +26,14 @@ void f(Object? a) { } test_callInvocation_cascade_Function() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function p) { p..call(); } -''', [ - lint(26, 4), - ]); +''', + [lint(26, 4)], + ); } test_callInvocation_cascade_functionType() async { @@ -44,13 +45,14 @@ void f(void Function() p) { } test_callInvocation_Function() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function p) { p.call(); } -''', [ - lint(25, 4), - ]); +''', + [lint(25, 4)], + ); } test_callInvocation_Function_tearoff() async { @@ -104,43 +106,47 @@ void f(dynamic a) { } test_dynamicBinaryExpression_caret() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a ^ 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicBinaryExpression_lessThan() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a < 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicBinaryExpression_lessThanLessThan() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a << 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicBinaryExpression_plus() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a + 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicBinaryExpression_questionQuestion() async { @@ -152,107 +158,117 @@ void f(dynamic a) { } test_dynamicBinaryExpression_tildeSlash() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a ~/ 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicCascadedMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a..b(); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicCascadedMethodCall_subsequent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a ..toString() ..b(); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicCascadedPropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a..b; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicCascadedPropertyAccess_subsequent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a ..toString() ..b; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicCompoundAssignment_ampersandEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a &= 1; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_caretEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a ^= 1; // LINT } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_minusEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a -= 1; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_pipeEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a |= 1; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_plusEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a += 1; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_questionQuestionEqualsOperator() async { @@ -264,43 +280,47 @@ void f(dynamic a) { } test_dynamicCompoundAssignment_slashEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a /= 1; // LINT } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicCompoundAssignment_starEqualsOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a *= 1; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_dynamicDecrementPostfixOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a--; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_dynamicDecrementPrefixOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { --a; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_dynamicEqualOperator() async { @@ -312,53 +332,58 @@ void f(dynamic a) { } test_dynamicImplicitCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a(); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicIncrementPostfixOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a++; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_dynamicIncrementPrefixOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { ++a; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_dynamicIndexAssignmetOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a[1] = 1; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicIndexOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a[1]; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicNotEqualOperator() async { @@ -370,63 +395,69 @@ void f(dynamic a) { } test_dynamicNullAssertMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a!.b(); } -''', [ - lint(22, 2), - ]); +''', + [lint(22, 2)], + ); } test_dynamicNullAssertPropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a!.b; } -''', [ - lint(22, 2), - ]); +''', + [lint(22, 2)], + ); } test_dynamicNullAwareMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a?.b(); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicNullAwarePropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a?.b; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_dynamicUnaryMinusOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { -a; } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_functionExpressionInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function? g1, Function g2) { (g1 ?? g2)(); } -''', [ - lint(38, 10), - ]); +''', + [lint(38, 10)], + ); } test_functionExpressionInvocation_asFunction() async { @@ -438,13 +469,14 @@ void f(Object? g1, Object? g2) { } test_functionInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function g) { g(); } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_functionInvocation_asFunction() async { @@ -456,23 +488,25 @@ void f(Object? g) { } test_functionInvocation_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function a) { (a)(); } -''', [ - lint(23, 3), - ]); +''', + [lint(23, 3)], + ); } test_indexAssignmentExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a[1] = 7; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_indexAssignmentExpression_asDynamic() async { @@ -484,13 +518,14 @@ void f(Object? a) { } test_indexExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a[1]; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_indexExpression_asDynamic() async { @@ -502,23 +537,25 @@ void f(Object? a) { } test_parenthesizedExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { (a).b; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_prefixedIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a.foo; } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_prefixedIdentifier_asDynamic() async { @@ -530,13 +567,14 @@ void f(Object? a) { } test_prefixedIdentifier_dynamicMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a.foo(); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_prefixedIdentifier_dynamicMethodCall_asDynamic() async { @@ -556,33 +594,36 @@ void f(dynamic a, Invocation i) { } test_prefixedIdentifier_noSuchMethod_withAdditionalPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a, Invocation i) { a.noSuchMethod(i, 7); } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_prefixedIdentifier_noSuchMethod_withNamedArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a, Invocation i) { a.noSuchMethod(i, p: 7); } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_prefixedIdentifier_noSuchMethod_withNamedArgumentBeforePositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a, Invocation i) { a.noSuchMethod(i, p: 7); } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_prefixedIdentifier_runtimeType() async { @@ -602,36 +643,39 @@ void f(dynamic a) { } test_prefixedIdentifier_toString_withNamedArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a.toString(p: 7); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_prefixedIdentifier_toString_withPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic a) { a.toString(7); } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.a.foo; } class C { dynamic a; } -''', [ - lint(16, 3), - ]); +''', + [lint(16, 3)], + ); } test_propertyAccess_asDynamic() async { diff --git a/pkg/linter/test/rules/avoid_empty_else_test.dart b/pkg/linter/test/rules/avoid_empty_else_test.dart index 809c87ac1cab..22188dd4d5ce 100644 --- a/pkg/linter/test/rules/avoid_empty_else_test.dart +++ b/pkg/linter/test/rules/avoid_empty_else_test.dart @@ -18,7 +18,8 @@ class AvoidEmptyElseTest extends LintRuleTest { String get lintRule => LintNames.avoid_empty_else; test_else_emptyStatement_hasElseIf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 0; var y = 1; @@ -29,13 +30,14 @@ void f() { else ; print(''); } -''', [ - lint(105, 1), - ]); +''', + [lint(105, 1)], + ); } test_else_emptyStatement_noElseIf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 0; var y = 1; @@ -44,9 +46,9 @@ void f() { else ; print(''); } -''', [ - lint(72, 1), - ]); +''', + [lint(72, 1)], + ); } test_else_noEmptyStatement_enclosed() async { @@ -77,7 +79,8 @@ void f() { } test_else_noStatement_notEnclosed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 0; var y = 1; @@ -85,10 +88,12 @@ void f() { print(''); else } -''', [ - // No lint - error(ParserErrorCode.EXPECTED_TOKEN, 67, 4), - error(ParserErrorCode.MISSING_IDENTIFIER, 72, 1), - ]); +''', + [ + // No lint + error(ParserErrorCode.EXPECTED_TOKEN, 67, 4), + error(ParserErrorCode.MISSING_IDENTIFIER, 72, 1), + ], + ); } } diff --git a/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart b/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart index c174c2047f66..c7f457d7bde2 100644 --- a/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart +++ b/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart @@ -21,7 +21,8 @@ class AvoidEqualsAndHashCodeOnMutableClassesTest extends LintRuleTest { LintNames.avoid_equals_and_hash_code_on_mutable_classes; test_enums() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { e(1), f(2), g(3); final int key; @@ -29,13 +30,21 @@ enum E { bool operator ==(Object other) => other is E && other.key == key; int get hashCode => key.hashCode; } -''', [ - error( - CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, 83, 2), - error(CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, 145, - 8), - // No lint. - ]); +''', + [ + error( + CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, + 83, + 2, + ), + error( + CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, + 145, + 8, + ), + // No lint. + ], + ); } test_immutableClass() async { @@ -55,8 +64,9 @@ class A { } @FailingTest( - reason: '`augmented.metadata` is unimplemented', - issue: 'https://github.com/dart-lang/linter/issues/4932') + reason: '`augmented.metadata` is unimplemented', + issue: 'https://github.com/dart-lang/linter/issues/4932', + ) test_immutableClass_augmented() async { var a = newFile('$testPackageLibPath/a.dart', r''' part 'b.dart'; @@ -83,7 +93,8 @@ augment class A { } } test_mutableClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { final String key; const A(this.key); @@ -92,10 +103,9 @@ class A { @override int get hashCode => key.hashCode; } -''', [ - lint(65, 8), - lint(133, 3), - ]); +''', + [lint(65, 8), lint(133, 3)], + ); } test_mutableClass_augmentationMethod() async { @@ -124,16 +134,17 @@ part 'test.dart'; class A {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { @override int get hashCode => 0; } -''', [ - lint(51, 3), - ]); +''', + [lint(51, 3)], + ); } test_subtypeOfImmutableClass() async { diff --git a/pkg/linter/test/rules/avoid_escaping_inner_quotes_test.dart b/pkg/linter/test/rules/avoid_escaping_inner_quotes_test.dart index 9cc25555ce13..9378b652691b 100644 --- a/pkg/linter/test/rules/avoid_escaping_inner_quotes_test.dart +++ b/pkg/linter/test/rules/avoid_escaping_inner_quotes_test.dart @@ -26,23 +26,25 @@ void f() { } test_doubleQuotes_escapedQuote() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print("\""); } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_doubleQuotes_escapedQuote_withInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print("\"$f"); } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_doubleQuotes_escapedQuote_withSingleQuote() async { @@ -62,13 +64,14 @@ void f() { } test_singleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(String d) { print('a\'b\'c ${d.length}'); } -''', [ - lint(27, 21), - ]); +''', + [lint(27, 21)], + ); } test_singleQuotes_empty() async { @@ -80,13 +83,14 @@ void f() { } test_singleQuotes_escapedQuote() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print('\''); } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_singleQuotes_escapedQuote_withDoubleQuote() async { @@ -106,12 +110,13 @@ void f() { } test_singleQuotes_escapedQuote_withInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print('\'$f'); } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } } diff --git a/pkg/linter/test/rules/avoid_field_initializers_in_const_classes_test.dart b/pkg/linter/test/rules/avoid_field_initializers_in_const_classes_test.dart index 03d07e9b47cc..c09c1f608f4c 100644 --- a/pkg/linter/test/rules/avoid_field_initializers_in_const_classes_test.dart +++ b/pkg/linter/test/rules/avoid_field_initializers_in_const_classes_test.dart @@ -18,25 +18,27 @@ class AvoidFieldInitializersInConstClassesTest extends LintRuleTest { String get lintRule => LintNames.avoid_field_initializers_in_const_classes; test_constClass_constructorInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final a; const C() : a = const []; } -''', [ - lint(35, 12), - ]); +''', + [lint(35, 12)], + ); } test_constClass_constructorInitializer_explicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final a; const C(int a) : this.a = 0; } -''', [ - lint(40, 10), - ]); +''', + [lint(40, 10)], + ); } test_constClass_constructorInitializer_usingParameter() async { @@ -58,14 +60,15 @@ class C { } test_constClass_fieldInitiailizer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final a = const []; const C(); } -''', [ - lint(18, 12), - ]); +''', + [lint(18, 12)], + ); } test_constClass_multipleConstructors() async { diff --git a/pkg/linter/test/rules/avoid_field_initializers_in_non_const_classes_test.dart b/pkg/linter/test/rules/avoid_field_initializers_in_non_const_classes_test.dart index 07898424c460..e830a99e6f95 100644 --- a/pkg/linter/test/rules/avoid_field_initializers_in_non_const_classes_test.dart +++ b/pkg/linter/test/rules/avoid_field_initializers_in_non_const_classes_test.dart @@ -49,15 +49,16 @@ class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { augment const A() : s = ''; } -''', [ - lint(59, 6), - ]); +''', + [lint(59, 6)], + ); } test_augmentedClass_augmentedField() async { @@ -86,16 +87,17 @@ part 'test.dart'; class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { final a; const A() : a = ''; } -''', [ - lint(62, 6), - ]); +''', + [lint(62, 6)], + ); } test_augmentedClass_constructorInitializer_multipleConstructors() async { @@ -126,14 +128,15 @@ class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { final s = ''; } -''', [ - lint(45, 6), - ]); +''', + [lint(45, 6)], + ); } } diff --git a/pkg/linter/test/rules/avoid_final_parameters_test.dart b/pkg/linter/test/rules/avoid_final_parameters_test.dart index cee993410dda..7c7a988bdef3 100644 --- a/pkg/linter/test/rules/avoid_final_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_final_parameters_test.dart @@ -20,17 +20,20 @@ class AvoidFinalParametersTest extends LintRuleTest { // TODO(srawlins): Test function-typed parameter like `void f(final p())`. test_constructorFieldFormal_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int p; C(final this.p); } -''', [ - // TODO(srawlins): Do not report this lint rule here, as it is redundant - // with the Warning. - error(WarningCode.UNNECESSARY_FINAL, 23, 5), - lint(23, 12), - ]); +''', + [ + // TODO(srawlins): Do not report this lint rule here, as it is redundant + // with the Warning. + error(WarningCode.UNNECESSARY_FINAL, 23, 5), + lint(23, 12), + ], + ); } test_constructorFieldFormal_noFinal() async { @@ -43,13 +46,14 @@ class C { } test_constructorSimple_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(final int p); } -''', [ - lint(14, 11), - ]); +''', + [lint(14, 11)], + ); } test_constructorSimple_noFinal() async { @@ -61,11 +65,12 @@ class C { } test_functionExpression_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = (final int value) {}; -''', [ - lint(9, 15), - ]); +''', + [lint(9, 15)], + ); } test_functionExpression_noFinal() async { @@ -75,13 +80,14 @@ var f = (int value) {}; } test_operator_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int operator +(final int other) => 0; } -''', [ - lint(27, 15), - ]); +''', + [lint(27, 15)], + ); } test_operator_noFinal() async { @@ -93,11 +99,12 @@ class C { } test_optionalNamed_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({final int? p}) {} -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_optionalNamed_noFinal() async { @@ -107,11 +114,12 @@ void f({int? p}) {} } test_optionalPositional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([final int? p]) {} -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_optionalPositional_noFinal() async { @@ -121,11 +129,12 @@ void f([int? p]) {} } test_optionalPositionalWithDefault_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([final int p = 0]) {} -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_optionalPositionalWithDefault_noFinal() async { @@ -135,11 +144,12 @@ void f([int p = 0]) {} } test_requiredNamed_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({required final int? p}) {} -''', [ - lint(8, 21), - ]); +''', + [lint(8, 21)], + ); } test_requiredNamed_noFinal() async { @@ -149,11 +159,12 @@ void f({required int p}) {} } test_requiredPositional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(final int p) {} -''', [ - lint(7, 11), - ]); +''', + [lint(7, 11)], + ); } test_requiredPositional_noFinal() async { @@ -165,19 +176,21 @@ void f(int p) {} test_requiredPositional_wildcard() async { // Wildcards are treated just like any param. // https://github.com/dart-lang/linter/issues/5045 - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(final int _) {} -''', [ - lint(7, 11), - ]); +''', + [lint(7, 11)], + ); } test_setter_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' set f(final int value) {} -''', [ - lint(6, 15), - ]); +''', + [lint(6, 15)], + ); } test_setter_noFinal() async { @@ -187,7 +200,8 @@ set f(int value) {} } test_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; String? b; @@ -196,13 +210,15 @@ class A { class B extends A { B(final super.a, final super.b); } -''', [ - // TODO(srawlins): Do not report this lint rule here, as it is redundant - // with the Hint. - error(WarningCode.UNNECESSARY_FINAL, 83, 5), - error(WarningCode.UNNECESSARY_FINAL, 98, 5), - lint(83, 13), - lint(98, 13), - ]); +''', + [ + // TODO(srawlins): Do not report this lint rule here, as it is redundant + // with the Hint. + error(WarningCode.UNNECESSARY_FINAL, 83, 5), + error(WarningCode.UNNECESSARY_FINAL, 98, 5), + lint(83, 13), + lint(98, 13), + ], + ); } } diff --git a/pkg/linter/test/rules/avoid_function_literals_in_foreach_calls_test.dart b/pkg/linter/test/rules/avoid_function_literals_in_foreach_calls_test.dart index fa15e7811c46..0630fb835d17 100644 --- a/pkg/linter/test/rules/avoid_function_literals_in_foreach_calls_test.dart +++ b/pkg/linter/test/rules/avoid_function_literals_in_foreach_calls_test.dart @@ -18,12 +18,15 @@ class AvoidFunctionLiteralsInForeachCalls extends LintRuleTest { String get lintRule => LintNames.avoid_function_literals_in_foreach_calls; test_expectedIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic iter) => iter?.forEach(...); -''', [ - // No lint - error(ParserErrorCode.MISSING_IDENTIFIER, 38, 3), - ]); +''', + [ + // No lint + error(ParserErrorCode.MISSING_IDENTIFIER, 38, 3), + ], + ); } test_functionExpression_nullableTarget() async { @@ -43,15 +46,16 @@ void f(Map? people) { } test_functionExpression_targetDoesNotHaveMethodChain() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List> people) { people .first .forEach((person) => print('$person!')); } -''', [ - lint(65, 7), - ]); +''', + [lint(65, 7)], + ); } test_functionExpression_targetHasCascade() async { @@ -89,7 +93,8 @@ void f(List people) { } test_functionExpression_targetInIrrelevantNestedCascade() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List>> lists) { final lists2 = lists..forEach((list) { list.forEach((item) { @@ -97,31 +102,33 @@ void f(List>> lists) { }); }); } -''', [ - lint(91, 7), - ]); +''', + [lint(91, 7)], + ); } test_functionExpressionWithBlockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List people) { people.forEach((person) { print('$person!'); }); } -''', [ - lint(39, 7), - ]); +''', + [lint(39, 7)], + ); } test_functionExpressionWithExpressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List people) { people.forEach((person) => print('$person!')); } -''', [ - lint(39, 7), - ]); +''', + [lint(39, 7)], + ); } test_nonFunctionExpression() async { diff --git a/pkg/linter/test/rules/avoid_futureor_void_test.dart b/pkg/linter/test/rules/avoid_futureor_void_test.dart index d65adeb5dea7..dd88217b4023 100644 --- a/pkg/linter/test/rules/avoid_futureor_void_test.dart +++ b/pkg/linter/test/rules/avoid_futureor_void_test.dart @@ -18,17 +18,19 @@ class AvoidFutureOrVoidTest extends LintRuleTest { String get lintRule => LintNames.avoid_futureor_void; test_asExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; var x = 1 as FutureOr; -''', [ - lint(35, 14), - ]); +''', + [lint(35, 14)], + ); } test_castPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; f() { @@ -36,121 +38,132 @@ f() { var [Object? x as FutureOr] = [1]; return x; } -''', [ - lint(86, 14), - ]); +''', + [lint(86, 14)], + ); } test_class_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; class A> {} -''', [ - lint(40, 14), - ]); +''', + [lint(40, 14)], + ); } test_enum_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; enum E> { one; } -''', [ - lint(39, 14), - ]); +''', + [lint(39, 14)], + ); } test_extension_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; extension E> on X {} -''', [ - lint(44, 14), - ]); +''', + [lint(44, 14)], + ); } test_extensionOnClause() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; extension E on FutureOr {} -''', [ - lint(37, 14), - ]); +''', + [lint(37, 14)], + ); } test_extensionType_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; extension type E>(X x) {} -''', [ - lint(49, 14), - ]); +''', + [lint(49, 14)], + ); } test_extensionType_representation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; extension type E(FutureOr _) {} -''', [ - lint(39, 14), - ]); +''', + [lint(39, 14)], + ); } test_function_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f>(List x) {} -''', [ - lint(39, 14), - ]); +''', + [lint(39, 14)], + ); } test_functionTypedFormalParameter_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(g>(X x)) {} -''', [ - lint(41, 14), - ]); +''', + [lint(41, 14)], + ); } test_functionTypedFormalParameter_parameter1() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(g(FutureOr x)) {} -''', [ - lint(31, 14), - ]); +''', + [lint(31, 14)], + ); } test_functionTypedFormalParameter_parameter2() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(g([FutureOr x])) {} -''', [ - lint(32, 14), - ]); +''', + [lint(32, 14)], + ); } test_functionTypedFormalParameter_parameter3() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(g({required FutureOr name})) {} -''', [ - lint(41, 14), - ]); +''', + [lint(41, 14)], + ); } test_functionTypedFormalParameter_return() async { @@ -162,46 +175,50 @@ void f(FutureOr g()) {} } test_isExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; // ignore: unnecessary_type_check var x = 1 is FutureOr; -''', [ - lint(69, 14), - ]); +''', + [lint(69, 14)], + ); } test_mixin_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; mixin A> {} -''', [ - lint(40, 14), - ]); +''', + [lint(40, 14)], + ); } test_objectPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; f(Object? x) { if (x case FutureOr()) return; } -''', [ - lint(50, 14), - ]); +''', + [lint(50, 14)], + ); } test_oldTypeAlias_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; typedef void F>(X arg); -''', [ - lint(47, 14), - ]); +''', + [lint(47, 14)], + ); } test_oldTypeAlias_parameter() async { @@ -237,12 +254,13 @@ typedef F = void Function(FutureOr); } test_typeAlias_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; typedef F> = int; -''', [ - lint(42, 14), - ]); +''', + [lint(42, 14)], + ); } } diff --git a/pkg/linter/test/rules/avoid_implementing_value_types_test.dart b/pkg/linter/test/rules/avoid_implementing_value_types_test.dart index b490fc0ae19d..eca7cbf13959 100644 --- a/pkg/linter/test/rules/avoid_implementing_value_types_test.dart +++ b/pkg/linter/test/rules/avoid_implementing_value_types_test.dart @@ -49,7 +49,8 @@ class C extends A {} } test_implementsClass_indirectlyWithEqualEqual() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @override bool operator ==(Object o) => false; @@ -58,21 +59,22 @@ class A { class B extends A {} class C implements B {} -''', [ - lint(105, 1), - ]); +''', + [lint(105, 1)], + ); } test_implementsClassWithEqualEqual() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @override bool operator ==(Object o) => false; } class C implements A {} -''', [ - lint(82, 1), - ]); +''', + [lint(82, 1)], + ); } test_implementsClassWithoutEqualEqual() async { diff --git a/pkg/linter/test/rules/avoid_init_to_null_test.dart b/pkg/linter/test/rules/avoid_init_to_null_test.dart index 940122ffa94e..af372e712c55 100644 --- a/pkg/linter/test/rules/avoid_init_to_null_test.dart +++ b/pkg/linter/test/rules/avoid_init_to_null_test.dart @@ -19,29 +19,32 @@ class AvoidInitToNullSuperFormalsTest extends LintRuleTest { String get lintRule => LintNames.avoid_init_to_null; test_forLoop() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i = null; i != null; i++) { } } -''', [ - lint(22, 8), - ]); +''', + [lint(22, 8)], + ); } test_nullableStringInit() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; A({this.a = null}); } -''', [ - lint(28, 13), - ]); +''', + [lint(28, 13)], + ); } test_superInit_2() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; A({this.a = null}); @@ -49,10 +52,9 @@ class A { class B extends A { B({super.a = null}); } -''', [ - lint(28, 13), - lint(72, 14), - ]); +''', + [lint(28, 13), lint(72, 14)], + ); } /// https://github.com/dart-lang/linter/issues/3349 @@ -78,14 +80,15 @@ class AvoidInitToNullTest extends LintRuleTest { String get lintRule => LintNames.avoid_init_to_null; test_fieldFormalParameter_inferredType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int? i; C({this.i = null}); } -''', [ - lint(25, 13), - ]); +''', + [lint(25, 13)], + ); } test_instanceField_inferredType_final() async { @@ -106,65 +109,79 @@ class C { } test_instanceField_nullableIntType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int? i = null; C(): i = 1; } -''', [ - lint(17, 8), - ]); +''', + [lint(17, 8)], + ); } test_invalidAssignment_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class X { int x = null; } -''', [ - // No lint - error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 20, 4), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 20, 4), + ], + ); } test_invalidAssignment_namedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class X { X({int a = null}); } -''', [ - // No lint - error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 23, 4), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 23, 4), + ], + ); } test_invalidAssignment_namedParameter_fieldFormal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class X { int x; X({this.x = null}); } -''', [ - // No lint - error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 33, 4), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 33, 4), + ], + ); } test_invalidAssignment_topLevelVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int i = null; -''', [ - // No lint - error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 8, 4), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.INVALID_ASSIGNMENT, 8, 4), + ], + ); } test_namedParameter_inferredType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' foo({p = null}) {} -''', [ - lint(5, 8), - ]); +''', + [lint(5, 8)], + ); } test_namedParameter_inferredType_defaultValueIsInt() async { @@ -180,19 +197,21 @@ foo({p}) {} } test_namedParameter_inferredType_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' foo({var p = null}) {} -''', [ - lint(5, 12), - ]); +''', + [lint(5, 12)], + ); } test_optionalParameter_inferredType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' foo([p = null]) {} -''', [ - lint(5, 8), - ]); +''', + [lint(5, 8)], + ); } test_optionalParameter_inferredType_defaultValueIsInt() async { @@ -208,11 +227,12 @@ foo([p]) {} } test_optionalParameter_inferredType_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' foo([var p = null]) {} -''', [ - lint(5, 12), - ]); +''', + [lint(5, 12)], + ); } test_staticConstField_inferredType_final() async { @@ -224,19 +244,21 @@ class C { } test_topLevelVariable_dynamic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic i = null; -''', [ - lint(8, 8), - ]); +''', + [lint(8, 8)], + ); } test_topLevelVariable_inferredType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var i = null; -''', [ - lint(4, 8), - ]); +''', + [lint(4, 8)], + ); } test_topLevelVariable_inferredType_const() async { @@ -264,10 +286,11 @@ var i; } test_topLevelVariable_nullableType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? ii = null; -''', [ - lint(5, 9), - ]); +''', + [lint(5, 9)], + ); } } diff --git a/pkg/linter/test/rules/avoid_js_rounded_ints_test.dart b/pkg/linter/test/rules/avoid_js_rounded_ints_test.dart index 76de8ac56d02..4f781d7e8d91 100644 --- a/pkg/linter/test/rules/avoid_js_rounded_ints_test.dart +++ b/pkg/linter/test/rules/avoid_js_rounded_ints_test.dart @@ -30,19 +30,21 @@ final r = -9007199254740991; } test_maxSafeInteger_plusTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final r = 9007199254740993; -''', [ - lint(10, 16), - ]); +''', + [lint(10, 16)], + ); } test_maxSafeInteger_plusTwo_negative() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final r = -9007199254740993; -''', [ - lint(11, 16), - ]); +''', + [lint(11, 16)], + ); } test_smallInt() async { @@ -64,11 +66,12 @@ final r = 1000000000000000000; } test_tenToTheEighteen_plusOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final r = 1000000000000000001; -''', [ - lint(10, 19), - ]); +''', + [lint(10, 19)], + ); } test_twoToTheSixtyThree_negative() async { diff --git a/pkg/linter/test/rules/avoid_multiple_declarations_per_line_test.dart b/pkg/linter/test/rules/avoid_multiple_declarations_per_line_test.dart index 7b0dfe96d389..b93955e5d0c6 100644 --- a/pkg/linter/test/rules/avoid_multiple_declarations_per_line_test.dart +++ b/pkg/linter/test/rules/avoid_multiple_declarations_per_line_test.dart @@ -18,13 +18,14 @@ class AvoidMultipleDeclarationsPerLineTest extends LintRuleTest { String get lintRule => LintNames.avoid_multiple_declarations_per_line; test_extensionField_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on Object { static String? a, b, c; } -''', [ - lint(44, 1), - ]); +''', + [lint(44, 1)], + ); } test_extensionField_single() async { @@ -36,13 +37,14 @@ extension E on Object { } test_field_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? a, b, c; } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_field_single() async { @@ -63,13 +65,14 @@ void f() { } test_functionVariable_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { String? a, b, c; } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_functionVariable_single() async { @@ -81,11 +84,12 @@ void f() { } test_topLevel_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String? a, b, c; -''', [ - lint(11, 1), - ]); +''', + [lint(11, 1)], + ); } test_topLevel_single() async { diff --git a/pkg/linter/test/rules/avoid_null_checks_in_equality_operators_test.dart b/pkg/linter/test/rules/avoid_null_checks_in_equality_operators_test.dart index e7d3ded58f50..fb4f92c3e58c 100644 --- a/pkg/linter/test/rules/avoid_null_checks_in_equality_operators_test.dart +++ b/pkg/linter/test/rules/avoid_null_checks_in_equality_operators_test.dart @@ -19,7 +19,8 @@ class AvoidNullChecksInEqualityOperatorsTest extends LintRuleTest { test_dynamicParameter_neNull() async { // https://github.com/dart-lang/linter/issues/2864 - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override @@ -27,26 +28,28 @@ class C { return other != null && other is C && foo == other.foo; } } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - ]); +''', + [error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2)], + ); } test_dynamicParameter_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override operator ==(dynamic other) => other is C && foo == other.foo; } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - ]); +''', + [error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2)], + ); } test_nonNullableParameter_neNull() async { // https://github.com/dart-lang/linter/issues/2864 - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override @@ -54,41 +57,42 @@ class C { return other != null && other is C && foo == other.foo; } } -''', [ - error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 88, 7), - ]); +''', + [error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 88, 7)], + ); } test_nullableParameter_eqeqNull_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override operator ==(Object? other) => !(other == null) && other is C && foo == other.foo; } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - lint(85, 13), - ]); +''', + [error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), lint(85, 13)], + ); } test_nullableParameter_eqeqNull_not_parens() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override operator ==(Object? other) => !((other) == null) && (other) is C && foo == (other.foo); } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - lint(85, 15), - ]); +''', + [error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), lint(85, 15)], + ); } test_nullableParameter_fieldComparisonOnLocal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo; C(this.foo); @@ -102,38 +106,43 @@ class C { } } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 62, 2), - lint(126, 14), - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 135, 5), - ]); +''', + [ + error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 62, 2), + lint(126, 14), + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 135, 5), + ], + ); } test_nullableParameter_neNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override operator ==(Object? other) => other != null && other is C && foo == other.foo; } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - lint(83, 13), - ]); +''', + [error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), lint(83, 13)], + ); } test_nullableParameter_nullAwarePropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String foo = ''; @override operator ==(Object? other) => other is C && foo == other?.foo; } -''', [ - error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), - lint(94, 10), - error(StaticWarningCode.INVALID_NULL_AWARE_OPERATOR, 99, 2), - ]); +''', + [ + error(WarningCode.NON_NULLABLE_EQUALS_PARAMETER, 52, 2), + lint(94, 10), + error(StaticWarningCode.INVALID_NULL_AWARE_OPERATOR, 99, 2), + ], + ); } } diff --git a/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart b/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart index ca67573a7fd0..d280973f0b28 100644 --- a/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart @@ -85,14 +85,15 @@ class C { } test_constructor_fieldFormalParameter_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { bool p; C.named(this.p); } -''', [ - lint(30, 6), - ]); +''', + [lint(30, 6)], + ); } test_constructor_named_withDefault() async { @@ -105,14 +106,15 @@ class C { } test_constructor_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.named(bool a) { } } -''', [ - lint(20, 6), - ]); +''', + [lint(20, 6)], + ); } test_constructorPrivate_positionalOptional() async { @@ -125,24 +127,26 @@ class C { } test_extensionMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension Ext on int { void f([bool p = false]) {} } -''', [ - lint(33, 14), - ]); +''', + [lint(33, 14)], + ); } test_extensionMethod_unnamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension on int { // ignore: unused_element, unused_element_parameter void f([bool p = false]) {} } -''', [ - lint(83, 14), - ]); +''', + [lint(83, 14)], + ); } test_instanceMethod_named() async { @@ -157,7 +161,8 @@ class C { // TODO(srawlins): Test where the parameter in the override is _not found_ // in the parent interface. // TODO(srawlins): Test where the parameter is renamed. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m([bool p = false]) {} } @@ -165,13 +170,14 @@ class D extends C { @override void m([bool p = false]) {} } -''', [ - lint(20, 14), - ]); +''', + [lint(20, 14)], + ); } test_instanceMethod_overrideImplements_positionalOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m([bool p = false]) {} } @@ -179,29 +185,31 @@ abstract class D implements C { @override void m([bool p = false]) {} } -''', [ - lint(20, 14), - ]); +''', + [lint(20, 14)], + ); } test_instanceMethod_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(bool p) {} } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_instanceMethod_positionalOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m([bool p = false]) {} } -''', [ - lint(20, 14), - ]); +''', + [lint(20, 14)], + ); } test_instanceSetter() async { @@ -246,13 +254,14 @@ class B { } test_staticMethod_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { static void m(bool p) {} } -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_topLevel_namedParameter() async { @@ -268,11 +277,12 @@ void f({bool p = false}) {} } test_topLevel_positionalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool p) {} -''', [ - lint(7, 6), - ]); +''', + [lint(7, 6)], + ); } test_topLevelPrivate() async { @@ -289,10 +299,11 @@ typedef T = Function({bool p}); } test_typedef_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef T = Function(bool p); -''', [ - lint(21, 6), - ]); +''', + [lint(21, 6)], + ); } } diff --git a/pkg/linter/test/rules/avoid_print_test.dart b/pkg/linter/test/rules/avoid_print_test.dart index 99acd52236c1..67741b81efdb 100644 --- a/pkg/linter/test/rules/avoid_print_test.dart +++ b/pkg/linter/test/rules/avoid_print_test.dart @@ -21,13 +21,14 @@ class AvoidPrintTest extends LintRuleTest { String get lintRule => LintNames.avoid_print; test_directCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print('ha'); } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_kDebugMode_blockStatement() async { @@ -62,23 +63,25 @@ void f(A a) { } test_tearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [1,2,3].forEach(print); } -''', [ - lint(29, 5), - ]); +''', + [lint(29, 5)], + ); } test_tearoff2() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Future.value('hello').then(print); } -''', [ - lint(40, 5), - ]); +''', + [lint(40, 5)], + ); } test_tearoff_assigned_thenCalled() async { diff --git a/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart b/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart index 1e68c99f55d9..5082379c3b80 100644 --- a/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart +++ b/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart @@ -17,10 +17,10 @@ main() { class AvoidPrivateTypedefFunctionsTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.avoid_private_typedef_functions; @@ -71,12 +71,13 @@ typedef _Td = void Function(); } test_private_genericFunctionTypeAlias_usedOneTime() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef _Td = int Function(); late _Td td; -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_private_genericFunctionTypeAlias_usedOneTime_declaredInPart() async { @@ -84,12 +85,13 @@ late _Td td; part 'test.dart'; late _Td td; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'lib.dart'; typedef _Td = void Function(); -''', [ - lint(28, 3), - ]); +''', + [lint(28, 3)], + ); } test_private_genericFunctionTypeAlias_usedOneTime_usedInPart() async { @@ -97,28 +99,31 @@ typedef _Td = void Function(); part of 'test.dart'; late _Td td; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part 'part.dart'; typedef _Td = void Function(); -''', [ - lint(26, 3), - ]); +''', + [lint(26, 3)], + ); } test_private_genericFunctionTypeAlias_usedZeroTimes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef _Td = int Function(); -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_private_legacyTypeAlias_usedZeroTimes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef int _Td(); -''', [ - lint(12, 3), - ]); +''', + [lint(12, 3)], + ); } test_public_genericFunctionTypeAlias_usedZeroTimes() async { diff --git a/pkg/linter/test/rules/avoid_redundant_argument_values_test.dart b/pkg/linter/test/rules/avoid_redundant_argument_values_test.dart index 64df6b5db99b..68b0adf23684 100644 --- a/pkg/linter/test/rules/avoid_redundant_argument_values_test.dart +++ b/pkg/linter/test/rules/avoid_redundant_argument_values_test.dart @@ -19,15 +19,16 @@ class AvoidRedundantArgumentValuesNamedArgsAnywhereTest extends LintRuleTest { String get lintRule => LintNames.avoid_redundant_argument_values; test_namedArgumentBeforePositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo(int a, int b, {bool c = true}) {} void f() { foo(0, c: true, 1); } -''', [ - lint(67, 4), - ]); +''', + [lint(67, 4)], + ); } } @@ -37,20 +38,22 @@ class AvoidRedundantArgumentValuesTest extends LintRuleTest { String get lintRule => LintNames.avoid_redundant_argument_values; test_constructor_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { A(p: true); } class A { A({bool p = true}); } -''', [ - lint(18, 4), - ]); +''', + [lint(18, 4)], + ); } test_constructor_tearoff_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var aNew = A.new; aNew(p: true); @@ -58,14 +61,15 @@ void f() { class A { A({bool p = true}); } -''', [ - lint(41, 4), - ]); +''', + [lint(41, 4)], + ); } /// https://github.com/dart-lang/linter/issues/3617 test_enumDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum TestEnum { a(test: false); @@ -73,9 +77,9 @@ enum TestEnum { final bool test; } -''', [ - lint(26, 5), - ]); +''', + [lint(26, 5)], + ); } @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/3447') @@ -112,14 +116,15 @@ void g([int? a, int? b = 1]) {} } test_function_optionalPositional_subsequent_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(0, 1); } void g([int? a, int? b = 1]) {} -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_localFunction_optionalNamed_different() async { @@ -132,14 +137,15 @@ void f() { } test_localFunction_optionalNamed_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void g({bool p = true}) {} g(p: true); } -''', [ - lint(47, 4), - ]); +''', + [lint(47, 4)], + ); } test_method_noDefault() async { @@ -165,16 +171,17 @@ class A { } test_method_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { a.g(p: true); } class A { void g({bool p = true}) {} } -''', [ - lint(23, 4), - ]); +''', + [lint(23, 4)], + ); } test_redirectingFactoryConstructor() async { @@ -195,7 +202,8 @@ void f() { } test_redirectingFactoryConstructor_cyclic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { factory A.foo() = A.bar; factory A.bar() = A.foo; @@ -203,11 +211,13 @@ class A { void f() { A.foo(); } -''', [ - // No lint. - error(CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, 30, 5), - error(CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, 57, 5), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, 30, 5), + error(CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT, 57, 5), + ], + ); } test_redirectingFactoryConstructor_multipleOptional() async { @@ -247,7 +257,8 @@ void f() { } test_redirectingFactoryConstructor_named_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { factory A({int? value}) = B; A._(); @@ -258,9 +269,9 @@ class B extends A { void f() { A(value: 2); } -''', [ - lint(124, 8), - ]); +''', + [lint(124, 8)], + ); } test_redirectingFactoryConstructor_namedArgumentsAnywhere() async { @@ -283,7 +294,8 @@ void f() { } test_redirectingFactoryConstructor_namedArgumentsAnywhere_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { factory A(int? one, int? two, {int? three}) = B; A._(); @@ -294,9 +306,9 @@ class B extends A { void f() { A(1, three: 3, 2); } -''', [ - lint(167, 8), - ]); +''', + [lint(167, 8)], + ); } test_redirectingFactoryConstructor_nested() async { @@ -325,7 +337,8 @@ void f() { } test_redirectingFactoryConstructor_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { factory A([int? value]) = B; A._(); @@ -336,9 +349,9 @@ class B extends A { void f() { A(2); } -''', [ - lint(124, 1), - ]); +''', + [lint(124, 1)], + ); } test_redirectingGenerativeConstructor() async { @@ -366,7 +379,8 @@ void f() { } test_redirectingGenerativeConstructor_named_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A({int? value}) : this._(value: value); A._({int? value = 2}); @@ -374,13 +388,14 @@ class A { void f() { A(value: null); } -''', [ - lint(101, 4), - ]); +''', + [lint(101, 4)], + ); } test_redirectingGenerativeConstructor_redundant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A([int? value]) : this._(value); A._([int? value = 2]); @@ -388,9 +403,9 @@ class A { void f() { A(null); } -''', [ - lint(87, 4), - ]); +''', + [lint(87, 4)], + ); } test_requiredNullable() async { @@ -405,12 +420,13 @@ void main() { @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/4967') test_toListOptionalGrowable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { [].toList(growable: true); } -''', [ - lint(26, 8), - ]); +''', + [lint(26, 8)], + ); } } diff --git a/pkg/linter/test/rules/avoid_relative_lib_imports_test.dart b/pkg/linter/test/rules/avoid_relative_lib_imports_test.dart index 3e75464d6a51..28c626e704cf 100644 --- a/pkg/linter/test/rules/avoid_relative_lib_imports_test.dart +++ b/pkg/linter/test/rules/avoid_relative_lib_imports_test.dart @@ -35,9 +35,7 @@ class C {} /// This provides [C]. import '../lib/lib.dart'; '''); - await assertDiagnosticsInFile(test.path, [ - lint(30, 17), - ]); + await assertDiagnosticsInFile(test.path, [lint(30, 17)]); } test_samePackage_relativeUri_inPart() async { @@ -55,8 +53,6 @@ part of 'a.dart'; /// This provides [C]. import '../lib/lib.dart'; '''); - await assertDiagnosticsInFile(test.path, [ - lint(49, 17), - ]); + await assertDiagnosticsInFile(test.path, [lint(49, 17)]); } } diff --git a/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart b/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart index 8bca4582d82e..8b1b5d4bf052 100644 --- a/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart @@ -25,8 +25,9 @@ class AvoidRenamingMethodParametersTest extends LintRuleTest { String get lintRule => LintNames.avoid_renaming_method_parameters; @FailingTest( - reason: 'lint is limited to methods', - issue: 'https://github.com/dart-lang/linter/issues/4891') + reason: 'lint is limited to methods', + issue: 'https://github.com/dart-lang/linter/issues/4891', + ) test_augmentedFunction() async { newFile('$testPackageLibPath/a.dart', r''' part 'test.dart'; @@ -34,13 +35,14 @@ part 'test.dart'; void f(int p) {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment void f(int q) {} -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_augmentedMethod() async { @@ -52,20 +54,24 @@ class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { augment void m(int q) {} augment void m(int q) {} } -''', [ - lint(58, 1), // Only the first augmentation gets linted. - ]); +''', + [ + lint(58, 1), // Only the first augmentation gets linted. + ], + ); } test_enumMixingIn() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin class C { int f(int f) => f; } @@ -74,22 +80,23 @@ enum A with C { @override int f(int x) => x; } -''', [ - lint(88, 1), - ]); +''', + [lint(88, 1)], + ); } test_optionalPositional_renamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m([int p = 0]) {} } class B extends A { void m([int q = 0]) {} } -''', [ - lint(71, 1), - ]); +''', + [lint(71, 1)], + ); } test_positional_docComments() async { @@ -117,16 +124,17 @@ class _B extends A { } test_positional_renamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(int p) {} } class B extends A { void m(int q) {} } -''', [ - lint(64, 1), - ]); +''', + [lint(64, 1)], + ); } test_positional_renamed_nonLibSource() async { @@ -167,7 +175,8 @@ class B extends A { } test_wildcard_featureDisabledFails() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // @dart = 3.4 // (pre wildcard-variables) @@ -177,9 +186,9 @@ class A { class B extends A { void m(_) {} } -''', [ - lint(104, 1), - ]); +''', + [lint(104, 1)], + ); } test_wildcard_mixed() async { @@ -194,16 +203,17 @@ class B extends A { } test_wildcard_mixedFails() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(int a, int b, int c) {} } class B extends A { void m(_, c, _) {} } -''', [ - lint(77, 1), - ]); +''', + [lint(77, 1)], + ); } test_wildcard_multipleWildcards() async { @@ -218,29 +228,31 @@ class B extends A { } test_wildcard_nonWildcardButUnderscoreBefore() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(int a, int b) {} } class B extends A { void m(_, _b) {} } -''', [ - lint(70, 2), - ]); +''', + [lint(70, 2)], + ); } test_wildcard_nonWildcardButUnderscoresAround() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(int p) {} } class B extends A { void m(_p_) {} } -''', [ - lint(60, 3), - ]); +''', + [lint(60, 3)], + ); } test_wildcardInBase() async { diff --git a/pkg/linter/test/rules/avoid_return_types_on_setters_test.dart b/pkg/linter/test/rules/avoid_return_types_on_setters_test.dart index fddca275d010..605ff18881e0 100644 --- a/pkg/linter/test/rules/avoid_return_types_on_setters_test.dart +++ b/pkg/linter/test/rules/avoid_return_types_on_setters_test.dart @@ -32,13 +32,14 @@ class C { } test_instanceSetter_voidReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void set f(int p) {} } -''', [ - lint(12, 4), - ]); +''', + [lint(12, 4)], + ); } test_staticSetter_implicitReturnType() async { @@ -50,20 +51,22 @@ class C { } test_staticSetter_voidReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void set f(String p) {} } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_voidReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void set f(int p) {} -''', [ - lint(0, 4), - ]); +''', + [lint(0, 4)], + ); } } diff --git a/pkg/linter/test/rules/avoid_returning_null_for_void_test.dart b/pkg/linter/test/rules/avoid_returning_null_for_void_test.dart index ad7a6e59f8b9..d7c0120f388f 100644 --- a/pkg/linter/test/rules/avoid_returning_null_for_void_test.dart +++ b/pkg/linter/test/rules/avoid_returning_null_for_void_test.dart @@ -17,21 +17,22 @@ main() { class AvoidReturningNullForVoidTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => 'avoid_returning_null_for_void'; test_function_async_returnsFutureVoid_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f3f() async { return null; } -''', [ - lint(29, 12), - ]); +''', + [lint(29, 12)], + ); } test_function_async_returnsFutureVoid_expressionBody_returnNothing() async { @@ -41,11 +42,12 @@ Future f() async => print(''); } test_function_async_returnsFutureVoid_expressionBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async => null; -''', [ - lint(17, 14), - ]); +''', + [lint(17, 14)], + ); } test_function_blockBody_conditional_returnNothing() async { @@ -59,15 +61,16 @@ void f(bool b) { } test_function_blockBody_conditional_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool b) { if (b) { return null; } } -''', [ - lint(32, 12), - ]); +''', + [lint(32, 12)], + ); } test_function_blockBody_returnNothing() async { @@ -79,13 +82,14 @@ void f() { } test_function_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { return null; } -''', [ - lint(13, 12), - ]); +''', + [lint(13, 12)], + ); } test_function_expressionBody_returnNothing() async { @@ -95,11 +99,12 @@ void f() => print(''); } test_function_expressionBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() => null; -''', [ - lint(9, 8), - ]); +''', + [lint(9, 8)], + ); } test_function_expressionBody_returnNullExpressionResult() async { @@ -110,102 +115,117 @@ void f() => nullFromGetter; } test_localFunction_async_returnsFutureVoid_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Future g() async { return null; } } -''', [ - lint(42, 12), - ]); +''', + [lint(42, 12)], + ); } test_localFunction_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void g() { return null; } } -''', [ - lint(28, 12), - ]); +''', + [lint(28, 12)], + ); } test_localFunction_expressionBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void g() => null; } -''', [ - lint(22, 8), - ]); +''', + [lint(22, 8)], + ); } test_method_class_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m() { return null; } } -''', [ - lint(27, 12), - ]); +''', + [lint(27, 12)], + ); } test_method_inClass_blockBody_async_returnsFutureVoid_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { Future m() async { return null; } } -''', [ - lint(41, 12), - ]); +''', + [lint(41, 12)], + ); } test_method_inExtension_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { void f() { return null; } } -''', [lint(38, 12)]); +''', + [lint(38, 12)], + ); } test_method_inExtensionType_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { void f() { return null; } } -''', [lint(43, 12)]); +''', + [lint(43, 12)], + ); } test_method_inMixin_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M { void f() { return null; } } -''', [lint(27, 12)]); +''', + [lint(27, 12)], + ); } test_staticMethod_inClass_blockBody_returnNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m() { return null; } } -''', [ - lint(34, 12), - ]); +''', + [lint(34, 12)], + ); } } diff --git a/pkg/linter/test/rules/avoid_returning_this_test.dart b/pkg/linter/test/rules/avoid_returning_this_test.dart index 9663722407ff..9ffd7939d331 100644 --- a/pkg/linter/test/rules/avoid_returning_this_test.dart +++ b/pkg/linter/test/rules/avoid_returning_this_test.dart @@ -95,15 +95,16 @@ class A { } test_methodReturnsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A m() { return this; } } -''', [ - lint(31, 4), - ]); +''', + [lint(31, 4)], + ); } test_methodReturnsThis_arrow_subclassOfGeneric_definedInInterface() async { @@ -131,7 +132,8 @@ class E implements C { } test_methodReturnsThis_containsFunctionExpressionWithBlockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 1; A m() { @@ -142,13 +144,14 @@ class A { return this; } } -''', [ - lint(99, 4), - ]); +''', + [lint(99, 4)], + ); } test_methodReturnsThis_containsFunctionExpressionWithExpressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 1; A m() { @@ -157,20 +160,21 @@ class A { return this; } } -''', [ - lint(75, 4), - ]); +''', + [lint(75, 4)], + ); } test_methodReturnsThis_inEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a, b, c; A m() => this; } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_methodReturnsThis_otherReturnType() async { @@ -198,16 +202,17 @@ class B extends A { } test_methodReturnsThis_subclass_notDefinedInInterface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} class B extends A{ B m() { return this; } } -''', [ - lint(51, 4), - ]); +''', + [lint(51, 4)], + ); } test_operatorReturnsThis() async { diff --git a/pkg/linter/test/rules/avoid_setters_without_getters_test.dart b/pkg/linter/test/rules/avoid_setters_without_getters_test.dart index cdf0211ecbd8..6a9ddd143117 100644 --- a/pkg/linter/test/rules/avoid_setters_without_getters_test.dart +++ b/pkg/linter/test/rules/avoid_setters_without_getters_test.dart @@ -60,13 +60,14 @@ class B extends A { } test_class_setter_noGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { set x(int value) {} } -''', [ - lint(16, 1), - ]); +''', + [lint(16, 1)], + ); } test_class_static_getter_setter() async { @@ -79,23 +80,25 @@ class A { } test_enum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; set x(int x) {} } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type B(int a) { set i(int i) {} } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } } diff --git a/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart b/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart index 25078d797eac..82336cb2ac16 100644 --- a/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart @@ -17,9 +17,9 @@ main() { class AvoidShadowingTypeParametersTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.avoid_shadowing_type_parameters; @@ -52,21 +52,23 @@ typedef Fn2 = void Function(T); } test_functionType_shadowingTypedef() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef Fn1 = void Function(T); -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } @FailingTest(reason: '') test_functionTypedParameter_shadowingFunction() async { // TODO(srawlins): Report lint here. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void fn2(void Function()) {} -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_localFunction_noShadowing() async { @@ -78,29 +80,32 @@ void f() { } test_localFunction_shadowingClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { void g() {} } } -''', [ - lint(37, 1), - ]); +''', + [lint(37, 1)], + ); } test_localFunction_shadowingFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void g() {} } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_localFunction_shadowingLocalFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { void g() { @@ -108,21 +113,22 @@ class C { } } } -''', [ - lint(54, 1), - ]); +''', + [lint(54, 1)], + ); } test_localFunction_shadowingMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void fn1() { void fn3() {} } } -''', [ - lint(44, 1), - ]); +''', + [lint(44, 1)], + ); } test_method_noShadowing() async { @@ -134,54 +140,59 @@ class C { } test_method_shadowingClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() {} } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_method_shadowingEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { a, b, c; void fn() {} } -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_method_shadowingExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on List { void f() {} } -''', [ - lint(37, 1), - ]); +''', + [lint(37, 1)], + ); } test_method_shadowingExtensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { void m() {} } -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_method_shadowingMixin() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M { void f() {} } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_staticMethod_shadowingClass() async { @@ -201,14 +212,17 @@ class A<_> { } test_wrongNumberOfTypeArguments() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef Predicate = bool (E element); -''', [ - // No lint. - error(CompileTimeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS, 20, 8), - error(CompileTimeErrorCode.NON_TYPE_AS_TYPE_ARGUMENT, 26, 1), - error(ParserErrorCode.EXPECTED_TOKEN, 28, 1), - error(CompileTimeErrorCode.UNDEFINED_CLASS, 29, 1), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS, 20, 8), + error(CompileTimeErrorCode.NON_TYPE_AS_TYPE_ARGUMENT, 26, 1), + error(ParserErrorCode.EXPECTED_TOKEN, 28, 1), + error(CompileTimeErrorCode.UNDEFINED_CLASS, 29, 1), + ], + ); } } diff --git a/pkg/linter/test/rules/avoid_single_cascade_in_expression_statements_test.dart b/pkg/linter/test/rules/avoid_single_cascade_in_expression_statements_test.dart index bb6dd5957c77..031d7c49730c 100644 --- a/pkg/linter/test/rules/avoid_single_cascade_in_expression_statements_test.dart +++ b/pkg/linter/test/rules/avoid_single_cascade_in_expression_statements_test.dart @@ -27,13 +27,14 @@ void f(int p) { } test_singleCascade() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p..toString(); } -''', [ - lint(18, 13), - ]); +''', + [lint(18, 13)], + ); } test_singleCascade_asArgument() async { diff --git a/pkg/linter/test/rules/avoid_slow_async_io_test.dart b/pkg/linter/test/rules/avoid_slow_async_io_test.dart index 6322cfe05bbc..b46d04ee21dc 100644 --- a/pkg/linter/test/rules/avoid_slow_async_io_test.dart +++ b/pkg/linter/test/rules/avoid_slow_async_io_test.dart @@ -18,14 +18,15 @@ class AvoidSlowAsyncIoTest extends LintRuleTest { String get lintRule => LintNames.avoid_slow_async_io; test_directory_exists() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(Directory dir) async { await dir.exists(); } -''', [ - lint(56, 12), - ]); +''', + [lint(56, 12)], + ); } test_directory_existsSync() async { @@ -38,14 +39,15 @@ void f(Directory dir) async { } test_directory_stat() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(Directory dir) async { await dir.stat(); } -''', [ - lint(56, 10), - ]); +''', + [lint(56, 10)], + ); } test_directory_statSync() async { @@ -58,14 +60,15 @@ void f(Directory dir) async { } test_file_exists() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(File file) async { await file.exists(); } -''', [ - lint(52, 13), - ]); +''', + [lint(52, 13)], + ); } test_file_existsSync() async { @@ -78,14 +81,15 @@ void f(File file) async { } test_file_lastModified() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(File file) async { await file.lastModified(); } -''', [ - lint(52, 19), - ]); +''', + [lint(52, 19)], + ); } test_file_lastModifiedSync() async { @@ -98,14 +102,15 @@ void f(File file) async { } test_file_stat() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(File file) async { await file.stat(); } -''', [ - lint(52, 11), - ]); +''', + [lint(52, 11)], + ); } test_file_statSync() async { @@ -118,14 +123,15 @@ void f(File file) async { } test_fileSystemEntity_isDirectory() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(String path) async { await FileSystemEntity.isDirectory(path); } -''', [ - lint(54, 34), - ]); +''', + [lint(54, 34)], + ); } test_fileSystemEntity_isDirectorySync() async { @@ -138,14 +144,15 @@ void f(String path) async { } test_fileSystemEntity_isFile() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(String path) async { await FileSystemEntity.isFile(path); } -''', [ - lint(54, 29), - ]); +''', + [lint(54, 29)], + ); } test_fileSystemEntity_isFileSync() async { @@ -158,14 +165,15 @@ void f(String path) async { } test_fileSystemEntity_isLink() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(String path) async { await FileSystemEntity.isLink(path); } -''', [ - lint(54, 29), - ]); +''', + [lint(54, 29)], + ); } test_fileSystemEntity_isLinkSync() async { @@ -178,14 +186,15 @@ void f(String path) async { } test_fileSystemEntity_type() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void f(String path) async { FileSystemEntity.type(path); } -''', [ - lint(48, 27), - ]); +''', + [lint(48, 27)], + ); } test_fileSystemEntity_typeSync() async { diff --git a/pkg/linter/test/rules/avoid_type_to_string_test.dart b/pkg/linter/test/rules/avoid_type_to_string_test.dart index 9c232324b5af..e55d053e1991 100644 --- a/pkg/linter/test/rules/avoid_type_to_string_test.dart +++ b/pkg/linter/test/rules/avoid_type_to_string_test.dart @@ -18,78 +18,85 @@ class AvoidTypeToStringTest extends LintRuleTest { String get lintRule => LintNames.avoid_type_to_string; test_extensionOnType_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on Type { void f() { toString(); } } -''', [ - lint(39, 8), - ]); +''', + [lint(39, 8)], + ); } test_extensionType_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { m() { runtimeType.toString(); } } -''', [ - lint(50, 8), - ]); +''', + [lint(50, 8)], + ); } test_extensionType_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { m() { E(i).runtimeType.toString(); } } -''', [ - lint(55, 8), - ]); +''', + [lint(55, 8)], + ); } test_mixinOnType_explicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M on Type { late var x = this.toString(); } -''', [ - lint(38, 8), - ]); +''', + [lint(38, 8)], + ); } test_mixinOnType_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M on Type { late var x = toString(); } -''', [ - lint(33, 8), - ]); +''', + [lint(33, 8)], + ); } test_runtimeType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 7.runtimeType.toString(); -''', [ - lint(22, 8), - ]); +''', + [lint(22, 8)], + ); } test_type_tearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { foo(7.runtimeType.toString); } void foo(String Function() p) {} -''', [ - lint(31, 8), - ]); +''', + [lint(31, 8)], + ); } test_typeExtendingType_withToStringOverride() async { @@ -105,89 +112,97 @@ class Type2 extends Type with M { } test_typeThatExtendsType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = Type2().toString(); class Type2 extends Type {} -''', [ - lint(16, 8), - ]); +''', + [lint(16, 8)], + ); } test_typeThatExtendsType_explicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type { late var x = this.toString(); } -''', [ - lint(47, 8), - ]); +''', + [lint(47, 8)], + ); } test_typeThatExtendsType_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type { late var x = toString(); } -''', [ - lint(42, 8), - ]); +''', + [lint(42, 8)], + ); } test_typeThatExtendsType_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type { late var x = super.toString(); } -''', [ - lint(48, 8), - ]); +''', + [lint(48, 8)], + ); } test_typeThatExtendsType_tearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type {} void f(Type2 t) { foo(t.toString); } void foo(String Function() p) {} -''', [ - lint(54, 8), - ]); +''', + [lint(54, 8)], + ); } test_typeThatExtendsType_tearoff_explicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type { void f() { foo(this.toString); } void foo(String Function() p) {} } -''', [ - lint(53, 8), - ]); +''', + [lint(53, 8)], + ); } test_typeThatExtendsType_tearoff_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Type2 extends Type { void f() { foo(toString); } void foo(String Function() p) {} } -''', [ - lint(48, 8), - ]); +''', + [lint(48, 8)], + ); } test_typeThatExtendsTypeThatExtendsType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = Type3().toString(); class Type2 extends Type {} class Type3 extends Type2 {} -''', [ - lint(16, 8), - ]); +''', + [lint(16, 8)], + ); } } diff --git a/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart b/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart index 187f72cc5a34..77c1db322c36 100644 --- a/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart +++ b/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart @@ -18,36 +18,39 @@ class AvoidTypesAsParameterNamesTest extends LintRuleTest { String get lintRule => LintNames.avoid_types_as_parameter_names; test_catchClauseParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} void f() { try {} catch (C) {} } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { } void f(E) { } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_factoryParameter_shadowingTypeParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { factory C(X) => C.name(); C.name(); } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_fieldFormalParameter_missingType() async { @@ -60,27 +63,30 @@ class C { } test_functionTypedParameter_missingName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(void g(int)) {} -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } test_functionTypedParameter_missingType_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(void g({int})) {} -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_functionTypedParameter_missingType_optionalPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(void g([int])) {} -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_functionTypedParameter_noShadowing() async { @@ -110,11 +116,12 @@ void f(int Function(T) g) {} } test_parameter_shadowingTypeParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(X) {} -''', [ - lint(10, 1), - ]); +''', + [lint(10, 1)], + ); } test_parameterIsFunctionName() async { @@ -125,16 +132,18 @@ void g() {} } test_parameterIsTypedefName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(T) {} typedef T = int; -''', [ - lint(7, 1), - ]); +''', + [lint(7, 1)], + ); } test_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String a; A(this.a); @@ -142,33 +151,36 @@ class A { class B extends A { B(super.String); } -''', [ - lint(67, 6), - ]); +''', + [lint(67, 6)], + ); } test_typedefParameter_legacy_missingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef void T(int); -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_typedefParameter_legacy_missingType_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef void T({int}); -''', [ - lint(16, 3), - ]); +''', + [lint(16, 3)], + ); } test_typedefParameter_legacy_missingType_optionalPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef void f([int]); -''', [ - lint(16, 3), - ]); +''', + [lint(16, 3)], + ); } test_typedefParameter_legacy_noShadowing() async { @@ -190,13 +202,14 @@ typedef T = int Function(int); } test_typeParameter_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C<_> { var _; C.c(this._, _); } -''', [ - error(WarningCode.UNUSED_FIELD, 19, 1), - ]); +''', + [error(WarningCode.UNUSED_FIELD, 19, 1)], + ); } } diff --git a/pkg/linter/test/rules/avoid_types_on_closure_parameters_test.dart b/pkg/linter/test/rules/avoid_types_on_closure_parameters_test.dart index b167bd07c984..43ab24d2894a 100644 --- a/pkg/linter/test/rules/avoid_types_on_closure_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_types_on_closure_parameters_test.dart @@ -26,26 +26,28 @@ void f(List list) { } test_argument_typedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.map((int e) => e.isEven); } -''', [ - lint(37, 3), - ]); +''', + [lint(37, 3)], + ); } test_assignedToFunctionTypedTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.onFoo = (int p) {}; } class C { void Function(int p)? onFoo; } -''', [ - lint(27, 3), - ]); +''', + [lint(27, 3)], + ); } test_assignedToNonFunctionTypedTarget() async { @@ -107,52 +109,56 @@ class C { } test_closureIsArgument_parameterIsTyped_functionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.map((int p(int x)) => p(0)); } -''', [ - lint(51, 12), - ]); +''', + [lint(51, 12)], + ); } test_closureIsArgument_parameterIsTyped_namedRequired() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.map(({required int p}) => p); } class C { void map(int Function({required int p})) {} } -''', [ - lint(33, 3), - ]); +''', + [lint(33, 3)], + ); } test_closureIsArgument_parameterIsTyped_optionalNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.map(([int? p]) => p); } class C { void map(int? Function([int? p])) {} } -''', [ - lint(24, 4), - ]); +''', + [lint(24, 4)], + ); } test_closureIsArgument_parameterIsTyped_optionalWithDefault() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.map(([int p = 0]) => p); } class C { void map(int? Function([int p])) {} } -''', [ - lint(24, 3), - ]); +''', + [lint(24, 3)], + ); } test_parameterIsNotInClosure_inFunction() async { diff --git a/pkg/linter/test/rules/avoid_unnecessary_containers_test.dart b/pkg/linter/test/rules/avoid_unnecessary_containers_test.dart index 9bc3e3a5ab17..a50b37777915 100644 --- a/pkg/linter/test/rules/avoid_unnecessary_containers_test.dart +++ b/pkg/linter/test/rules/avoid_unnecessary_containers_test.dart @@ -21,14 +21,15 @@ class AvoidUnnecessaryContainersTest extends LintRuleTest { String get lintRule => LintNames.avoid_unnecessary_containers; test_childOnly() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { return Container(child: Row()); } -''', [ - lint(61, 9), - ]); +''', + [lint(61, 9)], + ); } test_noArguments() async { diff --git a/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart b/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart index 589371dcd7e8..438bc2d346cb 100644 --- a/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart @@ -24,15 +24,16 @@ part 'test.dart'; class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { A(int a); } -''', [ - lint(41, 5), - ]); +''', + [lint(41, 5)], + ); } test_augmentedConstructor() async { @@ -88,13 +89,14 @@ class C { } test_namedParameter_hasDefault() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({int c = 0}); } -''', [ - lint(15, 9), - ]); +''', + [lint(15, 9)], + ); } test_noParameters() async { @@ -106,14 +108,15 @@ class C { } test_redirectingConstructor1() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.named(int p); factory C(int p) = C.named; } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_redirectingConstructor2() async { @@ -140,23 +143,25 @@ class B extends A { } test_unused_optionalPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C([int p = 0]) {} } -''', [ - lint(15, 9), - ]); +''', + [lint(15, 9)], + ); } test_unused_requiredPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(int p); } -''', [ - lint(14, 5), - ]); +''', + [lint(14, 5)], + ); } test_usedInConstructorBody() async { diff --git a/pkg/linter/test/rules/avoid_void_async_test.dart b/pkg/linter/test/rules/avoid_void_async_test.dart index ec7b3fa59189..7562ee0feaf2 100644 --- a/pkg/linter/test/rules/avoid_void_async_test.dart +++ b/pkg/linter/test/rules/avoid_void_async_test.dart @@ -30,19 +30,21 @@ Future c() async {} } test_function_async_voidReturnType_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async => null; -''', [ - lint(5, 1), - ]); +''', + [lint(5, 1)], + ); } test_function_async_voidReturnType_block() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async {} -''', [ - lint(5, 1), - ]); +''', + [lint(5, 1)], + ); } test_function_asyncStar() async { @@ -102,41 +104,43 @@ void f() { } test_functionLocal_async_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void g() async => null; } -''', [ - error(WarningCode.UNUSED_ELEMENT, 18, 1), - lint(18, 1), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 18, 1), lint(18, 1)], + ); } test_functionLocal_main_async_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void main() async => null; } -''', [ - error(WarningCode.UNUSED_ELEMENT, 18, 4), - lint(18, 4), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 18, 4), lint(18, 4)], + ); } test_getter_async() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void get l async => null; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_getter_async_voidReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void get f async => null; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_getter_notAsync() async { @@ -146,14 +150,14 @@ void get f => null; } test_localFunction_async() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { void g() async {} } -''', [ - error(WarningCode.UNUSED_ELEMENT, 32, 1), - lint(32, 1), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 32, 1), lint(32, 1)], + ); } test_main_async() async { @@ -166,23 +170,25 @@ void main() async { } test_method_async_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo { void d() async => null; } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_method_async_block() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo { void f() async {} } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_method_async_futureVoidReturnType_arrow() async { @@ -210,13 +216,14 @@ class Foo { } test_method_main_async_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo { void main() async => null; } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_method_notAsync_arrow() async { @@ -244,13 +251,14 @@ class Foo { } test_operator_async() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo { void operator |(_) async => null; } -''', [ - lint(28, 1), - ]); +''', + [lint(28, 1)], + ); } test_operator_notAsync() async { diff --git a/pkg/linter/test/rules/avoid_web_libraries_in_flutter_test.dart b/pkg/linter/test/rules/avoid_web_libraries_in_flutter_test.dart index 5e23294f4613..63d023da9399 100644 --- a/pkg/linter/test/rules/avoid_web_libraries_in_flutter_test.dart +++ b/pkg/linter/test/rules/avoid_web_libraries_in_flutter_test.dart @@ -67,9 +67,7 @@ flutter: // ignore: unused_import import 'dart:html'; '''); - await assertDiagnosticsInFile(mainFile.path, [ - lint(25, 19), - ]); + await assertDiagnosticsInFile(mainFile.path, [lint(25, 19)]); } test_noPubspec() async { diff --git a/pkg/linter/test/rules/await_only_futures_test.dart b/pkg/linter/test/rules/await_only_futures_test.dart index 67d3b50b5f8a..886723d92338 100644 --- a/pkg/linter/test/rules/await_only_futures_test.dart +++ b/pkg/linter/test/rules/await_only_futures_test.dart @@ -38,16 +38,19 @@ void f() async { } test_extensionType_notImplementingFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int c) { } void f() async { await E(1); } -''', [ - // No lint. - error(CompileTimeErrorCode.AWAIT_OF_INCOMPATIBLE_TYPE, 48, 5), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.AWAIT_OF_INCOMPATIBLE_TYPE, 48, 5), + ], + ); } test_future() async { @@ -77,13 +80,14 @@ abstract class MyFuture implements Future {} } test_int() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async { await 23; } -''', [ - lint(19, 5), - ]); +''', + [lint(19, 5)], + ); } test_null() async { @@ -95,11 +99,14 @@ void f() async { } test_undefinedClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Undefined f() async => await f(); -''', [ - // No lint. - error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 9), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 9), + ], + ); } } diff --git a/pkg/linter/test/rules/camel_case_extensions_test.dart b/pkg/linter/test/rules/camel_case_extensions_test.dart index e1b526633b1f..9ca7e89fab59 100644 --- a/pkg/linter/test/rules/camel_case_extensions_test.dart +++ b/pkg/linter/test/rules/camel_case_extensions_test.dart @@ -32,19 +32,21 @@ augment extension e { } } test_lowerCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension fooBar on Object {} -''', [ - lint(10, 6), - ]); +''', + [lint(10, 6)], + ); } test_underscore() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension Foo_Bar on Object { } -''', [ - lint(10, 7), - ]); +''', + [lint(10, 7)], + ); } test_unnamed() async { diff --git a/pkg/linter/test/rules/camel_case_types_test.dart b/pkg/linter/test/rules/camel_case_types_test.dart index c6b54c044b24..9cf056fbb70a 100644 --- a/pkg/linter/test/rules/camel_case_types_test.dart +++ b/pkg/linter/test/rules/camel_case_types_test.dart @@ -85,11 +85,12 @@ class $FooBar } test_class_lowerCamel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class fooBar {} -''', [ - lint(6, 6), - ]); +''', + [lint(6, 6)], + ); } test_class_upperCamel() async { @@ -123,19 +124,21 @@ class AA {} } test_class_upperSnake() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo_Bar {} -''', [ - lint(6, 7), - ]); +''', + [lint(6, 7)], + ); } test_enum_lowerCamel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum foooBar { a } -''', [ - lint(5, 7), - ]); +''', + [lint(5, 7)], + ); } test_enum_upperCamel() async { @@ -147,11 +150,12 @@ enum FoooBar { a } test_extensionType_lowerCase() async { // No need to test all the variations. Name checking is shared with other // declaration types. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type fooBar(int i) {} -''', [ - lint(15, 6), - ]); +''', + [lint(15, 6)], + ); } test_extensionType_wellFormed() async { @@ -161,45 +165,50 @@ extension type FooBar(int i) {} } test_macroClass_lowerCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' macro class a {} -''', [ - lint(12, 1), - ]); +''', + [lint(12, 1)], + ); } test_mixin_lowerCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin m {} -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_mixinApplication_lower() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M {} class c = Object with M; -''', [ - lint(17, 1), - ]); +''', + [lint(17, 1)], + ); } test_typedef_newFormat_lower() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef f = void Function(); -''', [ - lint(8, 1), - ]); +''', + [lint(8, 1)], + ); } test_typedef_newFormat_lowerCamel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Foo {} typedef foo = Foo; -''', [ - lint(21, 3), - ]); +''', + [lint(21, 3)], + ); } test_typedef_newFormat_upperCamel() async { @@ -210,11 +219,12 @@ typedef F = Foo; } test_typedef_oldFormat_lowerCamel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef bool predicate(); -''', [ - lint(13, 9), - ]); +''', + [lint(13, 9)], + ); } test_typedef_oldFormat_upperCamel() async { diff --git a/pkg/linter/test/rules/cancel_subscriptions_test.dart b/pkg/linter/test/rules/cancel_subscriptions_test.dart index 031fc4e7a27e..4116ade4ca60 100644 --- a/pkg/linter/test/rules/cancel_subscriptions_test.dart +++ b/pkg/linter/test/rules/cancel_subscriptions_test.dart @@ -43,14 +43,15 @@ void f(Stream stream) { } test_localVariable_notCanceled() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(Stream stream) { StreamSubscription s = stream.listen((_) {}); } -''', [ - lint(66, 25), - ]); +''', + [lint(66, 25)], + ); } test_privateField_canceled() async { @@ -84,14 +85,15 @@ class A { } @FailingTest( - reason: - 'It seems this is not implemented. In the previous incarnation of ' - 'this test, at `test_data/integration/cancel_subscriptions.dart`, an ' - 'end-of-line comment (`// OK`) indicated that the subscription ' - 'should be counted as canceled. However, that is not how an ' - 'expectation is set in an integration test, and a Lint is indeed ' - 'reported for this case. We have the test written here with what was ' - 'presumably the intention of the previous test.') + reason: + 'It seems this is not implemented. In the previous incarnation of ' + 'this test, at `test_data/integration/cancel_subscriptions.dart`, an ' + 'end-of-line comment (`// OK`) indicated that the subscription ' + 'should be counted as canceled. However, that is not how an ' + 'expectation is set in an integration test, and a Lint is indeed ' + 'reported for this case. We have the test written here with what was ' + 'presumably the intention of the previous test.', + ) test_privateField_canceled_outsideTheClass() async { await assertNoDiagnostics(r''' import 'dart:async'; @@ -111,7 +113,8 @@ class B { } test_privateField_notCanceled() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; class A { late StreamSubscription _subscription; @@ -119,9 +122,8 @@ class A { _subscription = stream.listen((_) {}); } } -''', [ - error(WarningCode.UNUSED_FIELD, 57, 13), - lint(57, 13), - ]); +''', + [error(WarningCode.UNUSED_FIELD, 57, 13), lint(57, 13)], + ); } } diff --git a/pkg/linter/test/rules/cascade_invocations_test.dart b/pkg/linter/test/rules/cascade_invocations_test.dart index 3415ee0356cd..43014c2b364c 100644 --- a/pkg/linter/test/rules/cascade_invocations_test.dart +++ b/pkg/linter/test/rules/cascade_invocations_test.dart @@ -33,18 +33,20 @@ void f(C c) { } test_assignmentThenMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list = []; list.clear(); } -''', [ - lint(40, 13), - ]); +''', + [lint(40, 13)], + ); } test_consecutiveMethodCalls_thenDifferentTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { late C parent; late C c; @@ -55,9 +57,9 @@ class C { parent.c.bar(); } } -''', [ - lint(72, 8), - ]); +''', + [lint(72, 8)], + ); } test_methodCallDependsOnTarget() async { @@ -88,27 +90,28 @@ class C { } test_multipleConsecutiveMethodCalls() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.clear(); list.clear(); } -''', [ - lint(43, 13), - ]); +''', + [lint(43, 13)], + ); } test_multipleConsecutiveMethodCalls_cascaded() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.clear(); list.clear(); list..clear(); } -''', [ - lint(43, 13), - lint(59, 14), - ]); +''', + [lint(43, 13), lint(59, 14)], + ); } test_nonConsecutiveReferences() async { @@ -127,7 +130,8 @@ class Foo { } test_nullAwareAccessThenConsecutiveAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c?.m(); // ignore: invalid_null_aware_operator c.m(); @@ -136,9 +140,9 @@ void f(C c) { class C { void m() {} } -''', [ - lint(74, 6), - ]); +''', + [lint(74, 6)], + ); } test_nullAwareAccessThenMethodCall() async { @@ -154,7 +158,8 @@ class C { } test_nullAwareAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C? c) { c ??= C(); c.foo = 1; @@ -164,9 +169,9 @@ class C { int foo = 0; int bar = 0; } -''', [ - lint(43, 10), - ]); +''', + [lint(43, 10)], + ); } test_oneCallIsAwaited() async { @@ -237,13 +242,14 @@ class C { } test_twoConsecutiveMethodCalls() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.clear(); list.clear(); } -''', [ - lint(43, 13), - ]); +''', + [lint(43, 13)], + ); } } diff --git a/pkg/linter/test/rules/cast_nullable_to_non_nullable_test.dart b/pkg/linter/test/rules/cast_nullable_to_non_nullable_test.dart index 614e4f0405ee..b2d698cb2df4 100644 --- a/pkg/linter/test/rules/cast_nullable_to_non_nullable_test.dart +++ b/pkg/linter/test/rules/cast_nullable_to_non_nullable_test.dart @@ -34,12 +34,13 @@ void f(dynamic a) { } test_castNullable_toNonNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String? s; var a = s as String; -''', [ - lint(19, 11), - ]); +''', + [lint(19, 11)], + ); } test_castNullable_toNullable() async { @@ -54,12 +55,15 @@ void f(A? a) { } test_castNullable_unresolvedType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Undefined? s; var a = s! as String; -''', [ - // No lint. - error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 9), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 9), + ], + ); } } diff --git a/pkg/linter/test/rules/close_sinks_test.dart b/pkg/linter/test/rules/close_sinks_test.dart index a72619f20dbb..54d3ef7e367c 100644 --- a/pkg/linter/test/rules/close_sinks_test.dart +++ b/pkg/linter/test/rules/close_sinks_test.dart @@ -110,7 +110,8 @@ class C { } test_field_initializedInMethod_notClosed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; class C { // ignore: unused_field @@ -119,9 +120,9 @@ class C { _sink = File('').openWrite(); } } -''', [ - lint(68, 5), - ]); +''', + [lint(68, 5)], + ); } test_localVariable_closed() async { @@ -135,14 +136,15 @@ void f() { } test_localVariable_inFunction_notInitialized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:io'; void someFunction() { IOSink sink; } -''', [ - lint(49, 4), - ]); +''', + [lint(49, 4)], + ); } test_localVariable_inMethod_returned_notClosed() async { diff --git a/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart b/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart index daaea53adbf8..fec6ebe09b0a 100644 --- a/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart +++ b/pkg/linter/test/rules/collection_methods_unrelated_type_test.dart @@ -106,13 +106,16 @@ abstract class C implements List { } test_contains_unrelated_implicitTarget() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' abstract class C implements List { void f() { contains('1'); } } -''', [lint(66, 3)]); +''', + [lint(66, 3)], + ); } test_contains_unrelated_recordAndNonRecord() async { @@ -128,22 +131,28 @@ abstract class C implements List { } test_contains_unrelated_subclassOfList() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' abstract class C implements List {} void f(C c) { c.contains('1'); } -''', [lint(68, 3)]); +''', + [lint(68, 3)], + ); } test_contains_unrelated_thisTarget() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' abstract class C implements List { void f() { this.contains('1'); } } -''', [lint(71, 3)]); +''', + [lint(71, 3)], + ); } } @@ -157,10 +166,7 @@ class CollectionMethodsUnrelatedTypeListTest extends LintRuleTest { } test_remove_unrelated() async { - await assertDiagnostics( - '''var x = [].remove('1');''', - [lint(23, 3)], - ); + await assertDiagnostics('''var x = [].remove('1');''', [lint(23, 3)]); } } @@ -196,10 +202,7 @@ class CollectionMethodsUnrelatedTypeMapTest extends LintRuleTest { } test_index_unrelated() async { - await assertDiagnostics( - '''var x = {}['1'];''', - [lint(24, 3)], - ); + await assertDiagnostics('''var x = {}['1'];''', [lint(24, 3)]); } test_remove_related_subtype() async { @@ -229,12 +232,15 @@ void f(Queue queue) { } test_remove_unrelated() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'dart:collection'; void f(Queue queue) { queue.remove('1'); } -''', [lint(68, 3)]); +''', + [lint(68, 3)], + ); } } @@ -248,10 +254,7 @@ class CollectionMethodsUnrelatedTypeSetTest extends LintRuleTest { } test_lookup_unrelated() async { - await assertDiagnostics( - '''var x = {}.lookup('1');''', - [lint(23, 3)], - ); + await assertDiagnostics('''var x = {}.lookup('1');''', [lint(23, 3)]); } test_remove_related_subtype() async { @@ -259,9 +262,6 @@ class CollectionMethodsUnrelatedTypeSetTest extends LintRuleTest { } test_remove_unrelated() async { - await assertDiagnostics( - '''var x = {}.remove('1');''', - [lint(23, 3)], - ); + await assertDiagnostics('''var x = {}.remove('1');''', [lint(23, 3)]); } } diff --git a/pkg/linter/test/rules/combinators_ordering_test.dart b/pkg/linter/test/rules/combinators_ordering_test.dart index d66224f7f33a..ec09abd35d83 100644 --- a/pkg/linter/test/rules/combinators_ordering_test.dart +++ b/pkg/linter/test/rules/combinators_ordering_test.dart @@ -28,11 +28,12 @@ import 'dart:math' hide max, min; } test_hideCombinator_import_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math' hide min, max; -''', [ - lint(19, 13), - ]); +''', + [lint(19, 13)], + ); } test_showCombinator_export_sorted() async { @@ -42,11 +43,12 @@ export 'dart:math' show max, min; } test_showCombinator_export_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'dart:math' show min, max; -''', [ - lint(19, 13), - ]); +''', + [lint(19, 13)], + ); } test_showCombinator_import_sorted() async { @@ -56,10 +58,11 @@ import 'dart:math' show max, min; } test_showCombinator_import_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math' show min, max; -''', [ - lint(19, 13), - ]); +''', + [lint(19, 13)], + ); } } diff --git a/pkg/linter/test/rules/comment_references_test.dart b/pkg/linter/test/rules/comment_references_test.dart index c83751eb7217..3c7675f652ea 100644 --- a/pkg/linter/test/rules/comment_references_test.dart +++ b/pkg/linter/test/rules/comment_references_test.dart @@ -25,12 +25,13 @@ class C {} } test_false() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// [false] class C {} -''', [ - lint(5, 5), - ]); +''', + [lint(5, 5)], + ); } test_field() async { @@ -141,12 +142,13 @@ class C {} } test_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// [null] class C {} -''', [ - lint(5, 4), - ]); +''', + [lint(5, 4)], + ); } test_parameter() async { @@ -213,21 +215,23 @@ class C {} } test_this() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// [this] class C {} -''', [ - lint(5, 4), - ]); +''', + [lint(5, 4)], + ); } test_true() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// [true] class C {} -''', [ - lint(5, 4), - ]); +''', + [lint(5, 4)], + ); } test_typeName() async { @@ -246,38 +250,42 @@ class C {} } test_unknownElement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text [y]. class C {} -''', [ - lint(10, 1), - ]); +''', + [lint(10, 1)], + ); } test_unknownElement_dottedName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Parameter [y.z]. class C {} -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_unknownElement_followedByColon() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Parameter [y]: z. void f(int x) {} -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_unknownElement_twiceDottedName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Parameter [x.y.z]. class C {} -''', [ - lint(15, 5), - ]); +''', + [lint(15, 5)], + ); } } diff --git a/pkg/linter/test/rules/conditional_uri_does_not_exist_test.dart b/pkg/linter/test/rules/conditional_uri_does_not_exist_test.dart index 973034f6e289..65f8118db35d 100644 --- a/pkg/linter/test/rules/conditional_uri_does_not_exist_test.dart +++ b/pkg/linter/test/rules/conditional_uri_does_not_exist_test.dart @@ -25,20 +25,23 @@ class ConditionalUriDoesNotExistTest extends LintRuleTest { part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; import '' if (dart.library.io) 'dart:missing_1' if (dart.library.html) 'dart:async' if (dart.library.async) 'dart:missing_2'; -''', [ - // The imported library '' can't have a part-of directive, - // but that's OK for the purposes of verifying the lint. - error(CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, 26, 2), - lint(54, 16), - lint(139, 16), - ]); +''', + [ + // The imported library '' can't have a part-of directive, + // but that's OK for the purposes of verifying the lint. + error(CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY, 26, 2), + lint(54, 16), + lint(139, 16), + ], + ); } test_missingDartLibraries() async { @@ -96,17 +99,16 @@ import '' part of 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import '' if (dart.library.io) 'dart:missing_1' if (dart.library.html) 'dart:async' if (dart.library.async) 'dart:missing_2'; part 'a.dart'; -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 2), - lint(35, 16), - lint(120, 16), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 2), lint(35, 16), lint(120, 16)], + ); } } diff --git a/pkg/linter/test/rules/constant_identifier_names_test.dart b/pkg/linter/test/rules/constant_identifier_names_test.dart index e4ac3da2a559..ceb520fb7887 100644 --- a/pkg/linter/test/rules/constant_identifier_names_test.dart +++ b/pkg/linter/test/rules/constant_identifier_names_test.dart @@ -26,15 +26,16 @@ enum E { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment enum E { Xy; } -''', [ - lint(38, 2), - ]); +''', + [lint(38, 2)], + ); } test_augmentationTopLevelVariable() async { @@ -42,13 +43,14 @@ augment enum E { part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; const PI = 3.14; -''', [ - lint(25, 2), - ]); +''', + [lint(25, 2)], + ); } test_augmentedEnumValue() async { @@ -84,35 +86,39 @@ augment const PI = 3.1415; } test_destructuredConstField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static const AA = (1, ); } -''', [ - lint(25, 2), - ]); +''', + [lint(25, 2)], + ); } test_destructuredConstVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const AA = (1, ); -''', [ - lint(6, 2), - ]); +''', + [lint(6, 2)], + ); } test_destructuredFinalVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final (AA, ) = (1, ); } -''', [ - lint(20, 2), - ]); +''', + [lint(20, 2)], + ); } test_destructuredObjectField_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var a; } @@ -126,11 +132,9 @@ f(A a) { case A(a: int a_b!): } } -''', [ - lint(64, 3), - lint(107, 3), - lint(132, 3), - ]); +''', + [lint(64, 3), lint(107, 3), lint(132, 3)], + ); } test_destructuredObjectField_switch_ok() async { @@ -152,24 +156,26 @@ f(A a) { } test_enumValue_upperFirstLetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum Foo { bar, Baz, } -''', [ - lint(20, 3), - ]); +''', + [lint(20, 3)], + ); } test_recordFieldDestructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (x: int x_x, z: int z)) { } } -''', [ - lint(35, 3), - ]); +''', + [lint(35, 3)], + ); } test_recordFieldDestructured_ok() async { @@ -181,11 +187,12 @@ f(Object o) { } test_recordTypeDeclarations() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const RR = (x: 1); -''', [ - lint(6, 2), - ]); +''', + [lint(6, 2)], + ); } test_recordTypeDeclarations_ok() async { @@ -195,28 +202,31 @@ const r = (x: 1); } test_staticField_allCaps() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static const DEBUG = false; } -''', [ - lint(25, 5), - ]); +''', + [lint(25, 5)], + ); } test_topLevel_allCaps() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const PI = 3.14; -''', [ - lint(6, 2), - ]); +''', + [lint(6, 2)], + ); } test_topLevel_screamingSnake() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const CCC_CCC = 1000; -''', [ - lint(6, 7), - ]); +''', + [lint(6, 7)], + ); } } diff --git a/pkg/linter/test/rules/control_flow_in_finally_test.dart b/pkg/linter/test/rules/control_flow_in_finally_test.dart index 30357711327b..683e185895c7 100644 --- a/pkg/linter/test/rules/control_flow_in_finally_test.dart +++ b/pkg/linter/test/rules/control_flow_in_finally_test.dart @@ -19,7 +19,8 @@ class ControlFlowInFinallyTest extends LintRuleTest { String get lintRule => LintNames.control_flow_in_finally; test_break() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var o in [1, 2]) { try { @@ -31,9 +32,9 @@ void f() { } } } -''', [ - lint(108, 6), - ]); +''', + [lint(108, 6)], + ); } test_break_loopDeclaredWithinFinally() async { @@ -53,7 +54,8 @@ void f() { } test_continue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var o in [1, 2]) { try { @@ -63,9 +65,9 @@ void f() { } } } -''', [ - lint(87, 9), - ]); +''', + [lint(87, 9)], + ); } test_continue_deep() async { @@ -97,7 +99,8 @@ void f(int i) { } test_return() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try { } catch (e) { @@ -105,9 +108,9 @@ void f() { return; } } -''', [ - lint(53, 7), - ]); +''', + [lint(53, 7)], + ); } test_returnInClosure() async { diff --git a/pkg/linter/test/rules/curly_braces_in_flow_control_structures_test.dart b/pkg/linter/test/rules/curly_braces_in_flow_control_structures_test.dart index 43882d60fc19..1c1fdb739991 100644 --- a/pkg/linter/test/rules/curly_braces_in_flow_control_structures_test.dart +++ b/pkg/linter/test/rules/curly_braces_in_flow_control_structures_test.dart @@ -27,36 +27,39 @@ void f() { } test_doWhile_singeStatement_sameLineAsDo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do print(''); while (true); } -''', [ - lint(16, 10), - ]); +''', + [lint(16, 10)], + ); } test_doWhile_singleStatement_lineAfterDo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do print(''); while (true); } -''', [ - lint(20, 10), - ]); +''', + [lint(20, 10)], + ); } test_doWhile_singleStatement_sameLineAsDoAndWhile() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do print(''); while (true); } -''', [ - lint(16, 10), - ]); +''', + [lint(16, 10)], + ); } test_forEachLoop_block_sameLine() async { @@ -68,24 +71,26 @@ void f(List l) { } test_forEachLoop_singleStatement_lineAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List l) { for (var i in l) return; } -''', [ - lint(45, 7), - ]); +''', + [lint(45, 7)], + ); } test_forEachLoop_singleStatement_sameLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List l) { for (var i in l) return; } -''', [ - lint(41, 7), - ]); +''', + [lint(41, 7)], + ); } test_forLoop_emptyBlock_sameLine() async { @@ -97,24 +102,26 @@ void f() { } test_forLoop_singleStatement_lineAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (;;) return; } -''', [ - lint(26, 7), - ]); +''', + [lint(26, 7)], + ); } test_forLoop_singleStatement_sameLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (;;) return; } -''', [ - lint(22, 7), - ]); +''', + [lint(22, 7)], + ); } test_ifStatement_block_sameLine() async { @@ -135,26 +142,28 @@ void f() { } test_ifStatement_singleStatement_lineAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) return; } -''', [ - lint(29, 7), - ]); +''', + [lint(29, 7)], + ); } test_ifStatement_singleStatement_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) print( 'First argument' 'Second argument'); } -''', [ - lint(25, 51), - ]); +''', + [lint(25, 51)], + ); } test_ifStatement_singleStatement_sameLine() async { @@ -166,14 +175,15 @@ void f() { } test_ifStatement_singleStatement_sameLine_multiLineCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) return; } -''', [ - lint(31, 7), - ]); +''', + [lint(31, 7)], + ); } test_ifStatementElse_block_sameLine() async { @@ -186,26 +196,28 @@ void f() { } test_ifStatementElse_singleStatement_lineAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) {} else return; } -''', [ - lint(39, 7), - ]); +''', + [lint(39, 7)], + ); } test_ifStatementElse_singleStatement_sameLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) {} else return; } -''', [ - lint(35, 7), - ]); +''', + [lint(35, 7)], + ); } test_ifStatementElseIf_block_sameLine_multiLine() async { @@ -218,26 +230,28 @@ void f() { } test_ifStatementElseIf_singleStatement_lineAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) {} else if (1 == 2) return; } -''', [ - lint(51, 7), - ]); +''', + [lint(51, 7)], + ); } test_ifStatementElseIf_singleStatement_sameLine_lineAfterIfCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) { } else if (1 == 3) return; } -''', [ - lint(48, 7), - ]); +''', + [lint(48, 7)], + ); } test_whileLoop_block_sameLine() async { @@ -249,23 +263,25 @@ void f() { } test_whileLoop_singleStatement_nextLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { while (true) return; } -''', [ - lint(30, 7), - ]); +''', + [lint(30, 7)], + ); } test_whileLoop_singleStatement_sameLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { while (true) return; } -''', [ - lint(26, 7), - ]); +''', + [lint(26, 7)], + ); } } diff --git a/pkg/linter/test/rules/depend_on_referenced_packages_test.dart b/pkg/linter/test/rules/depend_on_referenced_packages_test.dart index 6478d492d11d..6a09441926e9 100644 --- a/pkg/linter/test/rules/depend_on_referenced_packages_test.dart +++ b/pkg/linter/test/rules/depend_on_referenced_packages_test.dart @@ -35,11 +35,11 @@ version: 1.1.1 dev_dependencies: meta: any '''); - var binFile = - newFile('$testPackageRootPath/bin/bin.dart', sourceReferencingMeta); - await assertDiagnosticsInFile(binFile.path, [ - lint(7, 24), - ]); + var binFile = newFile( + '$testPackageRootPath/bin/bin.dart', + sourceReferencingMeta, + ); + await assertDiagnosticsInFile(binFile.path, [lint(7, 24)]); } void test_referencedInBuildHook_listedInDeps() async { @@ -50,8 +50,10 @@ version: 1.1.1 dependencies: meta: any '''); - var hookFile = - newFile('$testPackageRootPath/hook/build.dart', sourceReferencingMeta); + var hookFile = newFile( + '$testPackageRootPath/hook/build.dart', + sourceReferencingMeta, + ); await assertNoDiagnosticsInFile(hookFile.path); } @@ -63,11 +65,11 @@ version: 1.1.1 dev_dependencies: meta: any '''); - var hookFile = - newFile('$testPackageRootPath/hook/build.dart', sourceReferencingMeta); - await assertDiagnosticsInFile(hookFile.path, [ - lint(7, 24), - ]); + var hookFile = newFile( + '$testPackageRootPath/hook/build.dart', + sourceReferencingMeta, + ); + await assertDiagnosticsInFile(hookFile.path, [lint(7, 24)]); } void test_referencedInBuildHook_missingFromPubspec() async { @@ -75,11 +77,11 @@ dev_dependencies: name: fancy version: 1.1.1 '''); - var hookFile = - newFile('$testPackageRootPath/hook/build.dart', sourceReferencingMeta); - await assertDiagnosticsInFile(hookFile.path, [ - lint(7, 24), - ]); + var hookFile = newFile( + '$testPackageRootPath/hook/build.dart', + sourceReferencingMeta, + ); + await assertDiagnosticsInFile(hookFile.path, [lint(7, 24)]); } test_referencedInLib_flutterGen() async { @@ -120,9 +122,7 @@ version: 1.1.1 dev_dependencies: meta: any '''); - await assertDiagnostics(sourceReferencingMeta, [ - lint(7, 24), - ]); + await assertDiagnostics(sourceReferencingMeta, [lint(7, 24)]); } test_referencedInLib_missingFromPubspec() async { @@ -130,9 +130,7 @@ dev_dependencies: name: fancy version: 1.1.1 '''); - await assertDiagnostics(sourceReferencingMeta, [ - lint(7, 24), - ]); + await assertDiagnostics(sourceReferencingMeta, [lint(7, 24)]); } test_referencedInLib_selfPackage() async { @@ -156,11 +154,11 @@ version: 1.1.1 dev_dependencies: meta: any '''); - var hookFile = - newFile('$testPackageRootPath/hook/link.dart', sourceReferencingMeta); - await assertDiagnosticsInFile(hookFile.path, [ - lint(7, 24), - ]); + var hookFile = newFile( + '$testPackageRootPath/hook/link.dart', + sourceReferencingMeta, + ); + await assertDiagnosticsInFile(hookFile.path, [lint(7, 24)]); } test_referencedInTest_listedInDevDeps() async { @@ -171,8 +169,10 @@ version: 1.1.1 dev_dependencies: meta: any '''); - var testFile = - newFile('$testPackageRootPath/test/test.dart', sourceReferencingMeta); + var testFile = newFile( + '$testPackageRootPath/test/test.dart', + sourceReferencingMeta, + ); await assertNoDiagnosticsInFile(testFile.path); } } diff --git a/pkg/linter/test/rules/deprecated_consistency_test.dart b/pkg/linter/test/rules/deprecated_consistency_test.dart index 4ccbd4ace5a0..d471b2f94fb0 100644 --- a/pkg/linter/test/rules/deprecated_consistency_test.dart +++ b/pkg/linter/test/rules/deprecated_consistency_test.dart @@ -18,7 +18,8 @@ class DeprecatedConsistencyTest extends LintRuleTest { String get lintRule => LintNames.deprecated_consistency; test_classDeprecated_factoryConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class A { @deprecated @@ -26,9 +27,9 @@ class A { factory A() => A._(); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_classDeprecated_factoryConstructor_deprecated() async { @@ -45,14 +46,15 @@ class A { } test_classDeprecated_generativeConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class A { A(); } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_classDeprecated_generativeConstructor_deprecated() async { @@ -66,14 +68,15 @@ class A { } test_constructorFieldFormalDeprecated_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; A({@deprecated this.a}); } -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_constructorFieldFormalDeprecated_fieldDeprecated() async { @@ -100,15 +103,16 @@ class B extends A { } test_fieldDeprecated_fieldFormalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated String? a; A({this.a}); } -''', [ - lint(42, 6), - ]); +''', + [lint(42, 6)], + ); } test_fieldDeprecated_fieldFormalParameter_deprecated() async { diff --git a/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart b/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart index 43897cc3ee14..9e78686f995f 100644 --- a/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart +++ b/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart @@ -17,47 +17,50 @@ main() { class DeprecatedMemberUseFromSamePackageTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE, - HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE, + HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE_WITH_MESSAGE, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.deprecated_member_use_from_same_package; test_deprecatedCallMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated void call() {} } void f(C c) => c(); -''', [ - lint(59, 3), - ]); +''', + [lint(59, 3)], + ); } test_deprecatedClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} void f(C c) {} -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_deprecatedClass_usedInClassTypeAlias() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated mixin class C {} class D = Object with C; -''', [ - lint(52, 1), - ]); +''', + [lint(52, 1)], + ); } test_deprecatedClass_usedInDeprecatedClassTypeAlias() async { @@ -212,18 +215,20 @@ C? x; } test_deprecatedClass_usedInExtensionTypeRepresentation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} extension type E(C c) { } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_deprecatedClass_usedInFieldFormalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} @@ -231,31 +236,33 @@ class D { Object c; D({required C this.c}); } -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_deprecatedClass_usedInFunctionTypeAlias() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} typedef void Callback(C c); -''', [ - lint(46, 1), - ]); +''', + [lint(46, 1)], + ); } test_deprecatedClass_usedInFunctionTypedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} void f({void p(C c)?}) {} -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_deprecatedClass_usedInGenericFunctionTypeAlias() async { @@ -269,14 +276,15 @@ typedef Callback = void Function(C); } test_deprecatedClass_usedInGenericTypeAlias() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} typedef Callback = void Function(C); -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_deprecatedClass_usedInHideCombinator() async { @@ -284,12 +292,15 @@ typedef Callback = void Function(C); @deprecated class C {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'lib.dart' hide C; -''', [ - // No lint. - error(WarningCode.UNUSED_IMPORT, 7, 10), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_IMPORT, 7, 10), + ], + ); } test_deprecatedClass_usedInShowCombinator() async { @@ -297,16 +308,17 @@ import 'lib.dart' hide C; @deprecated class C {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'lib.dart' show C; -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 10), - lint(23, 1), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 10), lint(23, 1)], + ); } test_deprecatedConstructor_usedInSuperConstructorCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated A(); @@ -314,118 +326,128 @@ class A { class B extends A { B() : super(); } -''', [ - lint(61, 7), - ]); +''', + [lint(61, 7)], + ); } test_deprecatedDefaultParameterOfFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({@deprecated int p = 1}) {} void g() => f(p: 1); -''', [ - lint(50, 1), - ]); +''', + [lint(50, 1)], + ); } test_deprecatedEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated enum E { one, two; } late E e; -''', [ - lint(40, 1), - ]); +''', + [lint(40, 1)], + ); } test_deprecatedEnumValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { one, @deprecated two; } late E e = E.two; -''', [ - lint(48, 3), - ]); +''', + [lint(48, 3)], + ); } test_deprecatedExtension_usedInExtensionOverride_getter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension E on int { int get foo => 1; } var x = E(0).foo; -''', [ - lint(64, 1), - ]); +''', + [lint(64, 1)], + ); } test_deprecatedExtension_usedInExtensionOverride_methodInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension E on int { void f() {} } var x = E(0).f(); -''', [ - lint(58, 1), - ]); +''', + [lint(58, 1)], + ); } test_deprecatedExtensionType_usedInExtensionTypeImplements() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension type E(int i) { } extension type F(int i) implements E { } -''', [ - lint(76, 1), - ]); +''', + [lint(76, 1)], + ); } test_deprecatedExtensionType_usedInExtensionTypeRepresentation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension type E(int i) { } extension type F(E c) { } -''', [ - lint(58, 1), - ]); +''', + [lint(58, 1)], + ); } test_deprecatedExtensionType_usedInField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension type E(int i) { } class C { E? e; } -''', [ - lint(53, 1), - ]); +''', + [lint(53, 1)], + ); } test_deprecatedExtensionType_usedInFunctionParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated extension type E(int i) { } void f(E e) { } -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_deprecatedField_usedAsGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated int f = 0; @@ -434,13 +456,14 @@ class A { void f(A a) { a.f; } -''', [ - lint(58, 1), - ]); +''', + [lint(58, 1)], + ); } test_deprecatedField_usedAsSetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated int f = 0; @@ -449,9 +472,9 @@ class A { void f(A a) { a.f = 1; } -''', [ - lint(58, 1), - ]); +''', + [lint(58, 1)], + ); } test_deprecatedField_usedInDeprecatedClass() async { @@ -487,7 +510,8 @@ void f(A a) { } test_deprecatedField_usedInPostfix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated int f = 0; @@ -496,13 +520,14 @@ class A { void f(A a) { a.f++; } -''', [ - lint(56, 3), - ]); +''', + [lint(56, 3)], + ); } test_deprecatedField_usedInPrefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated int f = 0; @@ -511,13 +536,14 @@ class A { void f(A a) { ++a.f; } -''', [ - lint(58, 3), - ]); +''', + [lint(58, 3)], + ); } test_deprecatedField_usedInSuper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated int f = 0; @@ -526,9 +552,9 @@ class A { class B extends A { int get g => super.f; } -''', [ - lint(81, 1), - ]); +''', + [lint(81, 1)], + ); } test_deprecatedGetter_usedInAssignment() async { @@ -545,7 +571,8 @@ void f() { } test_deprecatedGetter_usedInCompoundAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated int get x => 1; @@ -554,13 +581,14 @@ set x(int value) {} void f() { x += 1; } -''', [ - lint(63, 1), - ]); +''', + [lint(63, 1)], + ); } test_deprecatedIndexOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated int operator[](int p) => 1; @@ -569,9 +597,9 @@ class C { void f(C c) { c[1]; } -''', [ - lint(73, 4), - ]); +''', + [lint(73, 4)], + ); } test_deprecatedLibrary_export() async { @@ -579,11 +607,12 @@ void f(C c) { @deprecated library a; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'lib.dart'; -''', [ - lint(0, 18), - ]); +''', + [lint(0, 18)], + ); } test_deprecatedLibrary_import() async { @@ -591,16 +620,17 @@ export 'lib.dart'; @deprecated library a; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'lib.dart'; -''', [ - lint(0, 18), - error(WarningCode.UNUSED_IMPORT, 7, 10), - ]); +''', + [lint(0, 18), error(WarningCode.UNUSED_IMPORT, 7, 10)], + ); } test_deprecatedMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated void m() {} @@ -609,9 +639,9 @@ class A { m(); } } -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_deprecatedMethod_usedInDeprecatedConstructor() async { @@ -644,7 +674,8 @@ class B extends A { } test_deprecatedMethod_withMessage() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @Deprecated('Message') void m() {} @@ -653,26 +684,28 @@ class A { m(); } } -''', [ - lint(68, 1), - ]); +''', + [lint(68, 1)], + ); } test_deprecatedNamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated C.named(); } var x = C.named(); -''', [ - lint(48, 7), - ]); +''', + [lint(48, 7)], + ); } test_deprecatedNamedConstructor_usedInSuperConstructorCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated A.named(); @@ -680,19 +713,20 @@ class A { class B extends A { B() : super.named(); } -''', [ - lint(67, 13), - ]); +''', + [lint(67, 13)], + ); } test_deprecatedNamedParameterOfFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({@deprecated int? p}) {} void g() => f(p: 1); -''', [ - lint(47, 1), - ]); +''', + [lint(47, 1)], + ); } test_deprecatedNamedParameterOfFunction_usedInDeclaringFunction() async { @@ -702,19 +736,21 @@ int? f({@deprecated int? p}) => p; } test_deprecatedNamedParameterOfMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f({@deprecated int? p}) {} void g() => f(p: 1); } -''', [ - lint(61, 1), - ]); +''', + [lint(61, 1)], + ); } test_deprecatedOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated C operator+(int other) => C(); @@ -722,13 +758,14 @@ class C { void f(C c) { c + 1; } -''', [ - lint(75, 5), - ]); +''', + [lint(75, 5)], + ); } test_deprecatedOperator_usedInCompoundAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated C operator+(int other) => C(); @@ -736,9 +773,9 @@ class C { void f(C c) { c += 1; } -''', [ - lint(75, 6), - ]); +''', + [lint(75, 6)], + ); } test_deprecatedParameterOfConstructor_usedInDeclaringConstructorBody() async { @@ -760,38 +797,42 @@ class C { } test_deprecatedParameterOfConstructor_usedInRedirectingConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({@deprecated int? p}); C.two() : this(p: 0); } -''', [ - lint(54, 1), - ]); +''', + [lint(54, 1)], + ); } test_deprecatedPositionalParameterOfFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([@deprecated int? p]) {} void g() => f(1); -''', [ - lint(47, 1), - ]); +''', + [lint(47, 1)], + ); } test_deprecatedSetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated set f(int value) {} void g() => f = 1; -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_deprecatedSetter_usedInCompoundAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int get x => 1; @deprecated @@ -800,47 +841,50 @@ set x(int value) {} void f() { x += 1; } -''', [ - lint(63, 1), - ]); +''', + [lint(63, 1)], + ); } test_deprecatedStaticField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { @deprecated static int f = 0; } var a = A.f; -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_deprecatedTopLevelVariable_usedInAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated int x = 1; void f() { x = 1; } -''', [ - lint(37, 1), - ]); +''', + [lint(37, 1)], + ); } test_deprecatedUnnamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @deprecated C(); } var x = C(); -''', [ - lint(42, 1), - ]); +''', + [lint(42, 1)], + ); } } diff --git a/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart b/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart index 8cbf0b197b65..7381cce59769 100644 --- a/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart +++ b/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart @@ -21,14 +21,15 @@ class DiagnosticDescribeAllPropertiesTest extends LintRuleTest { String get lintRule => LintNames.diagnostic_describe_all_properties; test_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/foundation.dart'; class MyWidget with Diagnosticable { bool p = false; } -''', [ - lint(86, 1), - ]); +''', + [lint(86, 1)], + ); } test_field_collectionOfWidgets() async { @@ -96,14 +97,15 @@ class MyWidget with Diagnosticable { } test_field_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/foundation.dart'; class MyWidget with Diagnosticable { String p = ''; } -''', [ - lint(88, 1), - ]); +''', + [lint(88, 1)], + ); } test_field_widget() async { @@ -117,14 +119,15 @@ class MyWidget with Diagnosticable { } test_getter_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/foundation.dart'; class MyWidget with Diagnosticable { String get p => ''; } -''', [ - lint(92, 1), - ]); +''', + [lint(92, 1)], + ); } test_getter_widget() async { diff --git a/pkg/linter/test/rules/directives_ordering_test.dart b/pkg/linter/test/rules/directives_ordering_test.dart index 8f3070905c49..0000c67a6af2 100644 --- a/pkg/linter/test/rules/directives_ordering_test.dart +++ b/pkg/linter/test/rules/directives_ordering_test.dart @@ -17,24 +17,30 @@ main() { void checkSection(List correctlyOrderedImports) { for (int i = 0; i < correctlyOrderedImports.length; i++) { var a = correctlyOrderedImports[i]; - expect(compareDirectives(a, a), 0, - reason: '"$a" sorts the same as itself'); + expect( + compareDirectives(a, a), + 0, + reason: '"$a" sorts the same as itself', + ); for (int j = i + 1; j < correctlyOrderedImports.length; j++) { var b = correctlyOrderedImports[j]; - expect(compareDirectives(a, b), lessThan(0), - reason: '"$a" sorts before "$b"'); - expect(compareDirectives(b, a), greaterThan(0), - reason: '"$b" sorts after "$a"'); + expect( + compareDirectives(a, b), + lessThan(0), + reason: '"$a" sorts before "$b"', + ); + expect( + compareDirectives(b, a), + greaterThan(0), + reason: '"$b" sorts after "$a"', + ); } } } test('dart: imports', () { - checkSection(const [ - 'dart:aaa', - 'dart:bbb', - ]); + checkSection(const ['dart:aaa', 'dart:bbb']); }); test('package: imports', () { @@ -78,51 +84,52 @@ class DirectivesOrderingTest extends LintRuleTest { test_dartDirectivesGoFirst_docImports() async { newFile('$testPackageLibPath/a.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// @docImport 'dart:math'; /// @docImport 'a.dart'; /// @docImport 'dart:html'; /// @docImport 'dart:isolate'; library; -''', [ - lint(61, 19), - lint(89, 22), - ]); +''', + [lint(61, 19), lint(89, 22)], + ); } test_dartDirectivesGoFirst_exports() async { newFile('$testPackageLibPath/a.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'dart:math'; export 'a.dart'; export 'dart:html'; export 'dart:isolate'; // ignore_for_file: unused_import -''', [ - lint(37, 19), - lint(57, 22), - ]); +''', + [lint(37, 19), lint(57, 22)], + ); } test_dartDirectivesGoFirst_imports() async { newFile('$testPackageLibPath/a.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math'; import 'a.dart'; import 'dart:html'; import 'dart:isolate'; // ignore_for_file: unused_import -''', [ - lint(37, 19), - lint(57, 22), - ]); +''', + [lint(37, 19), lint(57, 22)], + ); } test_importsGoBeforeExports() async { newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); newFile('$testPackageLibPath/c.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; export 'a.dart'; @@ -135,10 +142,9 @@ import 'c.dart'; export 'c.dart'; // ignore_for_file: unused_import -''', [ - lint(18, 16), - lint(54, 16), - ]); +''', + [lint(18, 16), lint(54, 16)], + ); } test_multipleSchemaImportsSortedByPath() async { @@ -184,47 +190,49 @@ main() {} test_packageDirectivesGoBeforeRelative_docImports() async { newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// @docImport 'dart:math'; /// @docImport 'package:js/js.dart'; /// @docImport 'a.dart'; /// @docImport 'package:meta/meta.dart'; /// @docImport 'b.dart'; library; -''', [ - lint(98, 32), - ]); +''', + [lint(98, 32)], + ); } test_packageDirectivesGoBeforeRelative_exports() async { newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'dart:math'; export 'a.dart'; export 'package:js/js.dart'; export 'package:meta/meta.dart'; export 'b.dart'; // ignore_for_file: unused_import -''', [ - lint(37, 28), - lint(66, 32), - ]); +''', + [lint(37, 28), lint(66, 32)], + ); } test_packageDirectivesGoBeforeRelative_imports() async { newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math'; import 'package:js/js.dart'; import 'a.dart'; import 'package:meta/meta.dart'; import 'b.dart'; // ignore_for_file: unused_import -''', [ - lint(66, 32), - ]); +''', + [lint(66, 32)], + ); } test_packageImportsSortedByPath() async { @@ -279,58 +287,65 @@ part 'a.dart'; test_reportOneNodeOnlyOnce() async { newFile('$testPackageLibPath/a.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; import 'a.dart'; import 'package:js/js.dart'; // ignore_for_file: unused_import -''', [ - lint(50, 28), - ]); +''', + [lint(50, 28)], + ); } test_sortDirectiveSectionsAlphabetically_dartSchema_docImport() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// @docImport 'dart:html'; /// @docImport 'dart:isolate'; /// @docImport 'dart:convert'; /// @docImport 'dart:math'; library; -''', [ - lint(67, 22), - ]); +''', + [lint(67, 22)], + ); } test_sortDirectiveSectionsAlphabetically_dartSchema_export() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'dart:isolate'; export 'dart:convert'; export 'dart:math'; -''', [ - lint(23, 22), - ]); +''', + [lint(23, 22)], + ); } test_sortDirectiveSectionsAlphabetically_dartSchema_import() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:html'; import 'dart:isolate'; import 'dart:convert'; import 'dart:math'; // ignore_for_file: unused_import -''', [ - lint(43, 22), - ]); +''', + [lint(43, 22)], + ); } test_sortDirectiveSectionsAlphabetically_dotInRelativePath_import() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import './foo1.dart'; import '../../foo2.dart'; import '../foo3.dart'; import 'foo4.dart'; // ignore_for_file: unused_import, uri_does_not_exist -''', [lint(22, 25)]); +''', + [lint(22, 25)], + ); } test_sortDirectiveSectionsAlphabetically_dotInRelativePath_import_ok() async { @@ -348,7 +363,8 @@ import 'foo1.dart'; newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); newFile('$testPackageLibPath/c.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'package:js/js.dart'; export 'package:meta/meta.dart'; export 'package:flutter/widgets.dart'; @@ -356,17 +372,17 @@ export 'package:flutter/widgets.dart'; export 'package:test/a.dart'; export 'package:test/c.dart'; export 'package:test/b.dart'; -''', [ - lint(62, 38), - lint(162, 29), - ]); +''', + [lint(62, 38), lint(162, 29)], + ); } test_sortDirectiveSectionsAlphabetically_packageSchema_import() async { newFile('$testPackageLibPath/a.dart', ''); newFile('$testPackageLibPath/b.dart', ''); newFile('$testPackageLibPath/c.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:js/js.dart'; import 'package:meta/meta.dart'; import 'package:flutter/widgets.dart'; @@ -375,10 +391,9 @@ import 'package:test/a.dart'; import 'package:test/c.dart'; import 'package:test/b.dart'; // ignore_for_file: unused_import -''', [ - lint(62, 38), - lint(162, 29), - ]); +''', + [lint(62, 38), lint(162, 29)], + ); } test_sortDirectiveSectionsAlphabetically_relativePath_export() async { @@ -386,14 +401,15 @@ import 'package:test/b.dart'; newFile('$testPackageLibPath/b.dart', ''); newFile('$testPackageLibPath/c.dart', ''); newFile('$testPackageLibPath/d.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' export 'd.dart'; export 'a.dart'; export 'b.dart'; export 'c.dart'; -''', [ - lint(17, 16), - ]); +''', + [lint(17, 16)], + ); } test_sortDirectiveSectionsAlphabetically_relativePath_import() async { @@ -401,7 +417,8 @@ export 'c.dart'; newFile('$testPackageLibPath/b.dart', ''); newFile('$testPackageLibPath/c.dart', ''); newFile('$testPackageLibPath/d.dart', ''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'd.dart'; import 'd.dart'; import 'c.dart'; @@ -411,10 +428,8 @@ import 'b.dart'; import 'a.dart'; import 'a.dart'; // ignore_for_file: duplicate_import, unused_import -''', [ - lint(34, 16), - lint(68, 16), - lint(102, 16), - ]); +''', + [lint(34, 16), lint(68, 16), lint(102, 16)], + ); } } diff --git a/pkg/linter/test/rules/discarded_futures_test.dart b/pkg/linter/test/rules/discarded_futures_test.dart index 0ffd9e0a577f..1a6740d49de4 100644 --- a/pkg/linter/test/rules/discarded_futures_test.dart +++ b/pkg/linter/test/rules/discarded_futures_test.dart @@ -32,7 +32,8 @@ Future g() async => 0; } test_constructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A() { g(); @@ -40,13 +41,14 @@ class A { } Future g() async => 0; -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_field_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var a = () { g(); @@ -54,13 +56,14 @@ class A { } Future g() async => 0; -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_function() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void recreateDir(String path) { deleteDir(path); createDir(path); @@ -68,14 +71,14 @@ void recreateDir(String path) { Future deleteDir(String path) async {} Future createDir(String path) async {} -''', [ - lint(34, 9), - lint(53, 9), - ]); +''', + [lint(34, 9), lint(53, 9)], + ); } test_function_closure() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { () { createDir('.'); @@ -83,9 +86,9 @@ void f() { } Future createDir(String path) async {} -''', [ - lint(22, 9), - ]); +''', + [lint(22, 9)], + ); } test_function_closure_ok() async { @@ -101,7 +104,8 @@ Future createDir(String path) async {} } test_function_expression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = h(() => g()); print(x); @@ -110,9 +114,9 @@ void f() { int h(Function f) => 0; Future g() async => 0; -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_function_ok_async() async { @@ -151,7 +155,8 @@ Future createDir(String path) async {} } test_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Dir{ void recreateDir(String path) { deleteDir(path); @@ -161,32 +166,33 @@ class Dir{ Future deleteDir(String path) async {} Future createDir(String path) async {} } -''', [ - lint(49, 9), - lint(70, 9), - ]); +''', + [lint(49, 9), lint(70, 9)], + ); } test_topLevel_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = () { g(); }; Future g() async => 0; -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_topLevel_assignment_expression_body() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = () => g(); Future g() async => 0; -''', [ - lint(14, 1), - ]); +''', + [lint(14, 1)], + ); } test_topLevel_assignment_ok_async() async { @@ -208,7 +214,8 @@ Future g() async => 0; } test_variable_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var handler = {}; void ff(String command) { @@ -218,8 +225,8 @@ void ff(String command) { } Future g() async => 0; -''', [ - lint(93, 1), - ]); +''', + [lint(93, 1)], + ); } } diff --git a/pkg/linter/test/rules/do_not_use_environment_test.dart b/pkg/linter/test/rules/do_not_use_environment_test.dart index cd9949ceacf8..e7b2df69df5f 100644 --- a/pkg/linter/test/rules/do_not_use_environment_test.dart +++ b/pkg/linter/test/rules/do_not_use_environment_test.dart @@ -17,42 +17,46 @@ class DoNotUseEnvironmentTest extends LintRuleTest { @override String get lintRule => LintNames.do_not_use_environment; test_bool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { bool.fromEnvironment('key'); } -''', [ - lint(13, 20), - ]); +''', + [lint(13, 20)], + ); } test_hasEnvironment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { bool.hasEnvironment('key'); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_int() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { int.fromEnvironment('key'); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { String.fromEnvironment('key'); } -''', [ - lint(13, 22), - ]); +''', + [lint(13, 22)], + ); } } diff --git a/pkg/linter/test/rules/document_ignores_test.dart b/pkg/linter/test/rules/document_ignores_test.dart index 99db91da4953..d1423ca30021 100644 --- a/pkg/linter/test/rules/document_ignores_test.dart +++ b/pkg/linter/test/rules/document_ignores_test.dart @@ -25,9 +25,7 @@ int x = 0; // ignore: unused_element int _y = 0; ''', - [ - lint(12, 25), - ], + [lint(12, 25)], ); } @@ -38,9 +36,7 @@ int x = 0; // Text. // ignore: unused_element int _y = 0; ''', - [ - lint(20, 25), - ], + [lint(20, 25)], ); } @@ -78,9 +74,7 @@ int _y = 0 as int; // ignore_for_file: unnecessary_cast int _y = 0 as int; ''', - [ - lint(45, 36), - ], + [lint(45, 36)], ); } diff --git a/pkg/linter/test/rules/empty_catches_test.dart b/pkg/linter/test/rules/empty_catches_test.dart index bd3867dc21f0..6543a0e19806 100644 --- a/pkg/linter/test/rules/empty_catches_test.dart +++ b/pkg/linter/test/rules/empty_catches_test.dart @@ -29,15 +29,16 @@ void foo() { } test_emptyCatch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { try { throw Exception(); } catch (e) {} } -''', [ - lint(58, 2), - ]); +''', + [lint(58, 2)], + ); } test_statement() async { diff --git a/pkg/linter/test/rules/empty_constructor_bodies_test.dart b/pkg/linter/test/rules/empty_constructor_bodies_test.dart index 37d0b2c3b31d..9b52a9966824 100644 --- a/pkg/linter/test/rules/empty_constructor_bodies_test.dart +++ b/pkg/linter/test/rules/empty_constructor_bodies_test.dart @@ -18,13 +18,14 @@ class EmptyConstructorBodiesTest extends LintRuleTest { String get lintRule => LintNames.empty_constructor_bodies; test_empty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A() {} } -''', [ - lint(16, 2), - ]); +''', + [lint(16, 2)], + ); } test_empty_withComment() async { diff --git a/pkg/linter/test/rules/empty_statements_test.dart b/pkg/linter/test/rules/empty_statements_test.dart index 07b775c62812..6fd43938e67a 100644 --- a/pkg/linter/test/rules/empty_statements_test.dart +++ b/pkg/linter/test/rules/empty_statements_test.dart @@ -18,47 +18,51 @@ class EmptyStatementsTest extends LintRuleTest { String get lintRule => LintNames.empty_statements; test_emptyFor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool b) { for ( ; b; ); } -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_emptyIf_followedByBlock() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool b) { if (b); { print(b); } } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_emptyIf_followedByStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool b) { if (b); print(b); } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_emptyWhile() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool b) { while (b); } -''', [ - lint(28, 1), - ]); +''', + [lint(28, 1)], + ); } test_nonEmptyIf_emptyBlock() async { @@ -79,7 +83,8 @@ void f(bool b) { /// https://github.com/dart-lang/linter/issues/4410 test_switchPatternCase_justEmpties() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch(true) { case true : @@ -90,15 +95,15 @@ f() { print(''); } } -''', [ - lint(45, 1), - lint(53, 1), - ]); +''', + [lint(45, 1), lint(53, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4410 test_switchPatternCase_leading() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch(true) { case true : @@ -108,14 +113,15 @@ f() { print(''); } } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4410 test_switchPatternCase_leading_trailing() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch(true) { case true : @@ -125,9 +131,9 @@ f() { print(''); } } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4410 @@ -146,7 +152,8 @@ f() { /// https://github.com/dart-lang/linter/issues/4410 test_switchPatternCase_trailing() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch(true) { case true : @@ -156,8 +163,8 @@ f() { print(''); } } -''', [ - lint(62, 1), - ]); +''', + [lint(62, 1)], + ); } } diff --git a/pkg/linter/test/rules/eol_at_end_of_file_test.dart b/pkg/linter/test/rules/eol_at_end_of_file_test.dart index 37b3726bb075..cfcb0a0d95b7 100644 --- a/pkg/linter/test/rules/eol_at_end_of_file_test.dart +++ b/pkg/linter/test/rules/eol_at_end_of_file_test.dart @@ -18,19 +18,21 @@ class EolAtEndOfFileTest extends LintRuleTest { String get lintRule => LintNames.eol_at_end_of_file; test_hasEol() async { - await assertDiagnostics(r''' -class A {}''', [ - lint(10, 1), - ]); + await assertDiagnostics( + r''' +class A {}''', + [lint(10, 1)], + ); } test_hasMultipleNewlines() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} -''', [ - lint(10, 1), - ]); +''', + [lint(10, 1)], + ); } test_hasNoEol() async { diff --git a/pkg/linter/test/rules/erase_dart_type_extension_types_test.dart b/pkg/linter/test/rules/erase_dart_type_extension_types_test.dart index 0436dbb31889..70d6630e2497 100644 --- a/pkg/linter/test/rules/erase_dart_type_extension_types_test.dart +++ b/pkg/linter/test/rules/erase_dart_type_extension_types_test.dart @@ -21,26 +21,28 @@ class EraseDartTypeExtensionTypesTest extends LintRuleTest { String get lintRule => LintNames.erase_dart_type_extension_types; test_isDartType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:kernel/ast.dart'; void f(Object t) { t is DartType; } -''', [ - lint(56, 13), - ]); +''', + [lint(56, 13)], + ); } test_isDartType_subclass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:kernel/ast.dart'; void f(Object t) { t is InterfaceType; } -''', [ - lint(56, 18), - ]); +''', + [lint(56, 18)], + ); } } diff --git a/pkg/linter/test/rules/exhaustive_cases_test.dart b/pkg/linter/test/rules/exhaustive_cases_test.dart index 74b02844618d..d4860b80e88b 100644 --- a/pkg/linter/test/rules/exhaustive_cases_test.dart +++ b/pkg/linter/test/rules/exhaustive_cases_test.dart @@ -28,7 +28,8 @@ void ae(ActualEnum e) { String get lintRule => LintNames.exhaustive_cases; test_enumLike() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class E { final int i; const E._(this.i); @@ -45,9 +46,9 @@ void e(E e) { case E.f: } } -''', [ - lint(147, 10), - ]); +''', + [lint(147, 10)], + ); } test_enumLike_default_ok() async { @@ -73,7 +74,8 @@ void okDefault(E e) { } test_enumLike_deprecatedFields() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class DeprecatedFields { final int i; const DeprecatedFields._(this.i); @@ -111,10 +113,12 @@ void dep(DeprecatedFields e) { break; } } -''', [ - lint(449, 10), - error(HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE, 599, 6), - ]); +''', + [ + lint(449, 10), + error(HintCode.DEPRECATED_MEMBER_USE_FROM_SAME_PACKAGE, 599, 6), + ], + ); } test_enumLike_ok() async { @@ -177,7 +181,8 @@ class E { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'e.dart' as prefixed; void e(prefixed.E e) { @@ -189,9 +194,9 @@ void e(prefixed.E e) { print('e'); } } -''', [ - lint(55, 9), - ]); +''', + [lint(55, 9)], + ); } test_notEnumLike_ok() async { diff --git a/pkg/linter/test/rules/file_names_test.dart b/pkg/linter/test/rules/file_names_test.dart index d2f6a35392e3..18db318ca9e8 100644 --- a/pkg/linter/test/rules/file_names_test.dart +++ b/pkg/linter/test/rules/file_names_test.dart @@ -22,11 +22,12 @@ class FileNamesInvalidTest extends LintRuleTest { String get testFilePath => '$testPackageLibPath/a-test.dart'; test_invalidName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { } -''', [ - lint(0, 0), - ]); +''', + [lint(0, 0)], + ); } } diff --git a/pkg/linter/test/rules/flutter_style_todos_test.dart b/pkg/linter/test/rules/flutter_style_todos_test.dart index 3dd38750cc90..560095be5bbc 100644 --- a/pkg/linter/test/rules/flutter_style_todos_test.dart +++ b/pkg/linter/test/rules/flutter_style_todos_test.dart @@ -48,94 +48,50 @@ class FlutterStyleTodosTest extends LintRuleTest { } test_badUsername_comma() async { - await assertDiagnostics( - r'// TODO(user1,user2): bla', - [ - lint(0, 25), - ], - ); + await assertDiagnostics(r'// TODO(user1,user2): bla', [lint(0, 25)]); } test_badUsername_extraSymbols() async { - await assertDiagnostics( - r'// TODO(#12357): bla', - [ - lint(0, 20), - ], - ); + await assertDiagnostics(r'// TODO(#12357): bla', [lint(0, 20)]); } test_charactersBeforeTODO() async { - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' // comment TODO(user): bla /// final todo = Todo(name: 'test todo', description: 'todo description'); /// Something interesting. TODO(someone): this is an ugly test case. -''', - ); +'''); } test_docComment() async { - await assertDiagnostics( - r'/// TODO(user): bla', - [ - lint(0, 19), - ], - ); + await assertDiagnostics(r'/// TODO(user): bla', [lint(0, 19)]); } test_extraColon() async { - await assertDiagnostics( - r'// TODO:(user): bla', - [ - lint(0, 19), - ], - ); + await assertDiagnostics(r'// TODO:(user): bla', [lint(0, 19)]); } test_goodPatterns() async { - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' // TODO(somebody): something // TODO(somebody): something, https://github.com/flutter/flutter -''', - ); +'''); } test_justTodo() async { - await assertDiagnostics( - r'// TODO', - [ - lint(0, 7), - ], - ); + await assertDiagnostics(r'// TODO', [lint(0, 7)]); } test_justTodo_noLeadingSpace() async { - await assertDiagnostics( - r'//TODO', - [ - lint(0, 6), - ], - ); + await assertDiagnostics(r'//TODO', [lint(0, 6)]); } test_missingColon() async { - await assertDiagnostics( - r'// TODO(user) bla', - [ - lint(0, 17), - ], - ); + await assertDiagnostics(r'// TODO(user) bla', [lint(0, 17)]); } test_missingParens() async { - await assertDiagnostics( - r'// TODO: bla', - [ - lint(0, 12), - ], - ); + await assertDiagnostics(r'// TODO: bla', [lint(0, 12)]); } test_properFormat_dottedUsername() async { @@ -159,11 +115,6 @@ class FlutterStyleTodosTest extends LintRuleTest { } test_spaceBeforeColon() async { - await assertDiagnostics( - r'// TODO(user) : bla', - [ - lint(0, 19), - ], - ); + await assertDiagnostics(r'// TODO(user) : bla', [lint(0, 19)]); } } diff --git a/pkg/linter/test/rules/hash_and_equals_test.dart b/pkg/linter/test/rules/hash_and_equals_test.dart index ffaa47567143..d4d861b23872 100644 --- a/pkg/linter/test/rules/hash_and_equals_test.dart +++ b/pkg/linter/test/rules/hash_and_equals_test.dart @@ -42,29 +42,36 @@ part 'test.dart'; class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { bool operator ==(Object other) => false; } -''', [ - lint(53, 2), - ]); +''', + [lint(53, 2)], + ); } test_enum_missingHash() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; @override bool operator ==(Object other) => false; } -''', [ - error( - CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, 46, 2), - // no lint - ]); +''', + [ + error( + CompileTimeErrorCode.ILLEGAL_CONCRETE_ENUM_MEMBER_DECLARATION, + 46, + 2, + ), + // no lint + ], + ); } test_equalsEquals_andHashCode() async { @@ -92,48 +99,57 @@ class C { } test_equalsEquals_noHashCode() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @override bool operator ==(Object other) => false; } -''', [ - lint(38, 2), - ]); +''', + [lint(38, 2)], + ); } test_extensionType_missingHash() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { bool operator ==(Object other) => false; } -''', [ - // No lint. - error( - CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_MEMBER_OF_OBJECT, 45, 2), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_MEMBER_OF_OBJECT, + 45, + 2, + ), + ], + ); } test_hashCode_noEqualsEquals() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @override int get hashCode => 7; } -''', [ - lint(32, 8), - ]); +''', + [lint(32, 8)], + ); } test_hashCodeField_missingEqualsEquals() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { @override final int hashCode = 7; } -''', [ - lint(34, 8), - ]); +''', + [lint(34, 8)], + ); } test_neither() async { diff --git a/pkg/linter/test/rules/implementation_imports_test.dart b/pkg/linter/test/rules/implementation_imports_test.dart index 57e753e39d35..3fc7de732a08 100644 --- a/pkg/linter/test/rules/implementation_imports_test.dart +++ b/pkg/linter/test/rules/implementation_imports_test.dart @@ -13,7 +13,7 @@ void main() { group('isPackage', () { for (var uri in [ Uri.parse('package:foo/src/bar.dart'), - Uri.parse('package:foo/src/baz/bar.dart') + Uri.parse('package:foo/src/baz/bar.dart'), ]) { test(uri.toString(), () { expect(isPackage(uri), isTrue); @@ -22,7 +22,7 @@ void main() { for (var uri in [ Uri.parse('foo/bar.dart'), Uri.parse('src/bar.dart'), - Uri.parse('dart:async') + Uri.parse('dart:async'), ]) { test(uri.toString(), () { expect(isPackage(uri), isFalse); @@ -33,15 +33,21 @@ void main() { group('samePackage', () { test('identity', () { expect( - samePackage(Uri.parse('package:foo/src/bar.dart'), - Uri.parse('package:foo/src/bar.dart')), - isTrue); + samePackage( + Uri.parse('package:foo/src/bar.dart'), + Uri.parse('package:foo/src/bar.dart'), + ), + isTrue, + ); }); test('foo/bar.dart', () { expect( - samePackage(Uri.parse('package:foo/src/bar.dart'), - Uri.parse('package:foo/bar.dart')), - isTrue); + samePackage( + Uri.parse('package:foo/src/bar.dart'), + Uri.parse('package:foo/bar.dart'), + ), + isTrue, + ); }); }); }); @@ -49,7 +55,7 @@ void main() { group('implementation', () { for (var uri in [ Uri.parse('package:foo/src/bar.dart'), - Uri.parse('package:foo/src/baz/bar.dart') + Uri.parse('package:foo/src/baz/bar.dart'), ]) { test(uri.toString(), () { expect(isImplementation(uri), isTrue); @@ -57,7 +63,7 @@ void main() { } for (var uri in [ Uri.parse('package:foo/bar.dart'), - Uri.parse('src/bar.dart') + Uri.parse('src/bar.dart'), ]) { test(uri.toString(), () { expect(isImplementation(uri), isFalse); @@ -82,13 +88,13 @@ class ImplementationImportsTest extends LintRuleTest { part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; import 'package:flutter/src/material/colors.dart'; -''', [ - error(WarningCode.UNUSED_IMPORT, 26, 42), - lint(26, 42), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 26, 42), lint(26, 42)], + ); } } diff --git a/pkg/linter/test/rules/implicit_call_tearoffs_test.dart b/pkg/linter/test/rules/implicit_call_tearoffs_test.dart index a1ca39b78358..353834bc6a71 100644 --- a/pkg/linter/test/rules/implicit_call_tearoffs_test.dart +++ b/pkg/linter/test/rules/implicit_call_tearoffs_test.dart @@ -27,20 +27,22 @@ class C { } test_ifNullExpression_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function() f(C? c1, C c2) { return c1 ?? c2; } class C { void call() {} } -''', [ - lint(42, 8), - ]); +''', + [lint(42, 8)], + ); } test_instanceCreation_argumentToFunctionTypeParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(C()); } @@ -48,13 +50,14 @@ class C { void call() {} } void g(void Function() f) {} -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_instanceCreation_argumentToFunctionTypeParameter_instantiatedTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(C()); } @@ -62,13 +65,14 @@ void g(void Function(int) f) {} class C { void call(T arg) {} } -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_instanceCreation_cascadeExpression_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function() f() { return C()..other(); } @@ -76,53 +80,57 @@ class C { void call() {} void other() {} } -''', [ - lint(31, 12), - ]); +''', + [lint(31, 12)], + ); } test_instanceCreation_functionContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Function f = C(); class C { void call(T arg) {} } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_instanceCreation_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function() f = C(); class C { void call() {} } -''', [ - lint(20, 3), - ]); +''', + [lint(20, 3)], + ); } test_instanceCreation_functionTypeContext_instantiatedTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(int) f = C(); class C { void call(T arg) {} } -''', [ - lint(23, 3), - ]); +''', + [lint(23, 3)], + ); } test_instanceCreation_genericFunctionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(T) f = C(); class C { void call(T arg) {} } -''', [ - lint(24, 3), - ]); +''', + [lint(24, 3)], + ); } test_instanceCreation_noContext() async { @@ -135,7 +143,8 @@ class C { } test_simpleIdentifier_argumentToFunctionTypedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { g(c); } @@ -143,13 +152,14 @@ void g(void Function() f) {} class C { void call() {} } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_simpleIdentifier_argumentToFunctionTypeParameter_instantiatedTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { g(c); } @@ -157,87 +167,94 @@ void g(void Function(int) f) {} class C { void call(T arg) {} } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_simpleIdentifier_functionContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { Function fn = c; } class C { void call() {} } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_simpleIdentifier_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function() f(C c) => c; class C { void call() {} } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_simpleIdentifier_functionTypeContext_instantiatedTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(int) f(C c) => c; class C { void call(T arg) {} } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_simpleIdentifier_functionTypeContext_listTypArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { [c]; } class C { void call() {} } -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_simpleIdentifier_genericFunctionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { void Function(T) fn = c; } class C { void call(T arg) {} } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_simpleIdentifier_listLiteral_listOfFunctionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f(C c) { return [c]; } class C { void call() {} } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_tearoffInstantiation_argumentToFunctionTypeParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { g(c); } @@ -245,52 +262,56 @@ void g(void Function(int) f) {} class C { void call(T arg) {} } -''', [ - lint(18, 6), - ]); +''', + [lint(18, 6)], + ); } test_tearoffInstantiation_functionContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { Function fn = c; } class C { void call(T arg) {} } -''', [ - lint(30, 6), - ]); +''', + [lint(30, 6)], + ); } test_tearoffInstantiation_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { void Function(int) fn = c; } class C { void call(T arg) {} } -''', [ - lint(40, 6), - ]); +''', + [lint(40, 6)], + ); } test_tearoffInstantiation_noContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c; } class C { void call(T arg) {} } -''', [ - lint(16, 6), - ]); +''', + [lint(16, 6)], + ); } test_tearoffInstantiationOfInstanceCreation_argumentToFunctionTypeParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(C()); } @@ -298,43 +319,46 @@ void g(void Function(int) f) {} class C { void call(T arg) {} } -''', [ - lint(15, 8), - ]); +''', + [lint(15, 8)], + ); } test_tearoffInstantiationOfInstanceCreation_functionContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Function f = C(); // LINT class C { void call(T arg) {} } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } test_tearoffInstantiationOfInstanceCreation_functionTypeContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(int) f = C(); class C { void call(T arg) {} } -''', [ - lint(23, 8), - ]); +''', + [lint(23, 8)], + ); } test_tearoffInstantiationofInstanceCreation_noContext() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { C(); } class C { void call(T arg) {} } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } } diff --git a/pkg/linter/test/rules/implicit_reopen_test.dart b/pkg/linter/test/rules/implicit_reopen_test.dart index 5e6b6112f777..295ba3b6059a 100644 --- a/pkg/linter/test/rules/implicit_reopen_test.dart +++ b/pkg/linter/test/rules/implicit_reopen_test.dart @@ -22,124 +22,145 @@ class ImplicitReopenInducedModifierTest extends LintRuleTest { String get lintRule => LintNames.implicit_reopen; test_inducedFinal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class F {} sealed class S extends F {} base class C extends S {} -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_inducedFinal_base_interface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' base class C {} interface class D {} sealed class E extends D implements C {} base class B extends E {} -''', [ - lint(89, 1), - ]); +''', + [lint(89, 1)], + ); } test_inducedFinal_baseMixin_interface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class D {} base mixin G {} sealed class H extends D with G {} base class B extends H {} -''', [ - lint(83, 1), - ]); +''', + [lint(83, 1)], + ); } test_inducedFinal_interface_base_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class S {} base class I {} sealed class A extends S implements I {} class C extends A {} -''', [ - // No lint. - error(CompileTimeErrorCode.SUBTYPE_OF_BASE_IS_NOT_BASE_FINAL_OR_SEALED, - 84, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.SUBTYPE_OF_BASE_IS_NOT_BASE_FINAL_OR_SEALED, + 84, + 1, + ), + ], + ); } test_inducedFinal_mixin_finalClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class S {} mixin M {} sealed class A extends S with M {} base class B extends A {} -''', [ - lint(74, 1), - ]); +''', + [lint(74, 1)], + ); } test_inducedInterface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} sealed class S extends I {} class C extends S {} -''', [ - lint(55, 1), - ]); +''', + [lint(55, 1)], + ); } test_inducedInterface_base() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} sealed class S extends I {} base class C extends S {} -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_inducedInterface_base_mixin_interface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class S {} mixin M {} sealed class A extends S with M {} base class C extends A {} -''', [ - lint(78, 1), - ]); +''', + [lint(78, 1)], + ); } test_inducedInterface_mixin_interface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class S {} mixin M {} sealed class A extends S with M {} class C extends A {} -''', [ - lint(73, 1), - ]); +''', + [lint(73, 1)], + ); } test_inducedInterface_twoLevels() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} sealed class S extends I {} sealed class S2 extends S {} class C extends S2 {} -''', [ - lint(84, 1), - ]); +''', + [lint(84, 1)], + ); } test_subtypingFinalError_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class F {} sealed class S extends F {} class C extends S {} -''', [ - // No lint. - error(CompileTimeErrorCode.SUBTYPE_OF_FINAL_IS_NOT_BASE_FINAL_OR_SEALED, - 51, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.SUBTYPE_OF_FINAL_IS_NOT_BASE_FINAL_OR_SEALED, + 51, + 1, + ), + ], + ); } } @@ -152,25 +173,32 @@ class ImplicitReopenTest extends LintRuleTest { String get lintRule => LintNames.implicit_reopen; test_class_classFinal_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class F {} class C extends F {} -''', [ - // No lint. - error(CompileTimeErrorCode.SUBTYPE_OF_FINAL_IS_NOT_BASE_FINAL_OR_SEALED, - 24, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.SUBTYPE_OF_FINAL_IS_NOT_BASE_FINAL_OR_SEALED, + 24, + 1, + ), + ], + ); } test_class_classInterface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} class C extends I {} -''', [ - lint(28, 1), - ]); +''', + [lint(28, 1)], + ); } test_class_classInterface_outsideLib_ok() async { @@ -178,15 +206,21 @@ class C extends I {} interface class I {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; class C extends I {} -''', [ - // No lint. - error(CompileTimeErrorCode.INTERFACE_CLASS_EXTENDED_OUTSIDE_OF_LIBRARY, - 34, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.INTERFACE_CLASS_EXTENDED_OUTSIDE_OF_LIBRARY, + 34, + 1, + ), + ], + ); } test_class_classInterface_reopened_ok() async { @@ -201,23 +235,25 @@ class C extends I {} } test_classBase_classFinal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class F {} base class B extends F {} -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_classBase_classInterface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} base class B extends I {} -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_classFinal_classInterface_ok() async { @@ -229,35 +265,43 @@ final class C extends I {} } test_classMixin_classInterface_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} mixin class M extends I {} -''', [ - // No lint. - error(CompileTimeErrorCode.MIXIN_CLASS_DECLARATION_EXTENDS_NOT_OBJECT, 44, - 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.MIXIN_CLASS_DECLARATION_EXTENDS_NOT_OBJECT, + 44, + 1, + ), + ], + ); } test_classTypeAlias_class_classInterface() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} mixin M {} class C = I with M; -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_classTypeAlias_classBase_classFinal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final class C {} mixin M {} base class D = C with M; -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_classTypeAlias_classBase_classFinal_reopened() async { @@ -272,13 +316,16 @@ base class D = C with M; } test_mixin_classInterface_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' interface class I {} mixin M extends I {} -''', [ - // No lint. - error(ParserErrorCode.EXPECTED_INSTEAD, 30, 7), - ]); +''', + [ + // No lint. + error(ParserErrorCode.EXPECTED_INSTEAD, 30, 7), + ], + ); } } diff --git a/pkg/linter/test/rules/invalid_case_patterns_test.dart b/pkg/linter/test/rules/invalid_case_patterns_test.dart index 6fab2a08c4d2..702c62da21d8 100644 --- a/pkg/linter/test/rules/invalid_case_patterns_test.dart +++ b/pkg/linter/test/rules/invalid_case_patterns_test.dart @@ -19,44 +19,47 @@ class InvalidCasePatternsTestLanguage219 extends LintRuleTest String get lintRule => LintNames.invalid_case_patterns; test_binaryExpression_logicalAnd() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(bool b) { switch (b) { case true && false: } } -''', [ - lint(36, 13), - ]); +''', + [lint(36, 13)], + ); } test_binaryExpression_plus() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case 1 + 2: } } -''', [ - lint(43, 5), - ]); +''', + [lint(43, 5)], + ); } test_conditionalExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case true ? 1 : 2: } } -''', [ - lint(43, 12), - error(WarningCode.DEAD_CODE, 54, 1), - ]); +''', + [lint(43, 12), error(WarningCode.DEAD_CODE, 54, 1)], + ); } test_constConstructorCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { const C(); } @@ -66,9 +69,9 @@ f(C c) { case C(): } } -''', [ - lint(59, 3), - ]); +''', + [lint(59, 3)], + ); } test_constConstructorCall_explicitConst_ok() async { @@ -85,65 +88,68 @@ f(C c) { } test_identicalCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case identical(1, 2): } } -''', [ - lint(43, 15), - ]); +''', + [lint(43, 15)], + ); } test_isExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case 1 is int: } } -''', [ - error(WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, 43, 8), - lint(43, 8), - ]); +''', + [error(WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, 43, 8), lint(43, 8)], + ); } test_isNotExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case 1 is! int: } } -''', [ - error(WarningCode.UNNECESSARY_TYPE_CHECK_FALSE, 43, 9), - lint(43, 9), - ]); +''', + [error(WarningCode.UNNECESSARY_TYPE_CHECK_FALSE, 43, 9), lint(43, 9)], + ); } test_lengthCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case ''.length: } } -''', [ - lint(43, 9), - ]); +''', + [lint(43, 9)], + ); } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case [1, 2]: } } -''', [ - lint(43, 6), - ]); +''', + [lint(43, 6)], + ); } test_listLiteral_ok() async { @@ -157,27 +163,29 @@ void f(Object o) { } test_listLiteral_typeArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case [1, 2]: } } -''', [ - lint(43, 11), - ]); +''', + [lint(43, 11)], + ); } test_mapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case {'k': 'v'}: } } -''', [ - lint(42, 10), - ]); +''', + [lint(42, 10)], + ); } test_mapLiteral_ok() async { @@ -191,39 +199,42 @@ void f(Object o) { } test_mapLiteral_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case ({'k': 'v'}): } } -''', [ - lint(43, 10), - ]); +''', + [lint(43, 10)], + ); } test_mapLiteral_parenthesized_twice() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case (({'k': 'v'})): } } -''', [ - lint(44, 10), - ]); +''', + [lint(44, 10)], + ); } test_mapLiteral_typeArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case {'k': 'v'}: } } -''', [ - lint(42, 25), - ]); +''', + [lint(42, 25)], + ); } test_parenthesizedExpression_ok() async { @@ -247,15 +258,16 @@ void f(Object o) { } test_setLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case {1}: } } -''', [ - lint(43, 3), - ]); +''', + [lint(43, 3)], + ); } test_setLiteral_ok() async { @@ -269,53 +281,57 @@ void f(Object o) { } test_setLiteral_typeArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { switch (o) { case {1}: } } -''', [ - lint(43, 8), - ]); +''', + [lint(43, 8)], + ); } test_unaryOperator_minus() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { const o = 1; switch (1) { case -o: } } -''', [ - lint(50, 2), - ]); +''', + [lint(50, 2)], + ); } test_unaryOperator_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { const b = false; switch (true) { case !b: } } -''', [ - lint(65, 2), - ]); +''', + [lint(65, 2)], + ); } test_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(int n) { const _ = 3; switch (n) { case _: } } -''', [ - lint(50, 1), - ]); +''', + [lint(50, 1)], + ); } } diff --git a/pkg/linter/test/rules/invalid_runtime_check_with_js_interop_types_test.dart b/pkg/linter/test/rules/invalid_runtime_check_with_js_interop_types_test.dart index 561e93c152e0..0db52d866557 100644 --- a/pkg/linter/test/rules/invalid_runtime_check_with_js_interop_types_test.dart +++ b/pkg/linter/test/rules/invalid_runtime_check_with_js_interop_types_test.dart @@ -29,8 +29,9 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_baseTypesAs_js_type_as_same_js_type() async { - await _testCasts( - [_AsCast('JSBoolean', 'JSBoolean', lint: false, unnecessary: true)]); + await _testCasts([ + _AsCast('JSBoolean', 'JSBoolean', lint: false, unnecessary: true), + ]); } test_baseTypesAs_js_type_as_subtype() async { @@ -46,7 +47,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _AsCast('JSAny', 'Object', lint: false), _AsCast('JSObject', 'dynamic', lint: false), _AsCast('List', 'Object', lint: false), - _AsCast('List', 'dynamic', lint: false) + _AsCast('List', 'dynamic', lint: false), ]); } @@ -59,7 +60,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _AsCast('Object', 'JSAny', lint: false), _AsCast('dynamic', 'JSObject', lint: false), _AsCast('List', 'Object', lint: false), - _AsCast('List', 'dynamic', lint: false) + _AsCast('List', 'dynamic', lint: false), ]); } @@ -72,8 +73,9 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_baseTypesIs_js_type_is_same_js_type() async { - await _testChecks( - [_IsCheck('JSBoolean', 'JSBoolean', lint: false, unnecessary: true)]); + await _testChecks([ + _IsCheck('JSBoolean', 'JSBoolean', lint: false, unnecessary: true), + ]); } test_baseTypesIs_js_type_is_subtype() async { @@ -81,8 +83,9 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_baseTypesIs_js_type_is_supertype() async { - await _testChecks( - [_IsCheck('JSArray', 'JSObject', lint: false, unnecessary: true)]); + await _testChecks([ + _IsCheck('JSArray', 'JSObject', lint: false, unnecessary: true), + ]); } test_baseTypesIs_js_type_is_top_type() async { @@ -90,7 +93,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _IsCheck('JSAny', 'Object', lint: false, unnecessary: true), _IsCheck('JSObject', 'dynamic', lint: false, unnecessary: true), _IsCheck('List', 'Object', lint: false, unnecessary: true), - _IsCheck('List', 'dynamic', lint: false, unnecessary: true) + _IsCheck('List', 'dynamic', lint: false, unnecessary: true), ]); } @@ -107,49 +110,60 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { // check the JS interop type against anything, since the left type is not // generic. _IsCheck('Object', 'List', lint: false), - _IsCheck('dynamic', 'List', lint: false) + _IsCheck('dynamic', 'List', lint: false), ]); } test_cyclicGenericInterfaceType_as() async { - await _testCasts([ - _AsCast('Object', 'A', lint: false) - ], typeDeclarations: [ - r''' + await _testCasts( + [_AsCast('Object', 'A', lint: false)], + typeDeclarations: [ + r''' class A> {} - ''' - ], typeParameters: [ - 'T extends A' - ]); + ''', + ], + typeParameters: ['T extends A'], + ); } test_cyclicGenericInterfaceType_is() async { - await _testChecks([ - _IsCheck('Object', 'A', lint: false) - ], typeDeclarations: [ - r''' + await _testChecks( + [_IsCheck('Object', 'A', lint: false)], + typeDeclarations: [ + r''' class A> {} - ''' - ], typeParameters: [ - 'T extends A' - ]); + ''', + ], + typeParameters: ['T extends A'], + ); } // TODO(srujzs): Some of the following type tests should result in an error, // but `canBeSubtypeOf` doesn't nest for function types. test_functionTypesAs_function_type_with_js_types_as() async { await _testCasts([ - _AsCast('JSAny Function()', 'JSAny Function()', - lint: false, unnecessary: true), + _AsCast( + 'JSAny Function()', + 'JSAny Function()', + lint: false, + unnecessary: true, + ), _AsCast('JSAny Function()', 'JSBoolean Function()', lint: false), _AsCast('JSBoolean Function()', 'JSAny Function()', lint: false), _AsCast('JSString Function()', 'JSBoolean Function()', lint: false), - _AsCast('void Function(JSAny)', 'void Function(JSAny)', - lint: false, unnecessary: true), + _AsCast( + 'void Function(JSAny)', + 'void Function(JSAny)', + lint: false, + unnecessary: true, + ), _AsCast('void Function(JSAny)', 'void Function(JSBoolean)', lint: false), _AsCast('void Function(JSBoolean)', 'void Function(JSAny)', lint: false), - _AsCast('void Function(JSString)', 'void Function(JSBoolean)', - lint: false) + _AsCast( + 'void Function(JSString)', + 'void Function(JSBoolean)', + lint: false, + ), ]); } @@ -157,19 +171,38 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { // but `canBeSubtypeOf` doesn't nest for function types. test_functionTypesIs_function_type_with_js_types_is() async { await _testChecks([ - _IsCheck('JSAny Function()', 'JSAny Function()', - lint: false, unnecessary: true), + _IsCheck( + 'JSAny Function()', + 'JSAny Function()', + lint: false, + unnecessary: true, + ), _IsCheck('JSAny Function()', 'JSBoolean Function()', lint: false), - _IsCheck('JSBoolean Function()', 'JSAny Function()', - lint: false, unnecessary: true), + _IsCheck( + 'JSBoolean Function()', + 'JSAny Function()', + lint: false, + unnecessary: true, + ), _IsCheck('JSString Function()', 'JSBoolean Function()', lint: false), - _IsCheck('void Function(JSAny)', 'void Function(JSAny)', - lint: false, unnecessary: true), - _IsCheck('void Function(JSAny)', 'void Function(JSBoolean)', - lint: false, unnecessary: true), + _IsCheck( + 'void Function(JSAny)', + 'void Function(JSAny)', + lint: false, + unnecessary: true, + ), + _IsCheck( + 'void Function(JSAny)', + 'void Function(JSBoolean)', + lint: false, + unnecessary: true, + ), _IsCheck('void Function(JSBoolean)', 'void Function(JSAny)', lint: false), - _IsCheck('void Function(JSString)', 'void Function(JSBoolean)', - lint: false) + _IsCheck( + 'void Function(JSString)', + 'void Function(JSBoolean)', + lint: false, + ), ]); } @@ -183,18 +216,22 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { await _testCasts([ _AsCast('JSArray', 'JSArray', lint: false), _AsCast('JSArray', 'JSArray', lint: false), - _AsCast('JSArray', 'JSArray', lint: false) + _AsCast('JSArray', 'JSArray', lint: false), ]); } test_genericTypesAs_generic_type_with_multiple_type_parameter_as() async { await _testCasts([ - _AsCast('Map', 'Map', - lint: false, unnecessary: true), + _AsCast( + 'Map', + 'Map', + lint: false, + unnecessary: true, + ), _AsCast('Map', 'Map', lint: false), _AsCast('Map', 'Map'), _AsCast('Map', 'Map', lint: false), - _AsCast('Map', 'Map') + _AsCast('Map', 'Map'), ]); } @@ -204,7 +241,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { test_genericTypesAs_js_type_generic_as_same_js_type_generic() async { await _testCasts([ - _AsCast('Set', 'Set', lint: false, unnecessary: true) + _AsCast('Set', 'Set', lint: false, unnecessary: true), ]); } @@ -213,14 +250,15 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_genericTypesAs_js_type_generic_as_supertype_generic() async { - await _testCasts( - [_AsCast('Future', 'Future', lint: false)]); + await _testCasts([ + _AsCast('Future', 'Future', lint: false), + ]); } test_genericTypesAs_js_type_generic_as_top_type_generic() async { await _testCasts([ _AsCast('List', 'List', lint: false), - _AsCast('List', 'List', lint: false) + _AsCast('List', 'List', lint: false), ]); } @@ -229,8 +267,9 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_genericTypesAs_js_type_generic_as_unrelated_js_type_generic_with_unrelated_container() async { - await _testCasts( - [_AsCast('List', 'Set', lint: false)]); + await _testCasts([ + _AsCast('List', 'Set', lint: false), + ]); } test_genericTypesAs_js_type_generic_with_container_inheritance_as() async { @@ -245,14 +284,14 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { // generics, and you can't declare a class that subtypes both the left // and right type, but `canBeSubtypeOf` doesn't nest in this case. _AsCast('List', 'Iterable', lint: false), - _AsCast('Iterable', 'List', lint: false) + _AsCast('Iterable', 'List', lint: false), ]); } test_genericTypesAs_top_type_generic_as_js_type_generic() async { await _testCasts([ _AsCast('List', 'List', lint: false), - _AsCast('List', 'List', lint: false) + _AsCast('List', 'List', lint: false), ]); } @@ -264,22 +303,34 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { // ignored. test_genericTypesIs_generic_js_type_is_generic_js_type() async { await _testChecks([ - _IsCheck('JSArray', 'JSArray', - lint: false, unnecessary: true), + _IsCheck( + 'JSArray', + 'JSArray', + lint: false, + unnecessary: true, + ), _IsCheck('JSArray', 'JSArray', lint: false), - _IsCheck('JSArray', 'JSArray', lint: false) + _IsCheck('JSArray', 'JSArray', lint: false), ]); } test_genericTypesIs_generic_type_with_multiple_type_parameter_is() async { await _testChecks([ - _IsCheck('Map', 'Map', - lint: false, unnecessary: true), - _IsCheck('Map', 'Map', - lint: false, unnecessary: true), + _IsCheck( + 'Map', + 'Map', + lint: false, + unnecessary: true, + ), + _IsCheck( + 'Map', + 'Map', + lint: false, + unnecessary: true, + ), _IsCheck('Map', 'Map'), _IsCheck('Map', 'Map'), - _IsCheck('Map', 'Map') + _IsCheck('Map', 'Map'), ]); } @@ -289,7 +340,12 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { test_genericTypesIs_js_type_generic_is_same_js_type_generic() async { await _testChecks([ - _IsCheck('Set', 'Set', lint: false, unnecessary: true) + _IsCheck( + 'Set', + 'Set', + lint: false, + unnecessary: true, + ), ]); } @@ -299,15 +355,19 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { test_genericTypesIs_js_type_generic_is_supertype_generic() async { await _testChecks([ - _IsCheck('Future', 'Future', - lint: false, unnecessary: true) + _IsCheck( + 'Future', + 'Future', + lint: false, + unnecessary: true, + ), ]); } test_genericTypesIs_js_type_generic_is_top_type_generic() async { await _testChecks([ _IsCheck('List', 'List', lint: false, unnecessary: true), - _IsCheck('List', 'List', lint: false, unnecessary: true) + _IsCheck('List', 'List', lint: false, unnecessary: true), ]); } @@ -316,17 +376,26 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_genericTypesIs_js_type_generic_is_unrelated_js_type_generic_with_unrelated_container() async { - await _testChecks( - [_IsCheck('List', 'Set', lint: false)]); + await _testChecks([ + _IsCheck('List', 'Set', lint: false), + ]); } test_genericTypesIs_js_type_generic_with_container_inheritance_is() async { await _testChecks([ - _IsCheck('List', 'Iterable', - lint: false, unnecessary: true), + _IsCheck( + 'List', + 'Iterable', + lint: false, + unnecessary: true, + ), _IsCheck('Iterable', 'List', lint: false), - _IsCheck('List', 'Iterable', - lint: false, unnecessary: true), + _IsCheck( + 'List', + 'Iterable', + lint: false, + unnecessary: true, + ), _IsCheck('Iterable', 'List', lint: false), // TODO(srujzs): These should be errors as there is a subtype or unrelated // check within the generics, and you can't declare a class that subtypes @@ -335,14 +404,14 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _IsCheck('List', 'Iterable', lint: false), _IsCheck('Iterable', 'List', lint: false), _IsCheck('List', 'Iterable', lint: false), - _IsCheck('Iterable', 'List', lint: false) + _IsCheck('Iterable', 'List', lint: false), ]); } test_genericTypesIs_top_type_generic_is_js_type_generic() async { await _testChecks([ _IsCheck('List', 'List'), - _IsCheck('List', 'List') + _IsCheck('List', 'List'), ]); } @@ -359,40 +428,46 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _AsCast('JSArray?', 'JSAny?', lint: false), _AsCast('JSString?', 'JSArray'), _AsCast('JSString', 'JSArray?'), - _AsCast('JSString?', 'JSArray?') + _AsCast('JSString?', 'JSArray?'), ]); } test_nullabilityAs_null_as_js_type() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'dart:js_interop'; void foo() { null as JSAny; null as JSArray?; } - ''', [error(WarningCode.CAST_FROM_NULL_ALWAYS_FAILS, 54, 13)]); + ''', + [error(WarningCode.CAST_FROM_NULL_ALWAYS_FAILS, 54, 13)], + ); } test_nullabilityAs_user_interop_type_as_user_interop_type() async { - await _testCasts([ - _AsCast('A', 'A?', lint: false), - _AsCast('A?', 'A', lint: false), - _AsCast('A?', 'A?', lint: false, unnecessary: true), - _AsCast('A?', 'B', lint: false), - _AsCast('A', 'B?', lint: false), - _AsCast('A?', 'B?', lint: false), - _AsCast('B?', 'A', lint: false), - _AsCast('B', 'A?', lint: false), - _AsCast('B?', 'A?', lint: false) - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('A', 'A?', lint: false), + _AsCast('A?', 'A', lint: false), + _AsCast('A?', 'A?', lint: false, unnecessary: true), + _AsCast('A?', 'B', lint: false), + _AsCast('A', 'B?', lint: false), + _AsCast('A?', 'B?', lint: false), + _AsCast('B?', 'A', lint: false), + _AsCast('B', 'A?', lint: false), + _AsCast('B?', 'A?', lint: false), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) implements A {} - ''' - ]); + ''', + ], + ); } test_nullabilityIs_js_type_is_js_type() async { @@ -408,515 +483,589 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { _IsCheck('JSArray?', 'JSAny?', lint: false, unnecessary: true), _IsCheck('JSString?', 'JSArray'), _IsCheck('JSString', 'JSArray?'), - _IsCheck('JSString?', 'JSArray?') + _IsCheck('JSString?', 'JSArray?'), ]); } test_nullabilityIs_null_is_js_type() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'dart:js_interop'; void foo() { null is JSAny; null is JSArray?; } - ''', [error(WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, 75, 16)]); + ''', + [error(WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, 75, 16)], + ); } test_nullabilityIs_user_interop_type_is_user_interop_type() async { - await _testChecks([ - _IsCheck('A', 'A?', lint: false, unnecessary: true), - _IsCheck('A?', 'A', lint: false), - _IsCheck('A?', 'A?', lint: false, unnecessary: true), - _IsCheck('A?', 'B'), - _IsCheck('A', 'B?'), - _IsCheck('A?', 'B?'), - _IsCheck('B?', 'A', lint: false), - _IsCheck('B', 'A?', lint: false, unnecessary: true), - _IsCheck('B?', 'A?', lint: false, unnecessary: true) - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('A', 'A?', lint: false, unnecessary: true), + _IsCheck('A?', 'A', lint: false), + _IsCheck('A?', 'A?', lint: false, unnecessary: true), + _IsCheck('A?', 'B'), + _IsCheck('A', 'B?'), + _IsCheck('A?', 'B?'), + _IsCheck('B?', 'A', lint: false), + _IsCheck('B', 'A?', lint: false, unnecessary: true), + _IsCheck('B?', 'A?', lint: false, unnecessary: true), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) implements A {} - ''' - ]); + ''', + ], + ); } test_staticInteropAs_js_type_as_static_interop_type() async { - await _testCasts([ - _AsCast('JSAny', 'A', lint: false), - _AsCast('JSObject', 'A', lint: false), - _AsCast('JSArray', 'A', lint: false), - _AsCast('JSBoolean', 'A') - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('JSAny', 'A', lint: false), + _AsCast('JSObject', 'A', lint: false), + _AsCast('JSArray', 'A', lint: false), + _AsCast('JSBoolean', 'A'), + ], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropAs_static_interop_type_as_js_type() async { - await _testCasts([ - _AsCast('A', 'JSAny', lint: false), - _AsCast('A', 'JSObject', lint: false), - _AsCast('A', 'JSArray', lint: false), - _AsCast('A', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('A', 'JSAny', lint: false), + _AsCast('A', 'JSObject', lint: false), + _AsCast('A', 'JSArray', lint: false), + _AsCast('A', 'JSBoolean'), + ], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropAs_static_interop_type_as_unrelated_type() async { - await _testCasts([ - _AsCast('A', 'String') - ], typeDeclarations: [ - r''' + await _testCasts( + [_AsCast('A', 'String')], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropAs_unrelated_type_as_static_interop_type() async { - await _testCasts([ - _AsCast('String', 'A') - ], typeDeclarations: [ - r''' + await _testCasts( + [_AsCast('String', 'A')], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } // Since A is an unrelated type, we warn users so they don't think a runtime // check is done to ensure the value actually is an A. test_staticInteropIs_js_type_is_static_interop_type() async { - await _testChecks([ - _IsCheck('JSAny', 'A'), - _IsCheck('JSObject', 'A'), - _IsCheck('JSArray', 'A'), - _IsCheck('JSBoolean', 'A') - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('JSAny', 'A'), + _IsCheck('JSObject', 'A'), + _IsCheck('JSArray', 'A'), + _IsCheck('JSBoolean', 'A'), + ], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropIs_static_interop_type_is_js_type() async { - await _testChecks([ - _IsCheck('A', 'JSAny', lint: false), - _IsCheck('A', 'JSObject', lint: false), - _IsCheck('A', 'JSArray'), - _IsCheck('A', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('A', 'JSAny', lint: false), + _IsCheck('A', 'JSObject', lint: false), + _IsCheck('A', 'JSArray'), + _IsCheck('A', 'JSBoolean'), + ], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropIs_static_interop_type_is_unrelated_type() async { - await _testChecks([ - _IsCheck('A', 'String') - ], typeDeclarations: [ - r''' + await _testChecks( + [_IsCheck('A', 'String')], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_staticInteropIs_unrelated_type_is_static_interop_type() async { - await _testChecks([ - _IsCheck('String', 'A') - ], typeDeclarations: [ - r''' + await _testChecks( + [_IsCheck('String', 'A')], + typeDeclarations: [ + r''' @JS() @staticInterop class A {} - ''' - ]); + ''', + ], + ); } test_typeParametersAs_js_type_as_js_type_parameter() async { - await _testCasts([ - _AsCast('JSAny', 'T', lint: false), - _AsCast('JSObject', 'T', lint: false), - _AsCast('JSBoolean', 'T'), - // This may or may not be a side cast, so warn. - _AsCast('JSArray', 'T') - ], typeParameters: [ - 'T extends JSObject' - ]); + await _testCasts( + [ + _AsCast('JSAny', 'T', lint: false), + _AsCast('JSObject', 'T', lint: false), + _AsCast('JSBoolean', 'T'), + // This may or may not be a side cast, so warn. + _AsCast('JSArray', 'T'), + ], + typeParameters: ['T extends JSObject'], + ); } test_typeParametersAs_js_type_parameter_as_js_type() async { - await _testCasts([ - _AsCast('T', 'JSAny', lint: false), - _AsCast('T', 'JSObject', lint: false), - _AsCast('T', 'JSBoolean'), - // This may or may not be a side cast, so warn. - _AsCast('T', 'JSUint8List') - ], typeParameters: [ - 'T extends JSObject' - ]); + await _testCasts( + [ + _AsCast('T', 'JSAny', lint: false), + _AsCast('T', 'JSObject', lint: false), + _AsCast('T', 'JSBoolean'), + // This may or may not be a side cast, so warn. + _AsCast('T', 'JSUint8List'), + ], + typeParameters: ['T extends JSObject'], + ); } test_typeParametersAs_js_type_parameter_as_js_type_parameter() async { - await _testCasts([ - _AsCast('T', 'T', lint: false, unnecessary: true), - _AsCast('U', 'U', lint: false, unnecessary: true), - _AsCast('V', 'V', lint: false, unnecessary: true), - _AsCast('T', 'U'), - _AsCast('U', 'T'), - _AsCast('T', 'V'), - _AsCast('V', 'T'), - _AsCast('U', 'V'), - _AsCast('V', 'U') - ], typeParameters: [ - 'T extends JSAny', - 'U extends JSArray', - 'V extends JSBoolean' - ]); + await _testCasts( + [ + _AsCast('T', 'T', lint: false, unnecessary: true), + _AsCast('U', 'U', lint: false, unnecessary: true), + _AsCast('V', 'V', lint: false, unnecessary: true), + _AsCast('T', 'U'), + _AsCast('U', 'T'), + _AsCast('T', 'V'), + _AsCast('V', 'T'), + _AsCast('U', 'V'), + _AsCast('V', 'U'), + ], + typeParameters: [ + 'T extends JSAny', + 'U extends JSArray', + 'V extends JSBoolean', + ], + ); } test_typeParametersAs_nested_user_interop_type_parameter_as_user_interop_type() async { - await _testCasts([ - _AsCast('T', 'A?', lint: false), - _AsCast('U?', 'A', lint: false), - _AsCast('V', 'A?', lint: false), - _AsCast('W?', 'A', lint: false), - _AsCast('X', 'A', lint: false), - _AsCast('Y?', 'A', lint: false) - ], typeParameters: [ - 'T extends A', - 'U extends B?', - 'V extends T', - 'W extends U', - 'X extends T?', - 'Y extends U?' - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('T', 'A?', lint: false), + _AsCast('U?', 'A', lint: false), + _AsCast('V', 'A?', lint: false), + _AsCast('W?', 'A', lint: false), + _AsCast('X', 'A', lint: false), + _AsCast('Y?', 'A', lint: false), + ], + typeParameters: [ + 'T extends A', + 'U extends B?', + 'V extends T', + 'W extends U', + 'X extends T?', + 'Y extends U?', + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_typeParametersAs_unrelated_type_as_js_type_parameter() async { - await _testCasts([_AsCast('String', 'T')], - typeParameters: ['T extends JSAny']); + await _testCasts( + [_AsCast('String', 'T')], + typeParameters: ['T extends JSAny'], + ); } test_typeParametersAs_unrelated_type_parameter_as_js_type() async { - await _testCasts([_AsCast('T', 'JSAny'), _AsCast('U', 'JSNumber')], - typeParameters: ['T', 'U extends int']); + await _testCasts( + [_AsCast('T', 'JSAny'), _AsCast('U', 'JSNumber')], + typeParameters: ['T', 'U extends int'], + ); } test_typeParametersAs_user_interop_type_parameter_as() async { - await _testCasts([ - _AsCast('T', 'JSAny', lint: false), - _AsCast('U', 'JSObject', lint: false), - _AsCast('T', 'JSUint8List'), - _AsCast('U', 'JSArray'), - _AsCast('JSAny', 'T', lint: false), - _AsCast('JSObject', 'U', lint: false), - _AsCast('JSUint8List', 'T'), - _AsCast('JSArray', 'U'), - _AsCast('T', 'A', lint: false), - _AsCast('T', 'B', lint: false), - _AsCast('U', 'A'), - _AsCast('U', 'B', lint: false), - _AsCast('A', 'T', lint: false), - _AsCast('A', 'U'), - _AsCast('B', 'T', lint: false), - _AsCast('B', 'U', lint: false), - _AsCast('T', 'U'), - _AsCast('U', 'T') - ], typeParameters: [ - 'T extends A', - 'U extends B' - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('T', 'JSAny', lint: false), + _AsCast('U', 'JSObject', lint: false), + _AsCast('T', 'JSUint8List'), + _AsCast('U', 'JSArray'), + _AsCast('JSAny', 'T', lint: false), + _AsCast('JSObject', 'U', lint: false), + _AsCast('JSUint8List', 'T'), + _AsCast('JSArray', 'U'), + _AsCast('T', 'A', lint: false), + _AsCast('T', 'B', lint: false), + _AsCast('U', 'A'), + _AsCast('U', 'B', lint: false), + _AsCast('A', 'T', lint: false), + _AsCast('A', 'U'), + _AsCast('B', 'T', lint: false), + _AsCast('B', 'U', lint: false), + _AsCast('T', 'U'), + _AsCast('U', 'T'), + ], + typeParameters: ['T extends A', 'U extends B'], + typeDeclarations: [ + r''' extension type A(JSTypedArray _) {} ''', - r''' + r''' @JS() @staticInterop class B {} - ''' - ]); + ''', + ], + ); } test_typeParametersIs_js_type_is_js_type_parameter() async { - await _testChecks([ - _IsCheck('JSAny', 'T'), - _IsCheck('JSObject', 'T'), - _IsCheck('JSBoolean', 'T'), - // This may or may not be an `is` check between unrelated types, so warn. - _IsCheck('JSArray', 'T') - ], typeParameters: [ - 'T extends JSObject' - ]); + await _testChecks( + [ + _IsCheck('JSAny', 'T'), + _IsCheck('JSObject', 'T'), + _IsCheck('JSBoolean', 'T'), + // This may or may not be an `is` check between unrelated types, so warn. + _IsCheck('JSArray', 'T'), + ], + typeParameters: ['T extends JSObject'], + ); } test_typeParametersIs_js_type_parameter_is_js_type() async { - await _testChecks([ - _IsCheck('T', 'JSAny', lint: false, unnecessary: true), - _IsCheck('T', 'JSObject', lint: false, unnecessary: true), - _IsCheck('T', 'JSBoolean'), - // This may or may not be an `is` check between unrelated types, so warn. - _IsCheck('T', 'JSUint8List') - ], typeParameters: [ - 'T extends JSObject' - ]); + await _testChecks( + [ + _IsCheck('T', 'JSAny', lint: false, unnecessary: true), + _IsCheck('T', 'JSObject', lint: false, unnecessary: true), + _IsCheck('T', 'JSBoolean'), + // This may or may not be an `is` check between unrelated types, so warn. + _IsCheck('T', 'JSUint8List'), + ], + typeParameters: ['T extends JSObject'], + ); } test_typeParametersIs_js_type_parameter_is_js_type_parameter() async { - await _testChecks([ - _IsCheck('T', 'T', lint: false, unnecessary: true), - _IsCheck('U', 'U', lint: false, unnecessary: true), - _IsCheck('V', 'V', lint: false, unnecessary: true), - _IsCheck('T', 'U'), - _IsCheck('U', 'T'), - _IsCheck('T', 'V'), - _IsCheck('V', 'T'), - _IsCheck('U', 'V'), - _IsCheck('V', 'U') - ], typeParameters: [ - 'T extends JSAny', - 'U extends JSArray', - 'V extends JSBoolean' - ]); + await _testChecks( + [ + _IsCheck('T', 'T', lint: false, unnecessary: true), + _IsCheck('U', 'U', lint: false, unnecessary: true), + _IsCheck('V', 'V', lint: false, unnecessary: true), + _IsCheck('T', 'U'), + _IsCheck('U', 'T'), + _IsCheck('T', 'V'), + _IsCheck('V', 'T'), + _IsCheck('U', 'V'), + _IsCheck('V', 'U'), + ], + typeParameters: [ + 'T extends JSAny', + 'U extends JSArray', + 'V extends JSBoolean', + ], + ); } test_typeParametersIs_nested_user_interop_type_parameter_is_user_interop_type() async { - await _testChecks([ - _IsCheck('T', 'A?', lint: false, unnecessary: true), - _IsCheck('U?', 'A'), - _IsCheck('V', 'A?', lint: false, unnecessary: true), - _IsCheck('W?', 'A'), - _IsCheck('X', 'A', lint: false), - _IsCheck('Y?', 'A') - ], typeParameters: [ - 'T extends A', - 'U extends B?', - 'V extends T', - 'W extends U', - 'X extends T?', - 'Y extends U?' - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('T', 'A?', lint: false, unnecessary: true), + _IsCheck('U?', 'A'), + _IsCheck('V', 'A?', lint: false, unnecessary: true), + _IsCheck('W?', 'A'), + _IsCheck('X', 'A', lint: false), + _IsCheck('Y?', 'A'), + ], + typeParameters: [ + 'T extends A', + 'U extends B?', + 'V extends T', + 'W extends U', + 'X extends T?', + 'Y extends U?', + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_typeParametersIs_unrelated_type_is_js_type_parameter() async { - await _testChecks([_IsCheck('String', 'T')], - typeParameters: ['T extends JSAny']); + await _testChecks( + [_IsCheck('String', 'T')], + typeParameters: ['T extends JSAny'], + ); } test_typeParametersIs_unrelated_type_parameter_is_js_type() async { - await _testChecks([_IsCheck('T', 'JSAny'), _IsCheck('U', 'JSNumber')], - typeParameters: ['T', 'U extends int']); + await _testChecks( + [_IsCheck('T', 'JSAny'), _IsCheck('U', 'JSNumber')], + typeParameters: ['T', 'U extends int'], + ); } test_typeParametersIs_user_interop_type_parameter_is() async { - await _testChecks([ - _IsCheck('T', 'JSAny', lint: false), - _IsCheck('U', 'JSObject', lint: false), - _IsCheck('T', 'JSUint8List'), - _IsCheck('U', 'JSArray'), - _IsCheck('JSAny', 'T'), - _IsCheck('JSObject', 'U'), - _IsCheck('JSUint8List', 'T'), - _IsCheck('JSArray', 'U'), - _IsCheck('T', 'A', lint: false, unnecessary: true), - _IsCheck('T', 'B'), - _IsCheck('U', 'A'), - _IsCheck('U', 'B', lint: false, unnecessary: true), - _IsCheck('A', 'T'), - _IsCheck('A', 'U'), - _IsCheck('B', 'T'), - _IsCheck('B', 'U'), - _IsCheck('T', 'U'), - _IsCheck('U', 'T') - ], typeParameters: [ - 'T extends A', - 'U extends B' - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('T', 'JSAny', lint: false), + _IsCheck('U', 'JSObject', lint: false), + _IsCheck('T', 'JSUint8List'), + _IsCheck('U', 'JSArray'), + _IsCheck('JSAny', 'T'), + _IsCheck('JSObject', 'U'), + _IsCheck('JSUint8List', 'T'), + _IsCheck('JSArray', 'U'), + _IsCheck('T', 'A', lint: false, unnecessary: true), + _IsCheck('T', 'B'), + _IsCheck('U', 'A'), + _IsCheck('U', 'B', lint: false, unnecessary: true), + _IsCheck('A', 'T'), + _IsCheck('A', 'U'), + _IsCheck('B', 'T'), + _IsCheck('B', 'U'), + _IsCheck('T', 'U'), + _IsCheck('U', 'T'), + ], + typeParameters: ['T extends A', 'U extends B'], + typeDeclarations: [ + r''' extension type A(JSTypedArray _) {} ''', - r''' + r''' @JS() @staticInterop class B {} - ''' - ]); + ''', + ], + ); } test_userInteropAs_js_type_as_user_interop_type() async { - await _testCasts([ - _AsCast('JSAny', 'A', lint: false), - _AsCast('JSObject', 'A', lint: false), - _AsCast('JSArray', 'A', lint: false), - _AsCast('JSBoolean', 'A') - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('JSAny', 'A', lint: false), + _AsCast('JSObject', 'A', lint: false), + _AsCast('JSArray', 'A', lint: false), + _AsCast('JSBoolean', 'A'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_userInteropAs_nested_user_interop_type_as_js_type() async { - await _testCasts([ - _AsCast('B', 'JSAny', lint: false), - _AsCast('B', 'JSObject', lint: false), - _AsCast('B', 'JSArray', lint: false), - _AsCast('B', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('B', 'JSAny', lint: false), + _AsCast('B', 'JSObject', lint: false), + _AsCast('B', 'JSArray', lint: false), + _AsCast('B', 'JSBoolean'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) implements JSObject {} ''', - r''' + r''' extension type B(A _) implements A {} - ''' - ]); + ''', + ], + ); } test_userInteropAs_user_interop_type_as_js_type() async { - await _testCasts([ - _AsCast('A', 'JSAny', lint: false), - _AsCast('A', 'JSObject', lint: false), - _AsCast('A', 'JSArray', lint: false), - _AsCast('A', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('A', 'JSAny', lint: false), + _AsCast('A', 'JSObject', lint: false), + _AsCast('A', 'JSArray', lint: false), + _AsCast('A', 'JSBoolean'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_userInteropAs_user_interop_type_as_user_interop_type() async { - await _testCasts([ - _AsCast('A', 'A', lint: false, unnecessary: true), - _AsCast('A', 'B', lint: false), - _AsCast('A', 'C'), - _AsCast('B', 'A', lint: false), - _AsCast('B', 'B', lint: false, unnecessary: true), - _AsCast('B', 'C'), - _AsCast('C', 'A'), - _AsCast('C', 'B'), - _AsCast('C', 'C', lint: false, unnecessary: true) - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('A', 'A', lint: false, unnecessary: true), + _AsCast('A', 'B', lint: false), + _AsCast('A', 'C'), + _AsCast('B', 'A', lint: false), + _AsCast('B', 'B', lint: false, unnecessary: true), + _AsCast('B', 'C'), + _AsCast('C', 'A'), + _AsCast('C', 'B'), + _AsCast('C', 'C', lint: false, unnecessary: true), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) implements A {} ''', - r''' + r''' extension type C(JSBoolean _) {} - ''' - ]); + ''', + ], + ); } // Since A is an unrelated type, we warn users so they don't think a runtime // check is done to ensure the value actually is an A. test_userInteropIs_js_type_is_user_interop_type() async { - await _testChecks([ - _IsCheck('JSAny', 'A'), - _IsCheck('JSObject', 'A'), - _IsCheck('JSArray', 'A'), - _IsCheck('JSBoolean', 'A') - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('JSAny', 'A'), + _IsCheck('JSObject', 'A'), + _IsCheck('JSArray', 'A'), + _IsCheck('JSBoolean', 'A'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_userInteropIs_nested_user_interop_type_is_js_type() async { - await _testChecks([ - _IsCheck('B', 'JSAny', lint: false, unnecessary: true), - _IsCheck('B', 'JSObject', lint: false, unnecessary: true), - _IsCheck('B', 'JSArray'), - _IsCheck('B', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('B', 'JSAny', lint: false, unnecessary: true), + _IsCheck('B', 'JSObject', lint: false, unnecessary: true), + _IsCheck('B', 'JSArray'), + _IsCheck('B', 'JSBoolean'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) implements JSObject {} ''', - r''' + r''' extension type B(A _) implements A {} - ''' - ]); + ''', + ], + ); } test_userInteropIs_user_interop_type_is_js_type() async { - await _testChecks([ - _IsCheck('A', 'JSAny', lint: false), - _IsCheck('A', 'JSObject', lint: false), - _IsCheck('A', 'JSArray'), - _IsCheck('A', 'JSBoolean') - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('A', 'JSAny', lint: false), + _IsCheck('A', 'JSObject', lint: false), + _IsCheck('A', 'JSArray'), + _IsCheck('A', 'JSBoolean'), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} - ''' - ]); + ''', + ], + ); } test_userInteropIs_user_interop_type_is_user_interop_type() async { - await _testChecks([ - _IsCheck('A', 'A', lint: false, unnecessary: true), - _IsCheck('A', 'B'), - _IsCheck('A', 'C'), - _IsCheck('B', 'A', lint: false, unnecessary: true), - _IsCheck('B', 'B', lint: false, unnecessary: true), - _IsCheck('B', 'C'), - _IsCheck('C', 'A'), - _IsCheck('C', 'B'), - _IsCheck('C', 'C', lint: false, unnecessary: true) - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('A', 'A', lint: false, unnecessary: true), + _IsCheck('A', 'B'), + _IsCheck('A', 'C'), + _IsCheck('B', 'A', lint: false, unnecessary: true), + _IsCheck('B', 'B', lint: false, unnecessary: true), + _IsCheck('B', 'C'), + _IsCheck('C', 'A'), + _IsCheck('C', 'B'), + _IsCheck('C', 'C', lint: false, unnecessary: true), + ], + typeDeclarations: [ + r''' extension type A(JSObject _) {} ''', - r''' + r''' extension type B(JSObject _) implements A {} ''', - r''' + r''' extension type C(JSBoolean _) {} - ''' - ]); + ''', + ], + ); } test_wasmIncompatibleTypesAs_dart_html_type_as_js_type() async { await _testCasts([ _AsCast('Event', 'JSAny', lint: false), _AsCast('Event', 'JSString', lint: false), - _AsCast('Event', 'JSObject', lint: false) + _AsCast('Event', 'JSObject', lint: false), ]); } @@ -927,7 +1076,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { test_wasmIncompatibleTypesAs_js_type_as_dart_html_type() async { await _testCasts([ _AsCast('JSString', 'Event', lint: false), - _AsCast('JSString', 'Window', lint: false) + _AsCast('JSString', 'Window', lint: false), ]); } @@ -936,62 +1085,68 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_wasmIncompatibleTypesAs_js_type_as_package_js_type() async { - await _testCasts([ - _AsCast('JSAny', 'A', lint: false), - _AsCast('JSString', 'B', lint: false) - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('JSAny', 'A', lint: false), + _AsCast('JSString', 'B', lint: false), + ], + typeDeclarations: [ + r''' @js.JS() class A {} ''', - r''' + r''' @js.JS() @js.staticInterop - class B {}''' - ]); + class B {}''', + ], + ); } test_wasmIncompatibleTypesAs_js_type_parameter_as() async { - await _testCasts([ - _AsCast('T', 'JSAny', lint: false), - _AsCast('U', 'JSObject', lint: false), - _AsCast('V', 'JSArray', lint: false), - _AsCast('JSString', 'T', lint: false), - _AsCast('JSString', 'U', lint: false), - _AsCast('JSString', 'V', lint: false) - ], typeParameters: [ - 'T extends A', - 'U extends Event', - 'V extends JsObject' - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('T', 'JSAny', lint: false), + _AsCast('U', 'JSObject', lint: false), + _AsCast('V', 'JSArray', lint: false), + _AsCast('JSString', 'T', lint: false), + _AsCast('JSString', 'U', lint: false), + _AsCast('JSString', 'V', lint: false), + ], + typeParameters: ['T extends A', 'U extends Event', 'V extends JsObject'], + typeDeclarations: [ + r''' @js.JS() class A {} - ''' - ]); + ''', + ], + ); } test_wasmIncompatibleTypesAs_package_js_type_as_js_type() async { - await _testCasts([ - _AsCast('A', 'JSBoolean', lint: false), - _AsCast('B', 'JSString', lint: false) - ], typeDeclarations: [ - r''' + await _testCasts( + [ + _AsCast('A', 'JSBoolean', lint: false), + _AsCast('B', 'JSString', lint: false), + ], + typeDeclarations: [ + r''' @js.JS() class A {} ''', - r''' + r''' @js.JS() @js.staticInterop - class B {}''' - ]); + class B {}''', + ], + ); } test_wasmIncompatibleTypesIs_dart_html_type_is_js_type() async { await _testChecks([ _IsCheck('Event', 'JSAny', lint: false), _IsCheck('Event', 'JSString', lint: false), - _IsCheck('Event', 'JSObject', lint: false) + _IsCheck('Event', 'JSObject', lint: false), ]); } @@ -1002,7 +1157,7 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { test_wasmIncompatibleTypesIs_js_type_is_dart_html_type() async { await _testChecks([ _IsCheck('JSString', 'Event', lint: false), - _IsCheck('JSString', 'Window', lint: false) + _IsCheck('JSString', 'Window', lint: false), ]); } @@ -1011,55 +1166,61 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { } test_wasmIncompatibleTypesIs_js_type_is_package_js_type() async { - await _testChecks([ - _IsCheck('JSAny', 'A', lint: false), - _IsCheck('JSString', 'B', lint: false) - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('JSAny', 'A', lint: false), + _IsCheck('JSString', 'B', lint: false), + ], + typeDeclarations: [ + r''' @js.JS() class A {} ''', - r''' + r''' @js.JS() @js.staticInterop - class B {}''' - ]); + class B {}''', + ], + ); } test_wasmIncompatibleTypesIs_js_type_parameter_is() async { - await _testChecks([ - _IsCheck('T', 'JSAny', lint: false), - _IsCheck('U', 'JSObject', lint: false), - _IsCheck('V', 'JSArray', lint: false), - _IsCheck('JSString', 'T', lint: false), - _IsCheck('JSString', 'U', lint: false), - _IsCheck('JSString', 'V', lint: false) - ], typeParameters: [ - 'T extends A', - 'U extends Event', - 'V extends JsObject' - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('T', 'JSAny', lint: false), + _IsCheck('U', 'JSObject', lint: false), + _IsCheck('V', 'JSArray', lint: false), + _IsCheck('JSString', 'T', lint: false), + _IsCheck('JSString', 'U', lint: false), + _IsCheck('JSString', 'V', lint: false), + ], + typeParameters: ['T extends A', 'U extends Event', 'V extends JsObject'], + typeDeclarations: [ + r''' @js.JS() class A {} - ''' - ]); + ''', + ], + ); } test_wasmIncompatibleTypesIs_package_js_type_is_js_type() async { - await _testChecks([ - _IsCheck('A', 'JSBoolean', lint: false), - _IsCheck('B', 'JSString', lint: false) - ], typeDeclarations: [ - r''' + await _testChecks( + [ + _IsCheck('A', 'JSBoolean', lint: false), + _IsCheck('B', 'JSString', lint: false), + ], + typeDeclarations: [ + r''' @js.JS() class A {} ''', - r''' + r''' @js.JS() @js.staticInterop - class B {}''' - ]); + class B {}''', + ], + ); } /// Given a list of JS interop [typeTests], constructs code to execute a type @@ -1073,16 +1234,19 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { /// executing the tests. /// /// If [cast] is true, uses `as` for the type test. Otherwise, uses `is`. - Future _assertDiagnosticsWithTypeTests(List<_TypeTest> typeTests, - {required List typeParameters, - required List typeDeclarations, - required bool cast}) { + Future _assertDiagnosticsWithTypeTests( + List<_TypeTest> typeTests, { + required List typeParameters, + required List typeDeclarations, + required bool cast, + }) { var lints = []; - var code = - StringBuffer("// ignore: unused_import\nimport 'dart:html' hide JS;\n" - "// ignore: unused_import\nimport 'dart:js';\n" - "// ignore: unused_import\nimport 'dart:js_interop';\n" - "// ignore: unused_import\nimport 'package:js/js.dart' as js;\n"); + var code = StringBuffer( + "// ignore: unused_import\nimport 'dart:html' hide JS;\n" + "// ignore: unused_import\nimport 'dart:js';\n" + "// ignore: unused_import\nimport 'dart:js_interop';\n" + "// ignore: unused_import\nimport 'package:js/js.dart' as js;\n", + ); for (var typeDeclaration in typeDeclarations) { code.write('$typeDeclaration\n'); } @@ -1101,10 +1265,16 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { if (typeTest.unnecessary) { if (cast) { lints.add( - error(WarningCode.UNNECESSARY_CAST, code.length, test.length)); + error(WarningCode.UNNECESSARY_CAST, code.length, test.length), + ); } else { - lints.add(error(WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, code.length, - test.length)); + lints.add( + error( + WarningCode.UNNECESSARY_TYPE_CHECK_TRUE, + code.length, + test.length, + ), + ); } } code.write('$test;\n'); @@ -1113,21 +1283,27 @@ class InvalidRuntimeCheckWithJSInteropTypesTest extends LintRuleTest { return assertDiagnostics(code.toString(), lints); } - Future _testCasts(List<_AsCast> typeTests, - {List typeParameters = const [], - List typeDeclarations = const []}) => - _assertDiagnosticsWithTypeTests(typeTests, - typeParameters: typeParameters, - typeDeclarations: typeDeclarations, - cast: true); - - Future _testChecks(List<_IsCheck> typeTests, - {List typeParameters = const [], - List typeDeclarations = const []}) => - _assertDiagnosticsWithTypeTests(typeTests, - typeDeclarations: typeDeclarations, - typeParameters: typeParameters, - cast: false); + Future _testCasts( + List<_AsCast> typeTests, { + List typeParameters = const [], + List typeDeclarations = const [], + }) => _assertDiagnosticsWithTypeTests( + typeTests, + typeParameters: typeParameters, + typeDeclarations: typeDeclarations, + cast: true, + ); + + Future _testChecks( + List<_IsCheck> typeTests, { + List typeParameters = const [], + List typeDeclarations = const [], + }) => _assertDiagnosticsWithTypeTests( + typeTests, + typeDeclarations: typeDeclarations, + typeParameters: typeParameters, + cast: false, + ); } /// Represents an `as` cast from a value of type [valueType] to [type]. @@ -1153,6 +1329,10 @@ abstract class _TypeTest { /// test should ignore the related warning. bool unnecessary; - _TypeTest(this.valueType, this.type, - {this.lint = true, this.unnecessary = false}); + _TypeTest( + this.valueType, + this.type, { + this.lint = true, + this.unnecessary = false, + }); } diff --git a/pkg/linter/test/rules/join_return_with_assignment_test.dart b/pkg/linter/test/rules/join_return_with_assignment_test.dart index e47b980733bf..fd367edd0c4b 100644 --- a/pkg/linter/test/rules/join_return_with_assignment_test.dart +++ b/pkg/linter/test/rules/join_return_with_assignment_test.dart @@ -18,7 +18,8 @@ class JoinReturnWithAssignmentTest extends LintRuleTest { String get lintRule => LintNames.join_return_with_assignment; test_class_field_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int f = 0; } @@ -27,13 +28,14 @@ int f(A a) { a.f = 0; return a.f; } -''', [ - lint(41, 8), - ]); +''', + [lint(41, 8)], + ); } test_class_field_propertyAccess_nested() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int f = 0; } @@ -46,9 +48,9 @@ int f(B b) { b.a.f = 0; return b.a.f; } -''', [ - lint(67, 10), - ]); +''', + [lint(67, 10)], + ); } test_class_field_propertyAccess_nested_notSame() async { @@ -82,7 +84,8 @@ int f(A a1, A a2) { } test_class_field_withoutPrefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int? _a; int? foo() { @@ -90,13 +93,14 @@ class A { return _a; } } -''', [ - lint(40, 9), - ]); +''', + [lint(40, 9)], + ); } test_class_field_withoutPrefix_ifThenElse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int? _a; int? foo(bool b) { @@ -109,32 +113,33 @@ class A { } } } -''', [ - lint(61, 7), - lint(105, 7), - ]); +''', + [lint(61, 7), lint(105, 7)], + ); } test_localVariable_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int f(int a) { a = 0; return a; } -''', [ - lint(17, 6), - ]); +''', + [lint(17, 6)], + ); } test_localVariable_assignment_compound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int f(int a) { a += 0; return a; } -''', [ - lint(17, 7), - ]); +''', + [lint(17, 7)], + ); } @failingTest @@ -172,25 +177,27 @@ int f(int a) { } test_localVariable_postfix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int f(int a) { a++; return a; } -''', [ - lint(17, 4), - ]); +''', + [lint(17, 4)], + ); } test_localVariable_prefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int f(int a) { ++a; return a; } -''', [ - lint(17, 4), - ]); +''', + [lint(17, 4)], + ); } test_patternAssignment_multiple() async { diff --git a/pkg/linter/test/rules/leading_newlines_in_multiline_strings_test.dart b/pkg/linter/test/rules/leading_newlines_in_multiline_strings_test.dart index 0a61d3428a65..ad6c2ef800b4 100644 --- a/pkg/linter/test/rules/leading_newlines_in_multiline_strings_test.dart +++ b/pkg/linter/test/rules/leading_newlines_in_multiline_strings_test.dart @@ -65,21 +65,23 @@ var x = '''this is a multiline string $a'''; } test_textBeforeNewline() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var x = '''this is a multiline string'''; -""", [ - lint(8, 33), - ]); +""", + [lint(8, 33)], + ); } test_textBeforeNewline_withInterpolation() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var a = 'a'; var x = '''this is a multiline string$a'''; -""", [ - lint(21, 35), - ]); +""", + [lint(21, 35)], + ); } } diff --git a/pkg/linter/test/rules/library_annotations_test.dart b/pkg/linter/test/rules/library_annotations_test.dart index 86560980df37..055c091dbcdd 100644 --- a/pkg/linter/test/rules/library_annotations_test.dart +++ b/pkg/linter/test/rules/library_annotations_test.dart @@ -85,8 +85,7 @@ void f() {} test_functionDeclaration_annotationWithTargetKindLibrary() async { // In this library, `invalid_annotation_target` is reported (and // suppressed), so we do not also report `library_annotations`. - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' import 'package:meta/meta_meta.dart'; @Target({TargetKind.library}) @@ -97,8 +96,7 @@ class TestOn { // ignore: invalid_annotation_target @TestOn('browser') class C {} -''', - ); +'''); } test_genericTypedefDeclaration() async { @@ -152,15 +150,16 @@ mixin M {} part of 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @pragma('dart2js:late:trust') part 'part.dart'; class C {} -''', [ - lint(0, 29), - ]); +''', + [lint(0, 29)], + ); } test_partOfFile() async { diff --git a/pkg/linter/test/rules/library_names_test.dart b/pkg/linter/test/rules/library_names_test.dart index f0365e3ec98d..bb139ddce979 100644 --- a/pkg/linter/test/rules/library_names_test.dart +++ b/pkg/linter/test/rules/library_names_test.dart @@ -35,18 +35,20 @@ library foo; } test_titlecase() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' library Foo; -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_uppercaseInDots() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' library one.Two.three; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } } diff --git a/pkg/linter/test/rules/library_prefixes_test.dart b/pkg/linter/test/rules/library_prefixes_test.dart index de00e1b3aae6..4102fa4aa8a5 100644 --- a/pkg/linter/test/rules/library_prefixes_test.dart +++ b/pkg/linter/test/rules/library_prefixes_test.dart @@ -16,18 +16,21 @@ main() { @reflectiveTest class LibraryPrefixesTest extends LintRuleTest { @override - List get ignoredErrorCodes => - [WarningCode.UNUSED_IMPORT, WarningCode.UNUSED_LOCAL_VARIABLE]; + List get ignoredErrorCodes => [ + WarningCode.UNUSED_IMPORT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.library_prefixes; test_camelCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async' as dartAsync; -''', [ - lint(23, 9), - ]); +''', + [lint(23, 9)], + ); } test_leadingDollar() async { @@ -49,11 +52,12 @@ import 'dart:async' as _i1; } test_numberWithLeadingUnderscore() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async' as _1; -''', [ - lint(23, 2), - ]); +''', + [lint(23, 2)], + ); } test_wildcard() async { @@ -63,13 +67,14 @@ import 'dart:async' as _; } test_wildcard_preWildCards() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // @dart = 3.4 // (pre wildcard-variables) import 'dart:async' as _; -''', [ - lint(67, 1), - ]); +''', + [lint(67, 1)], + ); } } diff --git a/pkg/linter/test/rules/library_private_types_in_public_api_test.dart b/pkg/linter/test/rules/library_private_types_in_public_api_test.dart index 25eba0191e39..6b7f8e540afa 100644 --- a/pkg/linter/test/rules/library_private_types_in_public_api_test.dart +++ b/pkg/linter/test/rules/library_private_types_in_public_api_test.dart @@ -20,10 +20,10 @@ main() { class LibraryPrivateTypesInPublicApiEnumTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + ]; @override String get lintRule => LintNames.library_private_types_in_public_api; @@ -53,7 +53,8 @@ abstract interface class E { } test_enum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _O {} enum E { a, b, c; @@ -61,11 +62,9 @@ enum E { void oo(_O o) { } _O get ooo => o; } -''', [ - lint(40, 2), - lint(63, 2), - lint(75, 2), - ]); +''', + [lint(40, 2), lint(63, 2), lint(75, 2)], + ); } /// https://github.com/dart-lang/linter/issues/4470 @@ -98,32 +97,34 @@ sealed class E { class LibraryPrivateTypesInPublicApiExtensionTypeTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + ]; @override String get lintRule => LintNames.library_private_types_in_public_api; test_constructorParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { E.e(_C c) : o = c; } -''', [ - lint(47, 2), - ]); +''', + [lint(47, 2)], + ); } test_extensionTypeDeclaration_representation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(_C c) {} -''', [ - lint(29, 2), - ]); +''', + [lint(29, 2)], + ); } test_extensionTypeDeclaration_representation_private() async { @@ -134,46 +135,56 @@ extension type E(_C _c) {} } test_extensionTypeDeclaration_typeParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) {} -''', [ - lint(39, 2), - ]); +''', + [lint(39, 2)], + ); } test_field_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { _C? c; } -''', [ - // No lint. - error(CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, 47, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, + 47, + 1, + ), + ], + ); } test_field_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { static _C? c; } -''', [ - lint(50, 2), - ]); +''', + [lint(50, 2)], + ); } test_method_instance_param() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { m(_C c){} } -''', [ - lint(45, 2), - ]); +''', + [lint(45, 2)], + ); } test_method_instance_private_param() async { @@ -186,25 +197,27 @@ extension type E(Object o) { } test_method_instance_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { _C? m() => null; } -''', [ - lint(43, 2), - ]); +''', + [lint(43, 2)], + ); } test_method_static_param() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { static m(_C c){} } -''', [ - lint(52, 2), - ]); +''', + [lint(52, 2)], + ); } test_method_static_private_returnType() async { @@ -217,14 +230,15 @@ extension type E(Object o) { } test_method_static_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _C {} extension type E(Object o) { static _C? m() => null; } -''', [ - lint(50, 2), - ]); +''', + [lint(50, 2)], + ); } } @@ -232,16 +246,17 @@ extension type E(Object o) { class LibraryPrivateTypesInPublicApiSuperParamTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + ]; @override String get lintRule => LintNames.library_private_types_in_public_api; test_implicitTypeFieldFormalParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _O {} class C { _O _x; @@ -250,13 +265,14 @@ class C { Object get x => _x; } -''', [ - lint(41, 2), - ]); +''', + [lint(41, 2)], + ); } test_implicitTypeSuperFormalParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _O extends Object {} class _A { _A(_O o); @@ -264,13 +280,14 @@ class _A { class B extends _A { B(super.o); } -''', [ - lint(83, 1), - ]); +''', + [lint(83, 1)], + ); } test_recursiveInterfaceInheritance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _O extends Object {} class A { Object o; @@ -280,9 +297,9 @@ class A { class B extends A { B(_O super.o); } -''', [ - lint(89, 2), - ]); +''', + [lint(89, 2)], + ); } } @@ -290,10 +307,10 @@ class B extends A { class LibraryPrivateTypesInPublicApiTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + ]; @override String get lintRule => LintNames.library_private_types_in_public_api; @@ -330,34 +347,37 @@ class _P {} } test_constructor_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.named(_P p); } class _P {} -''', [ - lint(20, 2), - ]); +''', + [lint(20, 2)], + ); } test_constructor_unnamed_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(_P p); } class _P {} -''', [ - lint(14, 2), - ]); +''', + [lint(14, 2)], + ); } test_extension_onPrivateType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on _P {} class _P {} -''', [ - lint(15, 2), - ]); +''', + [lint(15, 2)], + ); } test_function_private_privateTypes() async { @@ -368,21 +388,23 @@ class _P {} } test_function_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String f(_P p) => ''; class _P {} -''', [ - lint(9, 2), - ]); +''', + [lint(9, 2)], + ); } test_function_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' _P f2(int i) => _P(); class _P {} -''', [ - lint(0, 2), - ]); +''', + [lint(0, 2)], + ); } test_function_publicTypes() async { @@ -410,25 +432,27 @@ class _P {} } test_instanceField_privateType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { _P f = _P(); } class _P {} -''', [ - lint(12, 2), - ]); +''', + [lint(12, 2)], + ); } test_instanceField_privateTypeTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { List<_P> f = []; } class _P {} -''', [ - lint(17, 2), - ]); +''', + [lint(17, 2)], + ); } test_instanceGetter_private_privateReturnType() async { @@ -441,14 +465,15 @@ class _P {} } test_instanceGetter_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { _P get g2 => _P(); } class _P {} -''', [ - lint(12, 2), - ]); +''', + [lint(12, 2)], + ); } test_instanceMethod_private_privateReturnType() async { @@ -470,25 +495,27 @@ class _P {} } test_instanceMethod_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String m(_P p) => ''; } class _P {} -''', [ - lint(21, 2), - ]); +''', + [lint(21, 2)], + ); } test_instanceMethod_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { _P m(int i) => _P(); } class _P {} -''', [ - lint(12, 2), - ]); +''', + [lint(12, 2)], + ); } test_instanceMethod_pulicTypes() async { @@ -509,14 +536,15 @@ class _P {} } test_instanceSetter_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { set s(_P i) {} } class _P {} -''', [ - lint(18, 2), - ]); +''', + [lint(18, 2)], + ); } test_mixin_implementsPrivateType() async { @@ -527,12 +555,13 @@ class _P {} } test_mixin_onPrivateType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M on _P {} class _P {} -''', [ - lint(11, 2), - ]); +''', + [lint(11, 2)], + ); } test_mixin_private_onPrivateType() async { @@ -543,25 +572,27 @@ class _P {} } test_operator_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int operator+(_P p) => 0; } class _P {} -''', [ - lint(26, 2), - ]); +''', + [lint(26, 2)], + ); } test_operator_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { _P operator-(int i) => _P(); } class _P {} -''', [ - lint(12, 2), - ]); +''', + [lint(12, 2)], + ); } test_topLevelGetter_private_privateReturnType() async { @@ -572,12 +603,13 @@ class _P {} } test_topLevelGetter_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' _P get g => _P(); class _P {} -''', [ - lint(0, 2), - ]); +''', + [lint(0, 2)], + ); } test_topLevelSetter_private_privateParameterType() async { @@ -588,12 +620,13 @@ class _P {} } test_topLevelSetter_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' set s(_P i) {} class _P {} -''', [ - lint(6, 2), - ]); +''', + [lint(6, 2)], + ); } test_topLevelVariable_private_privateType() async { @@ -604,21 +637,23 @@ class _P {} } test_topLevelVariable_privateType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' _P? v; class _P {} -''', [ - lint(0, 2), - ]); +''', + [lint(0, 2)], + ); } test_topLevelVariable_privateTypeTypeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List<_P> v = []; class _P {} -''', [ - lint(5, 2), - ]); +''', + [lint(5, 2)], + ); } test_topLevelVariable_publicType() async { @@ -628,39 +663,43 @@ String v = ''; } test_typedef_legacy_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef void F(_P p); class _P {} -''', [ - lint(15, 2), - ]); +''', + [lint(15, 2)], + ); } test_typedef_legacy_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef _P F(); class _P {} -''', [ - lint(8, 2), - ]); +''', + [lint(8, 2)], + ); } test_typedef_privateParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef F = void Function(_P); class _P {} -''', [ - lint(26, 2), - ]); +''', + [lint(26, 2)], + ); } test_typedef_privateReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef F = _P Function(); class _P {} -''', [ - lint(12, 2), - ]); +''', + [lint(12, 2)], + ); } test_typedef_publicParameterType() async { diff --git a/pkg/linter/test/rules/lines_longer_than_80_chars_test.dart b/pkg/linter/test/rules/lines_longer_than_80_chars_test.dart index 18404bd60718..d1dec2274bfd 100644 --- a/pkg/linter/test/rules/lines_longer_than_80_chars_test.dart +++ b/pkg/linter/test/rules/lines_longer_than_80_chars_test.dart @@ -34,9 +34,7 @@ class LinesLongerThan80CharsTest extends LintRuleTest { await assertDiagnostics( '/* 5 10 15 20 25 30 35 40 50 55 60' ' 65 70 75 80 85 90 95 100 */', - [ - lint(80, 18), - ], + [lint(80, 18)], ); } @@ -57,9 +55,7 @@ class LinesLongerThan80CharsTest extends LintRuleTest { await assertDiagnostics( '/// 5 10 15 20 25 30 35 40 50 55 60' ' 65 70 75 80 85 90 95 100', - [ - lint(80, 15), - ], + [lint(80, 15)], ); } @@ -80,9 +76,7 @@ class LinesLongerThan80CharsTest extends LintRuleTest { await assertDiagnostics( '// 5 10 15 20 25 30 35 40 50 55 60' ' 65 70 75 80 85 90 95 100', - [ - lint(80, 15), - ], + [lint(80, 15)], ); } @@ -101,12 +95,13 @@ var p = } test_longerThan80Characters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var p = ' '; -''', [ - lint(88, 1), - ]); +''', + [lint(88, 1)], + ); } test_multilineBlockComment_noSpaceAfter80() async { @@ -141,9 +136,7 @@ var p = ' * 5 10 15 20 25 30 35 40 50 55 60' ' 65 70 75 80 85 90 95 100\n' ' */', - [ - lint(83, 15), - ], + [lint(83, 15)], ); } diff --git a/pkg/linter/test/rules/literal_only_boolean_expressions_test.dart b/pkg/linter/test/rules/literal_only_boolean_expressions_test.dart index 149769f1c82e..6f8a08a937e9 100644 --- a/pkg/linter/test/rules/literal_only_boolean_expressions_test.dart +++ b/pkg/linter/test/rules/literal_only_boolean_expressions_test.dart @@ -18,44 +18,47 @@ class LiteralOnlyBooleanExpressionsTest extends LintRuleTest { String get lintRule => LintNames.literal_only_boolean_expressions; test_doWhile_false() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do {} while (false); } -''', [ - lint(13, 20), - ]); +''', + [lint(13, 20)], + ); } test_for_trueCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (; true; ) {} } -''', [ - lint(13, 17), - ]); +''', + [lint(13, 17)], + ); } test_if_andTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 != 0 && true) {} } -''', [ - lint(13, 22), - ]); +''', + [lint(13, 22)], + ); } test_if_notTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (!true) {} } -''', [ - lint(13, 13), - error(WarningCode.DEAD_CODE, 24, 2), - ]); +''', + [lint(13, 13), error(WarningCode.DEAD_CODE, 24, 2)], + ); } test_if_nullAware_notEqual() async { @@ -67,77 +70,85 @@ void f(String? text) { } test_if_or_thenAndTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 != 0 || 3 < 4 && true) {} } -''', [ - lint(13, 31), - ]); +''', + [lint(13, 31)], + ); } test_if_true() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (true) {} } -''', [ - lint(13, 12), - ]); +''', + [lint(13, 12)], + ); } test_if_trueAnd() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (true && 1 != 0) {} } -''', [ - lint(13, 22), - ]); +''', + [lint(13, 22)], + ); } test_if_trueAnd_thenOr() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (true && 1 != 0 || 3 < 4) {} } -''', [ - lint(13, 31), - ]); +''', + [lint(13, 31)], + ); } test_if_trueAndFalse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void bad() { if (true && false) {} } -''', [ - lint(15, 21), - error(WarningCode.DEAD_CODE, 34, 2), - ]); +''', + [lint(15, 21), error(WarningCode.DEAD_CODE, 34, 2)], + ); } test_if_x() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 != 0) {} } -''', [ - lint(13, 14), - ]); +''', + [lint(13, 14)], + ); } test_ifCase_intLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 case {1:0}) { print(''); } } -''', [ - // No lint - error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 24, 5), - ]); +''', + [ + // No lint + error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 24, 5), + ], + ); } test_ifCase_listLiteral() async { @@ -187,13 +198,14 @@ void f() { } test_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool p) { if (null ?? p) {} } -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_switchExpression() async { @@ -209,27 +221,27 @@ bool f(Object o) => switch(o) { } test_whenClause() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { switch (1) { case [int a] when true: print(a); } } -''', [ - error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 35, 7), - lint(43, 9), - ]); +''', + [error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 35, 7), lint(43, 9)], + ); } test_while_notTrue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { while (!true) {} } -''', [ - lint(13, 16), - error(WarningCode.DEAD_CODE, 27, 2), - ]); +''', + [lint(13, 16), error(WarningCode.DEAD_CODE, 27, 2)], + ); } test_whileTrue() async { diff --git a/pkg/linter/test/rules/matching_super_parameters_test.dart b/pkg/linter/test/rules/matching_super_parameters_test.dart index b5be0f33b4d3..fdadb8f3c8ff 100644 --- a/pkg/linter/test/rules/matching_super_parameters_test.dart +++ b/pkg/linter/test/rules/matching_super_parameters_test.dart @@ -84,7 +84,8 @@ class C { } test_explicitSuperInvocation_nonMatching() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class D extends C { final String w; @@ -101,10 +102,9 @@ class C { C.named(this.x, this.y); } -''', [ - lint(60, 7), - lint(73, 7), - ]); +''', + [lint(60, 7), lint(73, 7)], + ); } test_implicitSuperInvocation_matchingWithGap() async { @@ -150,7 +150,8 @@ class C { } test_implicitSuperInvocation_nonMatching() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class D extends C { final String w; @@ -167,14 +168,14 @@ class C { C(this.x, this.y); } -''', [ - lint(60, 7), - lint(73, 7), - ]); +''', + [lint(60, 7), lint(73, 7)], + ); } test_implicitSuperInvocation_nonMatching_omittedOptional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class D extends C { final String w; @@ -190,13 +191,14 @@ class C { C(this.x, [this.y]); } -''', [ - lint(60, 7), - ]); +''', + [lint(60, 7)], + ); } test_implicitSuperInvocation_nonMatching_tooMany() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class D extends C { final String w; @@ -212,13 +214,16 @@ class C { C(this.x); } -''', [ - // No lint. - error( +''', + [ + // No lint. + error( CompileTimeErrorCode .SUPER_FORMAL_PARAMETER_WITHOUT_ASSOCIATED_POSITIONAL, 79, - 1), - ]); + 1, + ), + ], + ); } } diff --git a/pkg/linter/test/rules/missing_code_block_language_in_doc_comment_test.dart b/pkg/linter/test/rules/missing_code_block_language_in_doc_comment_test.dart index 7ab6406d96d4..ba3ca9ccbc1f 100644 --- a/pkg/linter/test/rules/missing_code_block_language_in_doc_comment_test.dart +++ b/pkg/linter/test/rules/missing_code_block_language_in_doc_comment_test.dart @@ -56,35 +56,38 @@ class A {} } test_missingLanguage() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// ``` /// test /// ``` class A {} -''', [ - lint(3, 4), - ]); +''', + [lint(3, 4)], + ); } test_missingLanguage_leadingWhitespace() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// ``` /// test /// ``` class A {} -''', [ - lint(3, 6), - ]); +''', + [lint(3, 6)], + ); } test_missingLanguage_noEndingFence() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// ``` /// test /// more test class A {} -''', [ - lint(3, 4), - ]); +''', + [lint(3, 4)], + ); } } diff --git a/pkg/linter/test/rules/missing_whitespace_between_adjacent_strings_test.dart b/pkg/linter/test/rules/missing_whitespace_between_adjacent_strings_test.dart index 39a055997e6e..d6dc0558cad4 100644 --- a/pkg/linter/test/rules/missing_whitespace_between_adjacent_strings_test.dart +++ b/pkg/linter/test/rules/missing_whitespace_between_adjacent_strings_test.dart @@ -31,14 +31,17 @@ var x = RegExp('(\n)+' '(\n)+' '(\n)+'); } test_extraPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { new Unresolved('aaa' 'bbb'); } -''', [ - // No lint - error(CompileTimeErrorCode.NEW_WITH_NON_TYPE, 17, 10), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.NEW_WITH_NON_TYPE, 17, 10), + ], + ); } test_firstPartEndsWithCarriageReturn() async { @@ -98,20 +101,22 @@ var x = 'longLineWithoutSpaceCouldBe' 'AnURL'; } test_noSpacesBetweenStringParts() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 'long line' 'is long'; -''', [ - lint(8, 11), - ]); +''', + [lint(8, 11)], + ); } test_noSpacesBetweenStringParts_leftHasInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = 1; var x = 'long $f line' 'is long'; -''', [ - lint(19, 14), - ]); +''', + [lint(19, 14)], + ); } test_rightPartStartsWithInterpolation() async { diff --git a/pkg/linter/test/rules/no_adjacent_strings_in_list_test.dart b/pkg/linter/test/rules/no_adjacent_strings_in_list_test.dart index 0331a7233250..a1be930efaab 100644 --- a/pkg/linter/test/rules/no_adjacent_strings_in_list_test.dart +++ b/pkg/linter/test/rules/no_adjacent_strings_in_list_test.dart @@ -18,48 +18,52 @@ class NoAdjacentStringsInListTest extends LintRuleTest { String get lintRule => LintNames.no_adjacent_strings_in_list; test_adjacentStrings_three() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = [ 'a' 'b' 'c' ]; -''', [ - lint(15, 15), - ]); +''', + [lint(15, 15)], + ); } test_forElement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = [ for (var v in []) 'a' 'b' ]; -''', [ - lint(33, 9), - ]); +''', + [lint(33, 9)], + ); } test_ifElement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = [ if (1 == 2) 'a' 'b' ]; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } test_ifElementWithElse_inElse() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = [ if (1 == 2) 'a' else 'b' 'c' ]; -''', [ - lint(38, 7), - ]); +''', + [lint(38, 7)], + ); } test_ifElementWithElse_inThen() async { @@ -73,15 +77,16 @@ var list = [ } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = [ 'a' 'b', 'c', ]; -''', [ - lint(15, 9), - ]); +''', + [lint(15, 9)], + ); } test_listLiteral_plusOperator() async { @@ -95,15 +100,16 @@ var list = [ } test_setLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var set = { 'a' 'b', 'c', }; -''', [ - lint(14, 9), - ]); +''', + [lint(14, 9)], + ); } test_setLiteral_plusOperator() async { @@ -117,15 +123,16 @@ var set = { } test_switchPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { List row = []; switch (row) { case ['one' 'two', var name!]: } } -''', [ - lint(64, 11), - ]); +''', + [lint(64, 11)], + ); } } diff --git a/pkg/linter/test/rules/no_default_cases_test.dart b/pkg/linter/test/rules/no_default_cases_test.dart index 5c9e2368907e..11b54058244f 100644 --- a/pkg/linter/test/rules/no_default_cases_test.dart +++ b/pkg/linter/test/rules/no_default_cases_test.dart @@ -18,7 +18,8 @@ class NoDefaultCasesTest extends LintRuleTest { String get lintRule => 'no_default_cases'; test_enumLikeType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final int i; const C._(this.i); @@ -37,13 +38,14 @@ void f(C c) { print('default'); } } -''', [ - lint(210, 32), - ]); +''', + [lint(210, 32)], + ); } test_enumType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(E e) { switch(e) { case E.a : @@ -57,9 +59,9 @@ void f(E e) { enum E { a, b, c; } -''', [ - lint(78, 32), - ]); +''', + [lint(78, 32)], + ); } test_intType() async { diff --git a/pkg/linter/test/rules/no_duplicate_case_values_test.dart b/pkg/linter/test/rules/no_duplicate_case_values_test.dart index d96b947d1738..fa9d1adc302b 100644 --- a/pkg/linter/test/rules/no_duplicate_case_values_test.dart +++ b/pkg/linter/test/rules/no_duplicate_case_values_test.dart @@ -21,7 +21,8 @@ abstract class BaseNoDuplicateCaseValuesTest extends LintRuleTest { @reflectiveTest class NoDuplicateCaseValuesTest extends BaseNoDuplicateCaseValuesTest { test_duplicateConstClassValue_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class ConstClass { final int v; const ConstClass(this.v); @@ -38,13 +39,14 @@ void switchConstClass() { default: } } -''', [ - error(WarningCode.UNREACHABLE_SWITCH_CASE, 237, 4), - ]); +''', + [error(WarningCode.UNREACHABLE_SWITCH_CASE, 237, 4)], + ); } test_duplicateEnumValue_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { one, two, @@ -62,15 +64,18 @@ void switchEnum() { default: } } -''', [ - // No lint. - error(WarningCode.UNREACHABLE_SWITCH_CASE, 139, 4), - error(WarningCode.UNREACHABLE_SWITCH_DEFAULT, 155, 7), - ]); +''', + [ + // No lint. + error(WarningCode.UNREACHABLE_SWITCH_CASE, 139, 4), + error(WarningCode.UNREACHABLE_SWITCH_DEFAULT, 155, 7), + ], + ); } test_duplicateIntConstant_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void switchInt() { const int A = 1; int v = 5; @@ -84,15 +89,18 @@ void switchInt() { default: } } -''', [ - // No lint. - error(WarningCode.UNREACHABLE_SWITCH_CASE, 95, 4), - error(WarningCode.UNREACHABLE_SWITCH_CASE, 107, 4), - ]); +''', + [ + // No lint. + error(WarningCode.UNREACHABLE_SWITCH_CASE, 95, 4), + error(WarningCode.UNREACHABLE_SWITCH_CASE, 107, 4), + ], + ); } test_duplicateStringConstant_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void switchString() { const String A = 'a'; String v = 'aa'; @@ -106,13 +114,15 @@ void switchString() { default: } } -''', [ - // No lint. - error(WarningCode.UNREACHABLE_SWITCH_CASE, 115, 4), - error(ParserErrorCode.INVALID_CONSTANT_PATTERN_BINARY, 122, 1), - error(WarningCode.UNREACHABLE_SWITCH_CASE, 131, 4), - error(ParserErrorCode.INVALID_CONSTANT_PATTERN_BINARY, 153, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNREACHABLE_SWITCH_CASE, 115, 4), + error(ParserErrorCode.INVALID_CONSTANT_PATTERN_BINARY, 122, 1), + error(WarningCode.UNREACHABLE_SWITCH_CASE, 131, 4), + error(ParserErrorCode.INVALID_CONSTANT_PATTERN_BINARY, 153, 1), + ], + ); } } @@ -120,7 +130,8 @@ void switchString() { class NoDuplicateCaseValuesTestLanguage219 extends BaseNoDuplicateCaseValuesTest with LanguageVersion219Mixin { test_duplicateConstClassValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class ConstClass { final int v; const ConstClass(this.v); @@ -137,13 +148,14 @@ void switchConstClass() { default: } } -''', [ - lint(242, 19), - ]); +''', + [lint(242, 19)], + ); } test_duplicateEnumValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { one, two, @@ -161,13 +173,14 @@ void switchEnum() { default: } } -''', [ - lint(144, 5), - ]); +''', + [lint(144, 5)], + ); } test_duplicateIntConstant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void switchInt() { const int A = 1; int v = 5; @@ -181,14 +194,14 @@ void switchInt() { default: } } -''', [ - lint(100, 1), - lint(112, 1), - ]); +''', + [lint(100, 1), lint(112, 1)], + ); } test_duplicateStringConstant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void switchString() { const String A = 'a'; String v = 'aa'; @@ -202,9 +215,8 @@ void switchString() { default: } } -''', [ - lint(120, 5), - lint(136, 4), - ]); +''', + [lint(120, 5), lint(136, 4)], + ); } } diff --git a/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart b/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart index 6577aead42d1..15975ebc5d88 100644 --- a/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart +++ b/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart @@ -16,18 +16,21 @@ main() { @reflectiveTest class NoLeadingUnderscoresForLibraryPrefixesTest extends LintRuleTest { @override - List get ignoredErrorCodes => - [WarningCode.UNUSED_IMPORT, WarningCode.UNUSED_LOCAL_VARIABLE]; + List get ignoredErrorCodes => [ + WarningCode.UNUSED_IMPORT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.no_leading_underscores_for_library_prefixes; test_leadingUnderscore() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async' as _async; -''', [ - lint(23, 6), - ]); +''', + [lint(23, 6)], + ); } test_snakeCase() async { @@ -37,11 +40,12 @@ import 'dart:async' as dart_async; } test_underscores() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async' as __; -''', [ - lint(23, 2), - ]); +''', + [lint(23, 2)], + ); } test_wildcard() async { diff --git a/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart b/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart index 71ca406b7ef4..07d276c7370f 100644 --- a/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart +++ b/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart @@ -17,24 +17,25 @@ main() { class NoLeadingUnderscoresForLocalIdentifiersTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_CATCH_STACK, - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_CATCH_STACK, + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.no_leading_underscores_for_local_identifiers; test_catchClause_error() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch(_error) {} } -''', [ - lint(28, 6), - ]); +''', + [lint(28, 6)], + ); } test_catchClause_error_justUnderscore() async { @@ -47,14 +48,15 @@ void f() { } test_catchClause_stackTrace() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch(error, _stackTrace) {} } -''', [ - lint(35, 11), - ]); +''', + [lint(35, 11)], + ); } test_field() async { @@ -76,13 +78,14 @@ class C { } test_forEach() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for(var _x in [1,2,3]) {} } -''', [ - lint(21, 2), - ]); +''', + [lint(21, 2)], + ); } test_forEach_justUnderscore() async { @@ -102,79 +105,86 @@ void f() { } test_forLoop_firstVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var _i = 0;;) {} } -''', [ - lint(22, 2), - ]); +''', + [lint(22, 2)], + ); } test_forLoop_multipleVariables() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i = 0, _j = 0;;) {} } -''', [ - lint(29, 2), - ]); +''', + [lint(29, 2)], + ); } test_listPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case [int _x, int y]) {} } -''', [ - lint(32, 2), - ]); +''', + [lint(32, 2)], + ); } test_listPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ([1,2]) { case [1 && var _a, 2 && var b]: } } -''', [ - lint(44, 2), - ]); +''', + [lint(44, 2)], + ); } test_listPattern_switch_leftOperand() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ([1,2]) { case [var _a && 1, 2 && var b]: } } -''', [ - lint(39, 2), - ]); +''', + [lint(39, 2)], + ); } test_localFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m() { int _f() => 10; } } -''', [ - lint(31, 2), - ]); +''', + [lint(31, 2)], + ); } test_localVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var _foo = 0; } -''', [ - lint(17, 4), - ]); +''', + [lint(17, 4)], + ); } test_localVariable_internalUnderscore() async { @@ -194,45 +204,49 @@ void f() { } test_localVariable_multipleVariables() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 1, _y = 2; } -''', [ - lint(24, 2), - ]); +''', + [lint(24, 2)], + ); } test_mapPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final {'first': _a, 'second': b} = {'first': 1, 'second': 2}; } -''', [ - lint(24, 2), - ]); +''', + [lint(24, 2)], + ); } test_mapPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case {'x': var _x, 'y' : var y}) {} } -''', [ - lint(37, 2), - ]); +''', + [lint(37, 2)], + ); } test_mapPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ({1: 2}) { case {'a': var _a, 'b': var b} : } } -''', [ - lint(45, 2), - ]); +''', + [lint(45, 2)], + ); } test_method() async { @@ -244,7 +258,8 @@ class C { } test_objectPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -252,9 +267,9 @@ class A { f() { final A(a: _b) = A(1); } -''', [ - lint(53, 2), - ]); +''', + [lint(53, 2)], + ); } test_objectPattern_destructured_field() async { @@ -270,7 +285,8 @@ f() { } test_objectPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int c; int d; @@ -280,13 +296,14 @@ class C { f(Object o) { if (o case C(c: var _x, d: var y)) {} } -''', [ - lint(88, 2), - ]); +''', + [lint(88, 2)], + ); } test_objectPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -296,9 +313,9 @@ f() { case A(a: >0 && var _b): } } -''', [ - lint(82, 2), - ]); +''', + [lint(82, 2)], + ); } test_objectPattern_switch_field() async { @@ -320,11 +337,12 @@ f(A a) { } test_parameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int _p) {} -''', [ - lint(11, 2), - ]); +''', + [lint(11, 2)], + ); } test_parameter_internalUnderscore() async { @@ -360,55 +378,60 @@ void f(int p) {} } test_recordPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var (_a, b) = ('a', 'b'); } -''', [ - lint(13, 2), - ]); +''', + [lint(13, 2)], + ); } test_recordPattern_destructured_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var (a: _a, :b) = (a: 1, b: 1); } -''', [ - lint(16, 2), - ]); +''', + [lint(16, 2)], + ); } test_recordPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (int _x, int y)) {} } -''', [ - lint(32, 2), - ]); +''', + [lint(32, 2)], + ); } test_recordPattern_ifCase_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (x: int _x, :int y)) {} } -''', [ - lint(35, 2), - ]); +''', + [lint(35, 2)], + ); } test_recordPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ((1, 2)) { case (var _a, var b): } } -''', [ - lint(40, 2), - ]); +''', + [lint(40, 2)], + ); } test_superFormalParameter() async { diff --git a/pkg/linter/test/rules/no_literal_bool_comparisons_test.dart b/pkg/linter/test/rules/no_literal_bool_comparisons_test.dart index b500cc1e5867..e71e8ecf9b3e 100644 --- a/pkg/linter/test/rules/no_literal_bool_comparisons_test.dart +++ b/pkg/linter/test/rules/no_literal_bool_comparisons_test.dart @@ -18,46 +18,50 @@ class NoLiteralBoolComparisonsTest extends LintRuleTest { String get lintRule => LintNames.no_literal_bool_comparisons; test_true_eqeq_x_localVariable_nonNullableBool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool x) { while (true == x) {} } -''', [ - lint(26, 4), - ]); +''', + [lint(26, 4)], + ); } test_x_bangeq_true_expression_nonNullableBool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool x, bool y) { print((x && y) != true); } -''', [ - lint(45, 4), - ]); +''', + [lint(45, 4)], + ); } test_x_eqeq_true_field_nonNullableBool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { if (c.x == true) {} } abstract class C { bool get x; } -''', [ - lint(27, 4), - ]); +''', + [lint(27, 4)], + ); } test_x_eqeq_true_localVariable_nonNullableBool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool x) { if (x == true) {} } -''', [ - lint(28, 4), - ]); +''', + [lint(28, 4)], + ); } test_x_eqeq_true_nullableBool() async { diff --git a/pkg/linter/test/rules/no_logic_in_create_state_test.dart b/pkg/linter/test/rules/no_logic_in_create_state_test.dart index 664ab8fd2b82..fe4ba4a6a7c0 100644 --- a/pkg/linter/test/rules/no_logic_in_create_state_test.dart +++ b/pkg/linter/test/rules/no_logic_in_create_state_test.dart @@ -54,7 +54,8 @@ class MyState extends State { } test_arrowBody_returnsState_passingArguments() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class MyWidget extends StatefulWidget { @@ -69,13 +70,14 @@ class MyState extends State { late BuildContext context; bool get mounted => false; } -''', [ - lint(119, 10), - ]); +''', + [lint(119, 10)], + ); } test_arrowBody_returnsState_withCascade() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class MyWidget extends StatefulWidget { @@ -89,13 +91,14 @@ class MyState extends State { late BuildContext context; bool get mounted => false; } -''', [ - lint(119, 20), - ]); +''', + [lint(119, 20)], + ); } test_blockBodyWithSingleStatement_returnsInstanceField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class MyWidget extends StatefulWidget { @@ -112,9 +115,9 @@ class MyState extends State { late BuildContext context; bool get mounted => false; } -''', [ - lint(161, 8), - ]); +''', + [lint(161, 8)], + ); } test_blockBodyWithSingleStatement_returnsState() async { @@ -138,7 +141,8 @@ class MyState extends State { } test_blockBodyWithSingleStatement_returnsState_withCascade() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class MyWidget extends StatefulWidget { @@ -154,13 +158,14 @@ class MyState extends State { late BuildContext context; bool get mounted => false; } -''', [ - lint(129, 20), - ]); +''', + [lint(129, 20)], + ); } test_instantiateTopLevel_returnTopLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class MyStatefulBad extends StatefulWidget { @@ -179,8 +184,8 @@ class MyState extends State { } var global = MyState(); -''', [ - lint(121, 48), - ]); +''', + [lint(121, 48)], + ); } } diff --git a/pkg/linter/test/rules/no_runtimeType_toString_test.dart b/pkg/linter/test/rules/no_runtimeType_toString_test.dart index 4db1c79d9eae..424f6a923496 100644 --- a/pkg/linter/test/rules/no_runtimeType_toString_test.dart +++ b/pkg/linter/test/rules/no_runtimeType_toString_test.dart @@ -28,14 +28,15 @@ extension E on C { } test_extension_onClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} extension E on C { String f() => '$runtimeType'; } -''', [ - lint(48, 11), - ]); +''', + [lint(48, 11)], + ); } test_inAbstractClass() async { @@ -82,27 +83,29 @@ class C { } test_interpolation_implicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { '$runtimeType'; } } -''', [ - lint(29, 11), - ]); +''', + [lint(29, 11)], + ); } test_interpolation_withBraces() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { '${runtimeType}'; } } -''', [ - lint(30, 11), - ]); +''', + [lint(30, 11)], + ); } test_inThrowExpression() async { @@ -137,15 +140,16 @@ class C { } test_toString_explicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { this.runtimeType.toString(); } } -''', [ - lint(44, 8), - ]); +''', + [lint(44, 8)], + ); } test_toString_expression() async { @@ -170,14 +174,15 @@ class C { } test_toString_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f() { super.runtimeType.toString(); } } -''', [ - lint(45, 8), - ]); +''', + [lint(45, 8)], + ); } } diff --git a/pkg/linter/test/rules/no_self_assignments_test.dart b/pkg/linter/test/rules/no_self_assignments_test.dart index 16711394c9d8..982c464d60ae 100644 --- a/pkg/linter/test/rules/no_self_assignments_test.dart +++ b/pkg/linter/test/rules/no_self_assignments_test.dart @@ -18,7 +18,8 @@ class NoSelfAssignmentsTest extends LintRuleTest { String get lintRule => LintNames.no_self_assignments; test_classMemberAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static String foo = "foo"; } @@ -26,7 +27,9 @@ class C { void main() { C.foo = C.foo; } -''', [lint(58, 13)]); +''', + [lint(58, 13)], + ); } test_classMemberAssignmentUnrelated() async { @@ -44,7 +47,8 @@ void main() { } test_fieldAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x = 5; @@ -52,7 +56,9 @@ class C { x = x; } } -''', [lint(41, 5)]); +''', + [lint(41, 5)], + ); } test_fieldAssignmentDifferentTargets() async { @@ -92,7 +98,8 @@ class C { } test_fieldAssignmentExplicitSameVar() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x = 5; @@ -100,7 +107,9 @@ class C { other.x = other.x; } } -''', [lint(53, 17)]); +''', + [lint(53, 17)], + ); } test_fieldAssignmentThisAndDifferentTarget() async { @@ -126,7 +135,8 @@ class C { } test_propertyAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x = 5; @@ -140,6 +150,8 @@ class C { x = x; } } -''', [lint(102, 5)]); +''', + [lint(102, 5)], + ); } } diff --git a/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart b/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart index c7deade63cc8..5f41378d3b22 100644 --- a/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart +++ b/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart @@ -72,16 +72,17 @@ class C { } test_localVar() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // @dart = 3.4 // (pre wildcard-variables) f() { var _ = 1; print(_); } -''', [ - lint(70, 1), - ]); +''', + [lint(70, 1)], + ); } test_localVar_wildcardsEnabled() async { @@ -109,16 +110,17 @@ class C { } test_param() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // @dart = 3.4 // (pre wildcard-variables) f(int __) { print(__); } -''', [ - lint(64, 2), - ]); +''', + [lint(64, 2)], + ); } test_topLevelFunction() async { diff --git a/pkg/linter/test/rules/non_constant_identifier_names_test.dart b/pkg/linter/test/rules/non_constant_identifier_names_test.dart index 5f815c010842..e79fd11b31b9 100644 --- a/pkg/linter/test/rules/non_constant_identifier_names_test.dart +++ b/pkg/linter/test/rules/non_constant_identifier_names_test.dart @@ -21,42 +21,45 @@ class NonConstantIdentifierNamesPatternsTest extends LintRuleTest { String get lintRule => LintNames.non_constant_identifier_names; test_extensionType_representationConstructorName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type e.Efg(int i) {} -''', [ - lint(17, 3), - ]); +''', + [lint(17, 3)], + ); } test_patternForStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var (AB, c) = (0, 1); AB <= 13; (AB, c) = (c, AB + c)) { } } -''', [ - lint(23, 2), - ]); +''', + [lint(23, 2)], + ); } test_patternIfStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if ([1,2] case [int AB, int c]) { } } -''', [ - lint(33, 2), - ]); +''', + [lint(33, 2)], + ); } test_patternIfStatement_recordField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object o) { if (o case (a: int AB, BC: int CD)) { } } -''', [ - lint(40, 2), - lint(52, 2), - ]); +''', + [lint(40, 2), lint(52, 2)], + ); } test_patternIfStatement_recordField_ok() async { @@ -76,14 +79,14 @@ void f() { } test_patternList_declaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [__, foo_bar] = [1,2]; } -''', [ - lint(13, 2), - lint(17, 7), - ]); +''', + [lint(13, 2), lint(17, 7)], + ); } test_patternList_declaration_underscore_ok() async { @@ -104,13 +107,14 @@ f() { } test_patternRecordField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var (AB, ) = (1, ); } -''', [ - lint(18, 2), - ]); +''', + [lint(18, 2)], + ); } test_patternRecordField_shortcut_ok() async { @@ -128,13 +132,14 @@ f(Object o) { } test_patternRecordField_underscores() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var (___, ) = (1, ); } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } } @@ -144,77 +149,93 @@ class NonConstantIdentifierNamesRecordsTest extends LintRuleTest { String get lintRule => LintNames.non_constant_identifier_names; test_recordFields() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = (x: 1); var b = (XX: 1); -''', [ - lint(25, 2), - ]); +''', + [lint(25, 2)], + ); } test_recordFields_fieldNameDuplicated() async { // This will produce a compile-time error and we don't want to over-report. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var r = (a: 1, a: 2); -''', [ - // No Lint. - error(CompileTimeErrorCode.DUPLICATE_FIELD_NAME, 15, 1), - ]); +''', + [ + // No Lint. + error(CompileTimeErrorCode.DUPLICATE_FIELD_NAME, 15, 1), + ], + ); } test_recordFields_fieldNameFromObject() async { // This will produce a compile-time error and we don't want to over-report. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = (hashCode: 1); -''', [ - // No Lint. - error(CompileTimeErrorCode.INVALID_FIELD_NAME_FROM_OBJECT, 9, 8), - ]); +''', + [ + // No Lint. + error(CompileTimeErrorCode.INVALID_FIELD_NAME_FROM_OBJECT, 9, 8), + ], + ); } test_recordFields_fieldNamePositional() async { // This will produce a compile-time error and we don't want to over-report. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var r = (0, $1: 2); -''', [ - // No Lint. - error(CompileTimeErrorCode.INVALID_FIELD_NAME_POSITIONAL, 12, 2), - ]); +''', + [ + // No Lint. + error(CompileTimeErrorCode.INVALID_FIELD_NAME_POSITIONAL, 12, 2), + ], + ); } test_recordFields_privateFieldName() async { // This will produce a compile-time error and we don't want to over-report. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = (_x: 1); -''', [ - // No Lint. - error(CompileTimeErrorCode.INVALID_FIELD_NAME_PRIVATE, 9, 2), - ]); +''', + [ + // No Lint. + error(CompileTimeErrorCode.INVALID_FIELD_NAME_PRIVATE, 9, 2), + ], + ); } test_recordTypeAnnotation_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' (int, {String SS, bool b})? triple; -''', [ - lint(14, 2), - ]); +''', + [lint(14, 2)], + ); } test_recordTypeAnnotation_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' (int, String SS, bool) triple = (1,'', false); -''', [ - lint(13, 2), - ]); +''', + [lint(13, 2)], + ); } test_recordTypeDeclarations() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var AA = (x: 1); const BB = (x: 1); -''', [ - lint(4, 2), - ]); +''', + [lint(4, 2)], + ); } } @@ -222,10 +243,10 @@ const BB = (x: 1); class NonConstantIdentifierNamesTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_ELEMENT, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_ELEMENT, + ]; @override String get lintRule => LintNames.non_constant_identifier_names; @@ -311,14 +332,14 @@ part 'test.dart'; void f(String? Ss, [int? Xx]) { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment void f(String? Ss, [int? Xx]) { } -''', [ - lint(42, 2), - lint(52, 2), - ]); +''', + [lint(42, 2), lint(52, 2)], + ); } test_augmentedGetter() async { @@ -384,16 +405,16 @@ class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class A { augment void m(String? Ss, [int? Xx]) { } } -''', [ - lint(62, 2), - lint(72, 2), - ]); +''', + [lint(62, 2), lint(72, 2)], + ); } test_augmentedTopLevelVariable() async { @@ -412,16 +433,15 @@ augment int Xx = 2; @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/5048') test_catch_underscores() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { try { } catch(__, ___) {} } -''', [ - lint(24, 2), - error(WarningCode.UNUSED_CATCH_STACK, 28, 3), - lint(28, 3), - ]); +''', + [lint(24, 2), error(WarningCode.UNUSED_CATCH_STACK, 28, 3), lint(28, 3)], + ); } test_catch_underscores_preWildcards() async { @@ -458,13 +478,14 @@ f() { } test_catchVariable_allCaps() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (ZZZ) {} } -''', [ - lint(27, 3), - ]); +''', + [lint(27, 3)], + ); } test_constructor_camelCase() async { @@ -476,14 +497,15 @@ class C { } test_constructor_factory() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(); factory C.Named() = C; } -''', [ - lint(29, 5), - ]); +''', + [lint(29, 5)], + ); } test_constructor_multipleUnderscores() async { @@ -503,23 +525,25 @@ class C { } test_constructor_private_title() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C._Named(); } -''', [ - lint(14, 6), - ]); +''', + [lint(14, 6)], + ); } test_constructor_private_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C._N(); } -''', [ - lint(14, 2), - ]); +''', + [lint(14, 2)], + ); } test_constructor_singleUnderscore() async { @@ -531,13 +555,14 @@ class C { } test_constructor_snakeCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.named_bar(); //LINT } -''', [ - lint(14, 9), - ]); +''', + [lint(14, 9)], + ); } test_constructor_startsWithDollar() async { @@ -549,13 +574,14 @@ class C { } test_constructor_title() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.Named(); } -''', [ - lint(14, 5), - ]); +''', + [lint(14, 5)], + ); } test_constructor_underscores() async { @@ -582,13 +608,14 @@ class A { } test_constructor_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.ZZZ(); } -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } test_field_private_lower() async { @@ -624,23 +651,25 @@ class C { } test_forEachVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var ZZZ in []) {} } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_forLoopVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var ZZZ = 0; ZZZ < 7; ++ZZZ) {} } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_formalParams_underscores() async { @@ -660,15 +689,18 @@ f(int _, int __) {} /// https://github.com/dart-lang/linter/issues/193 test_ignoreSyntheticNodes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { } C; -''', [ - // No lint - error(ParserErrorCode.MISSING_FUNCTION_PARAMETERS, 15, 1), - error(CompileTimeErrorCode.DUPLICATE_DEFINITION, 15, 1), - error(ParserErrorCode.MISSING_FUNCTION_BODY, 21, 1), - ]); +''', + [ + // No lint + error(ParserErrorCode.MISSING_FUNCTION_PARAMETERS, 15, 1), + error(CompileTimeErrorCode.DUPLICATE_DEFINITION, 15, 1), + error(ParserErrorCode.MISSING_FUNCTION_BODY, 21, 1), + ], + ); } test_localVariable_const_allCaps() async { @@ -680,24 +712,26 @@ void f() { } test_localVariable_multiple_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var ZZZ = 1, zzz = 1; } -''', [ - lint(17, 3), - ]); +''', + [lint(17, 3)], + ); } test_localVariable_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var ZZZ = 1; } -''', [ - lint(17, 3), - ]); +''', + [lint(17, 3)], + ); } test_method_instance_private_lower() async { @@ -709,72 +743,79 @@ class _F { } test_method_snakeCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int foo_bar() => 7; } -''', [ - lint(16, 7), - ]); +''', + [lint(16, 7)], + ); } test_method_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static Foo() {} } -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_parameter_fieldFormal_snakeCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final int bar_bar; C(this.bar_bar); } -''', [ - lint(22, 7), - ]); +''', + [lint(22, 7)], + ); } test_parameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m({int? Foo}) {} } -''', [ - lint(20, 3), - ]); +''', + [lint(20, 3)], + ); } test_parameter_optionalPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m([int? Foo]) {} } -''', [ - lint(20, 3), - ]); +''', + [lint(20, 3)], + ); } test_parameter_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m(var Foo) {} } -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_topLevelFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Main() {} -''', [ - lint(5, 4), - ]); +''', + [lint(5, 4)], + ); } test_topLevelFunction_private_camelCase() async { @@ -790,11 +831,12 @@ void _fun() {} //OK } test_topLevelFunction_private_snakeCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void _fun_bar() {} -''', [ - lint(5, 8), - ]); +''', + [lint(5, 8)], + ); } test_topLevelVariable_constant_upper() async { @@ -810,10 +852,11 @@ var cell_0_0 = 7; } test_topLevelVariable_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String ZZZ = ''; -''', [ - lint(7, 3), - ]); +''', + [lint(7, 3)], + ); } } diff --git a/pkg/linter/test/rules/noop_primitive_operations_test.dart b/pkg/linter/test/rules/noop_primitive_operations_test.dart index 82b0b5253a3f..5c8d2f5493d1 100644 --- a/pkg/linter/test/rules/noop_primitive_operations_test.dart +++ b/pkg/linter/test/rules/noop_primitive_operations_test.dart @@ -18,73 +18,80 @@ class NoopPrimitiveOperationsTest extends LintRuleTest { String get lintRule => LintNames.noop_primitive_operations; test_double_toDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(double x) { x.toDouble(); } -''', [ - lint(23, 8), - ]); +''', + [lint(23, 8)], + ); } test_int_ceil() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x) { x.ceil(); } -''', [ - lint(20, 4), - ]); +''', + [lint(20, 4)], + ); } test_int_floor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x) { x.floor(); } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_int_round() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x) { x.round(); } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_int_toInt() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x) { x.toInt(); } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_int_truncate() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x) { x.truncate(); } -''', [ - lint(20, 8), - ]); +''', + [lint(20, 8)], + ); } test_interpolation_object_toString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { '${1.toString()}'; } -''', [ - lint(18, 8), - ]); +''', + [lint(18, 8)], + ); } test_interpolation_super_toString() async { @@ -98,23 +105,25 @@ class C { } test_print_null_toString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print(null.toString()); } -''', [ - lint(24, 8), - ]); +''', + [lint(24, 8)], + ); } test_print_object_toString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print(1.toString()); } -''', [ - lint(21, 8), - ]); +''', + [lint(21, 8)], + ); } test_print_stringLiteral() async { @@ -132,30 +141,24 @@ void f(String x) { x = 'hello\n' '' 'world\n'; } ''', - [ - lint(35, 2), - ], + [lint(35, 2)], ); } test_string_adjacentBlankString_okAtEnd() async { - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' void f(String x) { x = 'hello\n' 'world\n' ''; } -''', - ); +'''); } test_string_adjacentBlankString_okAtStart() async { - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' void f(String x) { x = '' 'hello\n' 'world\n'; } -''', - ); +'''); } test_string_nullable_toString() async { @@ -167,13 +170,14 @@ void f(String? x) { } test_string_toString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(String x) { x.toString(); } -''', [ - lint(23, 8), - ]); +''', + [lint(23, 8)], + ); } test_super_toString() async { diff --git a/pkg/linter/test/rules/null_check_on_nullable_type_parameter_test.dart b/pkg/linter/test/rules/null_check_on_nullable_type_parameter_test.dart index ee16ac2c2fb5..b98ebec9eb9c 100644 --- a/pkg/linter/test/rules/null_check_on_nullable_type_parameter_test.dart +++ b/pkg/linter/test/rules/null_check_on_nullable_type_parameter_test.dart @@ -24,38 +24,42 @@ dynamic f(T? p) => p!; } test_expectedSameTypeVariable_arrow() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T f(T? p) => p!; -''', [ - lint(17, 1), - ]); +''', + [lint(17, 1)], + ); } test_expectedSameTypeVariable_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(T? p) { T t; t = p!; } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_expectedSameTypeVariable_assignmentInDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(T? p) { T t = p!; } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_expectedSameTypeVariable_block() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T f(T? p) { return p!; } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_inAsExpression() async { @@ -65,48 +69,53 @@ R f(P? p) => p! as R; } test_inAssignmentToNonNullableField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { late T t; void f(T? p) { t = p!; } } -''', [ - lint(51, 1), - ]); +''', + [lint(51, 1)], + ); } test_inListLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f(T? p) => [p!]; -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_inMapLiteralKey() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(T? p) => {p!: ''}; -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_inMapLiteralValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(T? p) => {'': p!}; -''', [ - lint(35, 1), - ]); +''', + [lint(35, 1)], + ); } test_inSetLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Set f(T? p) => {p!}; -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_inTargetOfObjectGetterCall() async { @@ -128,67 +137,72 @@ T f(T? p) => p!..toString(); } test_inYieldAsync() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Stream f(T? p) async* {yield p!;} -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_inYieldSync() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Iterable f(T? p) sync* {yield p!;} -''', [ - lint(37, 1), - ]); +''', + [lint(37, 1)], + ); } test_nullAssertPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(T? x){ if (x case var y!) print(y); } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_nullAssertPattern_list() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(List l){ var [x!, y] = l; } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_nullAssertPattern_logicalOr() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(T? x){ switch(x) { case var y! || var y! : print(y); } } -''', [ - lint(40, 1), - error(WarningCode.DEAD_CODE, 42, 9), - lint(50, 1), - ]); +''', + [lint(40, 1), error(WarningCode.DEAD_CODE, 42, 9), lint(50, 1)], + ); } test_nullAssertPattern_map() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Map m){ var {'x': y!} = m; } -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_nullAssertPattern_object() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { E? a; A(this.a); @@ -197,19 +211,20 @@ class A { f(T? t, A u) { A(a: t!) = u; } -''', [ - lint(66, 1), - ]); +''', + [lint(66, 1)], + ); } test_nullAssertPattern_record() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f((T?, T?) p){ var (x!, y) = p; } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_potentiallyNonNullableTypeVariable() async { @@ -219,19 +234,21 @@ T f(T p) => p!; // OK } test_typeParameterBoundToDynamic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T f(T? p) => p!; -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_typeParameterBoundToNullableObject() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T f(T? p) => p!; -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_typeParameterBoundToObject() async { @@ -241,18 +258,20 @@ T f(T? p) => p!; } test_typeParameterExtendsNullableObject_inAwaited() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f(T? p) async => await p!; -''', [ - lint(53, 1), - ]); +''', + [lint(53, 1)], + ); } test_typeParameterExtendsNullableObject_inAwaitedInList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future> f(T? p) async => await [p!]; -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } } diff --git a/pkg/linter/test/rules/null_closures_test.dart b/pkg/linter/test/rules/null_closures_test.dart index cf73a53573cc..50f6adfa62e0 100644 --- a/pkg/linter/test/rules/null_closures_test.dart +++ b/pkg/linter/test/rules/null_closures_test.dart @@ -26,23 +26,25 @@ void f() { } test_futureWait_cleanUp_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Future.wait([], cleanUp: null); } -''', [ - lint(29, 13), - ]); +''', + [lint(29, 13)], + ); } test_iterableFirstWhere_orElse_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.firstWhere((e) => e.isEven, orElse: null); } -''', [ - lint(60, 12), - ]); +''', + [lint(60, 12)], + ); } test_iterableSingleWhere_orElse_closure() async { @@ -54,13 +56,14 @@ void f(List list) { } test_iterableSingleWhere_orElse_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Set set) { set.singleWhere((e) => e.isEven, orElse: null); } -''', [ - lint(58, 12), - ]); +''', + [lint(58, 12)], + ); } test_iterableWhere_noOrElse() async { @@ -105,7 +108,8 @@ void f(Map map) { ///https://github.com/dart-lang/linter/issues/1414 test_recursiveInterfaceInheritance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A extends B { A(int x); } @@ -115,12 +119,18 @@ class B extends A {} void test_cycle() { A(null); } -''', [ - // No lint - error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 6, 1), - error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 41, 1), - error(CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT, 41, 1), - error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 81, 4), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 6, 1), + error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 41, 1), + error( + CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT, + 41, + 1, + ), + error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 81, 4), + ], + ); } } diff --git a/pkg/linter/test/rules/omit_local_variable_types_test.dart b/pkg/linter/test/rules/omit_local_variable_types_test.dart index 213826af1081..51853aa5ac2a 100644 --- a/pkg/linter/test/rules/omit_local_variable_types_test.dart +++ b/pkg/linter/test/rules/omit_local_variable_types_test.dart @@ -26,13 +26,14 @@ class C { } test_forEach() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (int i in [1, 2, 3]) { } } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_forEach_ok() async { @@ -44,15 +45,16 @@ f() { } test_forIn_iterableSubclass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class StringIterator implements Iterable {} void f(StringIterator items) { for (String item in items) {} } -''', [ - lint(106, 6), - ]); +''', + [lint(106, 6)], + ); } test_forIn_rightSideIsIterableOfDynamic_typedWithString() async { @@ -73,16 +75,17 @@ void f(StringIterator items) { } test_forLoop_declarationHasRedundantType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { late C next; } void f(C head) { for (C node = head; ; node = node.next) {} } -''', [ - lint(51, 1), - ]); +''', + [lint(51, 1)], + ); } /// Types are considered an important part of the pattern so we @@ -96,13 +99,14 @@ f() { } test_local_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { String a = 'a', b = 'b'; } -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } test_local_multiple_ok() async { @@ -122,13 +126,14 @@ f() { } test_multipleLocalVariables_rightSideIsIterable_typedWithRawIterable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Iterable a = new Iterable.empty(), b = new Iterable.empty(); } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } test_multipleLocalVariables_rightSideIsList_typedWithRawIterable() async { @@ -169,16 +174,17 @@ f() { /// https://github.com/dart-lang/linter/issues/3016 @failingTest test_paramIsType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T bar(T d) => d; String f() { String h = bar(''); return h; } -''', [ - lint(42, 26), - ]); +''', + [lint(42, 26)], + ); } test_record_destructured() async { @@ -239,15 +245,16 @@ String f() { /// https://github.com/dart-lang/linter/issues/3016 test_typeParamProvided() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' T bar(dynamic d) => d; String f() { String h = bar(''); return h; } -''', [ - lint(42, 6), - ]); +''', + [lint(42, 6)], + ); } } diff --git a/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart b/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart index e1c30a18107a..fb1bc27aac6e 100644 --- a/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart +++ b/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart @@ -18,31 +18,34 @@ class OmitObviousLocalVariableTypesTest extends LintRuleTest { String get lintRule => LintNames.omit_obvious_local_variable_types; test_as() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { int i = n as int; } num n = 1; -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_as_dynamic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { dynamic i = n as dynamic; } num n = 1; -''', [ - lint(8, 7), - ]); +''', + [lint(8, 7)], + ); } test_cascade() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { A a = A()..x..x..x; } @@ -50,19 +53,20 @@ f() { class A { final x = 0; } -''', [ - lint(8, 1), - ]); +''', + [lint(8, 1)], + ); } test_forEach_inferredList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (String s in ['a', 'b', 'c']) { } } -''', [ - lint(13, 6), - ]); +''', + [lint(13, 6)], + ); } test_forEach_listWithNonObviousElement() async { @@ -92,13 +96,14 @@ var list = [1, 2, 3]; } test_forEach_typedList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (int i in [1, 2, 3]) { } } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_genericInvocation_paramIsType() async { @@ -135,15 +140,16 @@ String f() { } test_instanceCreation_generic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { A a = A(); } class A {} -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } test_instanceCreation_generic_ok() async { @@ -157,25 +163,27 @@ class A {} } test_instanceCreation_nonGeneric() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { A a = A(); } class A {} -''', [ - lint(8, 1), - ]); +''', + [lint(8, 1)], + ); } test_list() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { List a = ['a', 'b', ('c' as dynamic) as String]; } -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_list_ok1() async { @@ -198,23 +206,25 @@ List foo(X x) => [x]; } test_literal_bool() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { bool b = true; } -''', [ - lint(8, 4), - ]); +''', + [lint(8, 4)], + ); } test_literal_double() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { double d = 1.5; } -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } // The type is not obvious. @@ -227,13 +237,14 @@ f() { } test_literal_int() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { int i = 1; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } // `Null` is not obvious, the inferred type is `dynamic`. @@ -246,33 +257,36 @@ f() { } test_literal_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { String s = "A string"; } -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } test_literal_symbol() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { Symbol s = #print; } -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } test_local_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { String a = 'a', b = 'b'; } -''', [ - lint(8, 6), - ]); +''', + [lint(8, 6)], + ); } test_local_multiple_ok() async { @@ -284,13 +298,14 @@ f() { } test_map() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { Map a = {1.5: 'a'}; } -''', [ - lint(8, 19), - ]); +''', + [lint(8, 19)], + ); } test_map_ok1() async { diff --git a/pkg/linter/test/rules/omit_obvious_property_types_test.dart b/pkg/linter/test/rules/omit_obvious_property_types_test.dart index bd0674cab5ee..65875680ffa8 100644 --- a/pkg/linter/test/rules/omit_obvious_property_types_test.dart +++ b/pkg/linter/test/rules/omit_obvious_property_types_test.dart @@ -18,49 +18,54 @@ class OmitObviousPropertyTypesTest extends LintRuleTest { String get lintRule => 'omit_obvious_property_types'; test_as_dynamic_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static dynamic i = n as dynamic; } num n = 1; -''', [ - lint(19, 7), - ]); +''', + [lint(19, 7)], + ); } test_as_dynamic_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic i = n as dynamic; num n = 1; -''', [ - lint(0, 7), - ]); +''', + [lint(0, 7)], + ); } test_as_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static int i = n as int; } num n = 1; -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_as_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int i = n as int; num n = 1; -''', [ - lint(0, 3), - ]); +''', + [lint(0, 3)], + ); } test_cascade_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static C c = C()..x..x..x; } @@ -68,21 +73,22 @@ class A { class C { final x = 0; } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_cascade_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' C c = C()..x..x..x; class C { final x = 0; } -''', [ - lint(0, 1), - ]); +''', + [lint(0, 1)], + ); } test_genericInvocation_paramIsType_static() async { @@ -155,47 +161,51 @@ class C {} } test_instanceCreation_generic_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static C c = C(); } class C {} -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_instanceCreation_generic_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' C c = C(); class C {} -''', [ - lint(0, 6), - ]); +''', + [lint(0, 6)], + ); } test_instanceCreation_nonGeneric_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static C c = C(); } class C {} -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_instanceCreation_nonGeneric_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' C c = C(); class C {} -''', [ - lint(0, 1), - ]); +''', + [lint(0, 1)], + ); } test_list_ok1_static() async { @@ -231,57 +241,63 @@ List foo(X x) => [x]; } test_list_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static List a = ['a', 'b', ('c' as dynamic) as String]; } -''', [ - lint(19, 12), - ]); +''', + [lint(19, 12)], + ); } test_list_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List a = ['a', 'b', ('c' as dynamic) as String]; -''', [ - lint(0, 12), - ]); +''', + [lint(0, 12)], + ); } test_literal_bool_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static bool b = true; } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_literal_bool_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool b = true; -''', [ - lint(0, 4), - ]); +''', + [lint(0, 4)], + ); } test_literal_double_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static double d = 1.5; } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_literal_double_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double d = 1.5; -''', [ - lint(0, 6), - ]); +''', + [lint(0, 6)], + ); } // The type is not obvious. @@ -301,21 +317,23 @@ double d = 1; } test_literal_int_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static int i = 1; } -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_literal_int_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int i = 1; -''', [ - lint(0, 3), - ]); +''', + [lint(0, 3)], + ); } // `Null` is not obvious, the inferred type is `dynamic`. @@ -335,39 +353,43 @@ Null nil = null; } test_literal_string_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static String s = "A string"; } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_literal_string_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String s = "A string"; -''', [ - lint(0, 6), - ]); +''', + [lint(0, 6)], + ); } test_literal_symbol_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static Symbol s = #print; } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_literal_symbol_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Symbol s = #print; -''', [ - lint(0, 6), - ]); +''', + [lint(0, 6)], + ); } test_local_multiple_ok_static() async { @@ -447,38 +469,42 @@ var b = 'b'; } test_map_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static Map a = {1.5: 'a'}; } -''', [ - lint(19, 19), - ]); +''', + [lint(19, 19)], + ); } test_map_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map a = {1.5: 'a'}; -''', [ - lint(0, 19), - ]); +''', + [lint(0, 19)], + ); } test_multiple_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static String a = 'a', b = 'b'; } -''', [ - lint(19, 6), - ]); +''', + [lint(19, 6)], + ); } test_multiple_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String a = 'a', b = 'b'; -''', [ - lint(0, 6), - ]); +''', + [lint(0, 6)], + ); } } diff --git a/pkg/linter/test/rules/one_member_abstracts_test.dart b/pkg/linter/test/rules/one_member_abstracts_test.dart index 0659a7d4c656..82524d63395a 100644 --- a/pkg/linter/test/rules/one_member_abstracts_test.dart +++ b/pkg/linter/test/rules/one_member_abstracts_test.dart @@ -18,23 +18,27 @@ class OneMemberAbstractsTest extends LintRuleTest { String get lintRule => LintNames.one_member_abstracts; test_macroClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract macro class M { void m(); } -''', [ - // TODO(pq): add abstract macro compilation error when implemented - ]); +''', + [ + // TODO(pq): add abstract macro compilation error when implemented + ], + ); } test_oneMember_abstract() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class C { void m(); } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_oneMember_abstractGetter() async { @@ -82,13 +86,14 @@ augment abstract class A { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part 'a.dart'; abstract class A { } -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_oneMember_extendedType() async { @@ -184,14 +189,15 @@ abstract class C { } test_zeroMember_extendedTypeHasOneMember() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class D extends C {} abstract class C { void m(); } -''', [ - lint(46, 1), - ]); +''', + [lint(46, 1)], + ); } } diff --git a/pkg/linter/test/rules/only_throw_errors_test.dart b/pkg/linter/test/rules/only_throw_errors_test.dart index 9534b41d0726..685e3a8944e0 100644 --- a/pkg/linter/test/rules/only_throw_errors_test.dart +++ b/pkg/linter/test/rules/only_throw_errors_test.dart @@ -71,13 +71,14 @@ void f() { } test_int() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { throw 7; } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_never() async { @@ -91,22 +92,24 @@ Never e() => throw Exception(); } test_object() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { throw Object(); } -''', [ - lint(19, 8), - ]); +''', + [lint(19, 8)], + ); } test_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { throw 'hello'; } -''', [ - lint(19, 7), - ]); +''', + [lint(19, 7)], + ); } } diff --git a/pkg/linter/test/rules/overridden_fields_test.dart b/pkg/linter/test/rules/overridden_fields_test.dart index ad9b235e2fee..9f271392f570 100644 --- a/pkg/linter/test/rules/overridden_fields_test.dart +++ b/pkg/linter/test/rules/overridden_fields_test.dart @@ -37,9 +37,7 @@ augment class A { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(45, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(45, 1)]); } test_augmentedField() async { @@ -64,14 +62,13 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(85, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(85, 1)]); await assertNoDiagnosticsInFile(b.path); } test_conflictingFieldAndMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x() => 0; } @@ -79,9 +76,9 @@ class A { class B extends A { int x = 9; } -''', [ - error(CompileTimeErrorCode.CONFLICTING_FIELD_AND_METHOD, 55, 1), - ]); +''', + [error(CompileTimeErrorCode.CONFLICTING_FIELD_AND_METHOD, 55, 1)], + ); } /// https://github.com/dart-lang/linter/issues/2874 @@ -98,16 +95,17 @@ class B extends A { } test_extendingClass_multipleDeclarations() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int y = 1; } class B extends A { final x = 1, y = 2; } -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_extendingClass_overridingAbstract() async { @@ -134,7 +132,8 @@ class B extends A { } test_extendsClass_indirectly() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 0; } @@ -143,9 +142,9 @@ class C extends B { @override int x = 1; } -''', [ - lint(84, 1), - ]); +''', + [lint(84, 1)], + ); } test_externalLibrary() async { @@ -154,14 +153,15 @@ class A { int? public; } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; class B extends A { int? public; } -''', [ - lint(44, 6), - ]); +''', + [lint(44, 6)], + ); } test_externalLibraryWithPrivateField() async { @@ -170,14 +170,15 @@ class A { int? _private; } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'a.dart'; class B extends A { int? _private; } -''', [ - error(WarningCode.UNUSED_FIELD, 44, 8), - ]); +''', + [error(WarningCode.UNUSED_FIELD, 44, 8)], + ); } test_fieldOverridesGetter() async { @@ -205,7 +206,8 @@ class B implements A { } test_mixingInMixin() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin M { int x = 1; } @@ -213,9 +215,9 @@ class A with M { @override int x = 2; } -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_mixingInMixin_overridingAbstract() async { @@ -234,7 +236,8 @@ class A with M { // See: https://github.com/dart-lang/linter/issues/2969 // Preserves existing testing logic but has so many misuses of mixins that // that it's hard to know how much tested logic is intentional. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Base { Object field = 'lorem'; @@ -299,28 +302,31 @@ class GC34 extends GC33 { @override Object gc33 = 'yada'; } -''', [ - error(WarningCode.OVERRIDE_ON_NON_OVERRIDING_FIELD, 120, 1), - lint(127, 5), - lint(194, 9), - error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 273, 4), - lint(301, 9), - lint(343, 5), - lint(418, 9), - error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 472, 4), - lint(500, 9), - lint(542, 5), - lint(617, 9), - error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 751, 4), - lint(779, 9), - lint(821, 4), - lint(883, 1), - lint(912, 4), - ]); +''', + [ + error(WarningCode.OVERRIDE_ON_NON_OVERRIDING_FIELD, 120, 1), + lint(127, 5), + lint(194, 9), + error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 273, 4), + lint(301, 9), + lint(343, 5), + lint(418, 9), + error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 472, 4), + lint(500, 9), + lint(542, 5), + lint(617, 9), + error(CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT, 751, 4), + lint(779, 9), + lint(821, 4), + lint(883, 1), + lint(912, 4), + ], + ); } test_mixinSuperclassConstraint() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 1; } @@ -328,9 +334,9 @@ mixin M on A { @override final x = 1; } -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_overridingAbstractField() async { @@ -347,7 +353,8 @@ class B extends A { } test_privateFieldInSameLibrary() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int _x = 0; } @@ -355,15 +362,18 @@ class A { class B extends A { int _x = 9; } -''', [ - error(WarningCode.UNUSED_FIELD, 16, 2), - lint(53, 2), - error(WarningCode.UNUSED_FIELD, 53, 2), - ]); +''', + [ + error(WarningCode.UNUSED_FIELD, 16, 2), + lint(53, 2), + error(WarningCode.UNUSED_FIELD, 53, 2), + ], + ); } test_publicFieldInSameLibrary() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 0; } @@ -371,22 +381,25 @@ class A { class B extends A { int x = 9; } -''', [ - lint(52, 1), - ]); +''', + [lint(52, 1)], + ); } test_recursiveInterfaceInheritance() async { // Produces a recursive_interface_inheritance diagnostic. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A extends B {} class B extends A { int field = 0; } -''', [ - // No lint - error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 6, 1), - error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 27, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 6, 1), + error(CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE, 27, 1), + ], + ); } } diff --git a/pkg/linter/test/rules/package_names_test.dart b/pkg/linter/test/rules/package_names_test.dart index 98cd95837ad1..5e6ed207ab1d 100644 --- a/pkg/linter/test/rules/package_names_test.dart +++ b/pkg/linter/test/rules/package_names_test.dart @@ -21,30 +21,30 @@ class PackageNamesTest extends LintRuleTest { String get lintRule => LintNames.package_names; test_lowerCamelCase() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fooBar version: 0.0.1 -''', [ - lint(6, 6), - ]); +''', + [lint(6, 6)], + ); } test_oneUpperWord() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: Foo version: 0.0.1 -''', [ - lint(6, 3), - ]); +''', + [lint(6, 3)], + ); } test_oneWord() async { - await assertNoPubspecDiagnostics( - r''' + await assertNoPubspecDiagnostics(r''' name: foo version: 0.0.1 -''', - ); +'''); } test_snakeCase() async { @@ -55,11 +55,12 @@ version: 0.0.1 } test_upperCamelCase() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: FooBar version: 0.0.1 -''', [ - lint(6, 6), - ]); +''', + [lint(6, 6)], + ); } } diff --git a/pkg/linter/test/rules/package_prefixed_library_names_test.dart b/pkg/linter/test/rules/package_prefixed_library_names_test.dart index 67a3c9aa85d0..5245ab4ba1dc 100644 --- a/pkg/linter/test/rules/package_prefixed_library_names_test.dart +++ b/pkg/linter/test/rules/package_prefixed_library_names_test.dart @@ -19,10 +19,11 @@ class PackagePrefixedLibraryNamesTest extends LintRuleTest { @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/3395') test_badName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library linter.not_where_it_should_be; -''', [ - lint(8, 29), - ]); +''', + [lint(8, 29)], + ); } } diff --git a/pkg/linter/test/rules/parameter_assignments_test.dart b/pkg/linter/test/rules/parameter_assignments_test.dart index f6572f5c8bdb..870816a156eb 100644 --- a/pkg/linter/test/rules/parameter_assignments_test.dart +++ b/pkg/linter/test/rules/parameter_assignments_test.dart @@ -18,89 +18,99 @@ class ParameterAssignmentsTest extends LintRuleTest { String get lintRule => LintNames.parameter_assignments; test_assignment_nullableParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? p]) { p ??= 8; p = 42; } -''', [ - lint(32, 6), - ]); +''', + [lint(32, 6)], + ); } test_assignment_nullableParameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({int? p}) { p ??= 8; p = 42; } -''', [ - lint(32, 6), - ]); +''', + [lint(32, 6)], + ); } test_assignment_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? _]) { _ = 8; } -''', [ - // No lint. - error(CompileTimeErrorCode.UNDEFINED_IDENTIFIER, 21, 1), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.UNDEFINED_IDENTIFIER, 21, 1), + ], + ); } @FailingTest(reason: 'Closures not implemented') test_closure_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (int p) { p = 2; }(2); } -''', [ - lint(27, 5), - ]); +''', + [lint(27, 5)], + ); } test_compoundAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p += 3; } -''', [ - lint(18, 6), - ]); +''', + [lint(18, 6)], + ); } test_function_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p = 4; } -''', [ - lint(18, 5), - ]); +''', + [lint(18, 5)], + ); } test_function_incrementAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p += 4; } -''', [ - lint(18, 6), - ]); +''', + [lint(18, 6)], + ); } test_function_named_default() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({int p = 5}) { print(p++); } -''', [ - lint(30, 3), - ]); +''', + [lint(30, 3)], + ); } test_function_named_optional_ok() async { @@ -131,15 +141,18 @@ void f(String? p) { } test_function_positional_optional_assignedTwice() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? optional]) { optional ??= 8; optional ??= 16; } -''', [ - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 59, 2), - lint(46, 15), - ]); +''', + [ + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 59, 2), + lint(46, 15), + ], + ); } test_function_positional_optional_ok() async { @@ -151,57 +164,62 @@ void f([int? optional]) { } test_function_positional_optional_re_incremented() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? optional]) { optional ??= 8; optional += 16; } -''', [ - lint(46, 14), - ]); +''', + [lint(46, 14)], + ); } test_function_positional_optional_reassigned() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? optional]) { optional ??= 8; optional = 16; } -''', [ - lint(46, 13), - ]); +''', + [lint(46, 13)], + ); } test_function_postfix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p++; } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } test_function_prefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { ++p; } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } test_instanceMethod_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(int p) { p = 4; } } -''', [ - lint(32, 5), - ]); +''', + [lint(32, 5)], + ); } test_instanceMethod_nonAssignment() async { @@ -215,85 +233,92 @@ class A { } test_instanceSetter_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { set x(int value) { value = 5; } } -''', [ - lint(35, 9), - ]); +''', + [lint(35, 9)], + ); } // If and switch cases don't need verification since params aren't valid // constant pattern expressions. test_listAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(var b) { [b] = [1]; } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_localFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { void g() { p = 3; } g(); } -''', [ - lint(33, 5), - ]); +''', + [lint(33, 5)], + ); } test_mapAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(var a) { {'a': a} = {'a': 1}; } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } test_member_setter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { set x(int v) { v = 5; } } -''', [ - lint(31, 5), - ]); +''', + [lint(31, 5)], + ); } test_nullAwareAssignment_nonNullableParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int p = 42]) { // ignore: dead_null_aware_expression p ??= 8; } -''', [ - lint(65, 7), - ]); +''', + [lint(65, 7)], + ); } test_nullAwareAssignment_nonNullableParameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({int p = 42}) { // ignore: dead_null_aware_expression p ??= 8; } -''', [ - lint(65, 7), - ]); +''', + [lint(65, 7)], + ); } test_nullAwareAssignment_nullableParameter() async { @@ -313,19 +338,21 @@ void f({int? p}) { } test_nullAwareAssignment_nullableParameter_promotedToNonNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([int? p]) { p ??= 8; // ignore: dead_null_aware_expression p ??= 16; } -''', [ - lint(72, 8), - ]); +''', + [lint(72, 8)], + ); } test_objectAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -334,50 +361,54 @@ class A { f(var b) { A(a: b) = A(1); } -''', [ - lint(48, 7), - ]); +''', + [lint(48, 7)], + ); } test_postfixOperation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p++; } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } test_postfixOperation_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({int p = 5}) { p++; } -''', [ - lint(24, 3), - ]); +''', + [lint(24, 3)], + ); } test_recordAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(var a) { var b = 0; (a, b) = (1, 2); } -''', [ - lint(31, 6), - ]); +''', + [lint(31, 6)], + ); } test_topLevelFunction_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { p = 4; } -''', [ - lint(18, 5), - ]); +''', + [lint(18, 5)], + ); } test_topLevelFunction_nonAssignment() async { diff --git a/pkg/linter/test/rules/prefer_adjacent_string_concatenation_test.dart b/pkg/linter/test/rules/prefer_adjacent_string_concatenation_test.dart index 9953d487d7da..5d0620a36329 100644 --- a/pkg/linter/test/rules/prefer_adjacent_string_concatenation_test.dart +++ b/pkg/linter/test/rules/prefer_adjacent_string_concatenation_test.dart @@ -24,19 +24,21 @@ var s = 'hello' ' world'; } test_plusOperator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = 'hello' + ' world'; -''', [ - lint(16, 1), - ]); +''', + [lint(16, 1)], + ); } test_plusOperator_inListLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var list = ['this is' + ' not allowed']; -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_plusOperator_nonStringLiteralLeft() async { diff --git a/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart b/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart index 091f3a3b9f90..8bb36f4c9a4c 100644 --- a/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart +++ b/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart @@ -30,16 +30,17 @@ class A { } test_assertContainsFieldFormalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int? f; C({this.f}) { assert(f != null); } } -''', [ - lint(40, 6), - ]); +''', + [lint(40, 6)], + ); } test_assertContainsInstanceMethod() async { @@ -140,42 +141,44 @@ class D extends C { } test_assertContainsParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(int? p) { assert(p != null); } } -''', [ - lint(28, 6), - ]); +''', + [lint(28, 6)], + ); } test_assertContainsParameter_consecutive() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(int? p) { assert(p != null); assert(p != null); } } -''', [ - lint(28, 6), - lint(51, 6), - ]); +''', + [lint(28, 6), lint(51, 6)], + ); } test_assertContainsParameter_usedInInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int? f; C({int? f}) : f = f ?? 7 { assert(f != null); } } -''', [ - lint(53, 6), - ]); +''', + [lint(53, 6)], + ); } test_assertContainsSimpleParameter() async { @@ -192,33 +195,36 @@ class C { } test_assertContainsStaticMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static int? m() => null; C() { assert(m() != null); } } -''', [ - lint(49, 6), - ]); +''', + [lint(49, 6)], + ); } test_assertContainsStaticProperty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static int? get f => null; C() { assert(f != null); } } -''', [ - lint(51, 6), - ]); +''', + [lint(51, 6)], + ); } test_assertContainsTopLevelMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? m() => null; class C { @@ -226,13 +232,14 @@ class C { assert(m() != null); } } -''', [ - lint(41, 6), - ]); +''', + [lint(41, 6)], + ); } test_assertContainsTopLevelProperty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? get f => null; class C { @@ -240,9 +247,9 @@ class C { assert(f != null); } } -''', [ - lint(43, 6), - ]); +''', + [lint(43, 6)], + ); } test_assertFollowsStatement() async { @@ -257,15 +264,16 @@ class C { } test_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int? i) { E.e(this.i) { assert(i != null); } } -''', [ - lint(47, 6), - ]); +''', + [lint(47, 6)], + ); } test_extensionType_initializer() async { @@ -277,16 +285,17 @@ extension type E(int? i) { } test_firstStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named(a) { assert(a != null); } } -''', [ - lint(29, 6), - ]); +''', + [lint(29, 6)], + ); } test_initializer() async { @@ -307,7 +316,8 @@ class C { } test_nonBoolExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { bool? f; A() { @@ -318,14 +328,17 @@ class A { }); } } -''', [ - // No lint - error(CompileTimeErrorCode.NON_BOOL_EXPRESSION, 40, 50), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.NON_BOOL_EXPRESSION, 40, 50), + ], + ); } test_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { final int a; A(this.a); @@ -336,8 +349,8 @@ class B extends A { assert(a != 0); } } -''', [ - lint(80, 6), - ]); +''', + [lint(80, 6)], + ); } } diff --git a/pkg/linter/test/rules/prefer_asserts_with_message_test.dart b/pkg/linter/test/rules/prefer_asserts_with_message_test.dart index 59a2784646ed..7b3899ed4fcc 100644 --- a/pkg/linter/test/rules/prefer_asserts_with_message_test.dart +++ b/pkg/linter/test/rules/prefer_asserts_with_message_test.dart @@ -26,13 +26,14 @@ class A { } test_assertInitializer_noMessage() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A() : assert(true); } -''', [ - lint(18, 12), - ]); +''', + [lint(18, 12)], + ); } test_assertStatement_message() async { @@ -44,12 +45,13 @@ void f() { } test_assertStatement_noMessage() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { assert(true); } -''', [ - lint(13, 13), - ]); +''', + [lint(13, 13)], + ); } } diff --git a/pkg/linter/test/rules/prefer_collection_literals_test.dart b/pkg/linter/test/rules/prefer_collection_literals_test.dart index 08c1dff44a6c..166b2f2b47ac 100644 --- a/pkg/linter/test/rules/prefer_collection_literals_test.dart +++ b/pkg/linter/test/rules/prefer_collection_literals_test.dart @@ -48,7 +48,8 @@ void f(LinkedHashSet s) { } test_closure_returns_linkedHashSet() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void a(Set Function() f) {} @@ -56,9 +57,9 @@ void a(Set Function() f) {} void c() { a(() => LinkedHashSet()); } -''', [ - lint(82, 20), - ]); +''', + [lint(82, 20)], + ); } test_conditionalLeft() async { @@ -111,13 +112,14 @@ class C { } test_functionExpression_omittedReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; f() => LinkedHashMap(); -''', [ - lint(34, 15), - ]); +''', + [lint(34, 15)], + ); } test_iterable_emptyConstructor_iterableDeclaration() async { @@ -129,14 +131,15 @@ void f() { } test_linkedHashMap_unnamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { LinkedHashMap(); } -''', [ - lint(39, 15), - ]); +''', + [lint(39, 15)], + ); } test_linkedHashMap_unnamedConstructor_linkedHashMapParameterType() async { @@ -150,26 +153,28 @@ void g(LinkedHashMap p) {} } test_linkedHashMap_unnamedConstructor_mapParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { g(LinkedHashMap()); } void g(Map p) {} -''', [ - lint(41, 25), - ]); +''', + [lint(41, 25)], + ); } test_linkedHashSet_fromConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { LinkedHashSet.from(['foo', 'bar', 'baz']); } -''', [ - lint(39, 41), - ]); +''', + [lint(39, 41)], + ); } test_linkedHashSet_fromConstructor_linkedHashSetDeclaration() async { @@ -182,36 +187,39 @@ void f() { } test_linkedHashSet_fromConstructor_setDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { Set x = LinkedHashSet.from([1, 2, 3]); } -''', [ - lint(52, 29), - ]); +''', + [lint(52, 29)], + ); } test_linkedHashSet_ofConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { LinkedHashSet.of(['foo', 'bar', 'baz']); } -''', [ - lint(39, 39), - ]); +''', + [lint(39, 39)], + ); } test_linkedHashSet_unnamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { LinkedHashSet(); } -''', [ - lint(39, 15), - ]); +''', + [lint(39, 15)], + ); } test_linkedHashSet_unnamedConstructor_hashSetParameterType() async { @@ -244,14 +252,15 @@ void f() { } test_linkedHashSet_unnamedConstructor_setDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { Set x = LinkedHashSet(); } -''', [ - lint(52, 20), - ]); +''', + [lint(52, 20)], + ); } /// https://github.com/dart-lang/linter/issues/2985 @@ -270,7 +279,8 @@ void c() { } test_linkedHashSetParameter_named_type_unrequired() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; class Foo {} @@ -280,9 +290,9 @@ void a({required Set some}) {} void c() { a(some: LinkedHashSet()); } -''', [ - lint(99, 20), - ]); +''', + [lint(99, 20)], + ); } test_linkedHashSetParameter_type_required() async { @@ -300,7 +310,8 @@ void c() { } test_linkedHashSetParameter_type_unrequired() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; class Foo {} @@ -310,9 +321,9 @@ void b(Set some) {} void c() { b(LinkedHashSet()); } -''', [ - lint(82, 20), - ]); +''', + [lint(82, 20)], + ); } test_list_filledConstructor() async { @@ -332,13 +343,14 @@ void f() { } test_listLiteral_toSet() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { ['foo', 'bar', 'baz'].toSet(); } -''', [ - lint(13, 29), - ]); +''', + [lint(13, 29)], + ); } test_map_identityConstructor() async { @@ -358,13 +370,14 @@ void f() { } test_map_unnamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Map(); } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_mapLiteral() async { @@ -442,23 +455,25 @@ Iterable> f() sync* { } test_set_fromConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Set.from(['foo', 'bar', 'baz']); } -''', [ - lint(13, 31), - ]); +''', + [lint(13, 31)], + ); } test_set_fromConstructor_withTypeArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Set.from([]); } -''', [ - lint(13, 17), - ]); +''', + [lint(13, 17)], + ); } test_set_identityConstructor() async { @@ -470,44 +485,48 @@ void f() { } test_set_ofConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Set.of(['foo', 'bar', 'baz']); } -''', [ - lint(13, 29), - ]); +''', + [lint(13, 29)], + ); } test_set_unnamedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Set(); } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_set_unnamedConstructor_objectParameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(Set()); } void g(Object p) {} -''', [ - lint(15, 5), - ]); +''', + [lint(15, 5)], + ); } test_set_unnamedContsructor_explicitTypeArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Set(); } -''', [ - lint(13, 10), - ]); +''', + [lint(13, 10)], + ); } test_typedefConstruction() async { @@ -519,15 +538,18 @@ var x = MyMap(); } test_undefinedFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:collection'; void f() { printUnresolved(LinkedHashSet()); } -''', [ - // No lints. - error(CompileTimeErrorCode.UNDEFINED_FUNCTION, 40, 15), - ]); +''', + [ + // No lints. + error(CompileTimeErrorCode.UNDEFINED_FUNCTION, 40, 15), + ], + ); } } diff --git a/pkg/linter/test/rules/prefer_conditional_assignment_test.dart b/pkg/linter/test/rules/prefer_conditional_assignment_test.dart index bd20c02c85fb..43f8400d1631 100644 --- a/pkg/linter/test/rules/prefer_conditional_assignment_test.dart +++ b/pkg/linter/test/rules/prefer_conditional_assignment_test.dart @@ -18,7 +18,8 @@ class PreferConditionalAssignmentTest extends LintRuleTest { String get lintRule => LintNames.prefer_conditional_assignment; test_field_ifEqNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? x; @@ -28,13 +29,14 @@ class C { } } } -''', [ - lint(49, 35), - ]); +''', + [lint(49, 35)], + ); } test_field_ifEqNull_conditionWrappedInParens() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? x; void f(String s) { @@ -43,13 +45,14 @@ class C { } } } -''', [ - lint(48, 37), - ]); +''', + [lint(48, 37)], + ); } test_field_ifEqNull_eachWrappedInParens() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? x; void f(String s) { @@ -58,13 +61,14 @@ class C { } } } -''', [ - lint(48, 39), - ]); +''', + [lint(48, 39)], + ); } test_field_ifEqNull_statementBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? x; String? f(String s) { @@ -73,9 +77,9 @@ class C { return x; } } -''', [ - lint(51, 27), - ]); +''', + [lint(51, 27)], + ); } test_field_ifHasElse() async { @@ -108,7 +112,8 @@ class C { } test_field_onSameTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? x; void f(C a) { @@ -117,9 +122,9 @@ class C { } } } -''', [ - lint(43, 40), - ]); +''', + [lint(43, 40)], + ); } test_field_unrelatedAssignment() async { diff --git a/pkg/linter/test/rules/prefer_const_constructors_in_immutables_test.dart b/pkg/linter/test/rules/prefer_const_constructors_in_immutables_test.dart index 942acfe1ce5e..155481a5743b 100644 --- a/pkg/linter/test/rules/prefer_const_constructors_in_immutables_test.dart +++ b/pkg/linter/test/rules/prefer_const_constructors_in_immutables_test.dart @@ -21,16 +21,17 @@ class PreferConstConstructorsInImmutablesTest extends LintRuleTest { String get lintRule => LintNames.prefer_const_constructors_in_immutables; test_assertInitializer_canBeConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { C.named(a) : assert(a != null); } -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_assertInitializer_cannotBeConst() async { @@ -58,7 +59,8 @@ class B extends A { } test_extendsImmutable_nonConstConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class A { @@ -67,9 +69,9 @@ class A { class B extends A { B(); } -''', [ - lint(91, 1), - ]); +''', + [lint(91, 1)], + ); } test_extendsImmutable_nonConstSuperCall() async { @@ -102,25 +104,27 @@ extension type const E(int i) { } } test_extensionType_nonConstConstructor_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable extension type const E(int i) { E.e(this.i); } -''', [ - lint(78, 1), - ]); +''', + [lint(78, 1)], + ); } test_extensionType_nonConstConstructor_primary() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable extension type E(int i) { } -''', [ - lint(59, 1), - ]); +''', + [lint(59, 1)], + ); } test_immutable_constConstructor() async { @@ -176,16 +180,17 @@ class A { } test_immutable_factoryConstructor_toConstConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(); factory C.named() = C; } -''', [ - lint(69, 7), - ]); +''', + [lint(69, 7)], + ); } test_immutable_factoryConstructor_toNonConst() async { @@ -223,28 +228,30 @@ class C with M { } test_immutable_nonConstConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class A { A(); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_immutable_nonConstFactory() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { factory C() = C.named; const C.named(); } -''', [ - lint(56, 7), - ]); +''', + [lint(56, 7)], + ); } test_immutable_nonConstInInitializerList() async { @@ -259,55 +266,59 @@ class C { } test_immutable_nonConstInInitializerList2() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { final int _a; // ignore: unused_field C(int a) : _a = a; } -''', [ - lint(96, 1), - ]); +''', + [lint(96, 1)], + ); } test_immutable_nonConstInInitializerList3() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { final bool _a; // ignore: unused_field C(bool a) : _a = a && a; } -''', [ - lint(97, 1), - ]); +''', + [lint(97, 1)], + ); } test_immutable_nonConstInInitializerList4() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { final String _a; // ignore: unused_field C(bool a) : _a = '${a ? a : ''}'; } -''', [ - lint(99, 1), - ]); +''', + [lint(99, 1)], + ); } test_immutable_nonConstInInitializerList5() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { final bool f; C(bool? f) : f = f ?? f == null; } -''', [ - lint(72, 1), - ]); +''', + [lint(72, 1)], + ); } test_immutable_nonConstInInitializerList6() async { @@ -323,29 +334,31 @@ class C { } test_immutable_redirectingConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { C.a(); C.b() : this.a(); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_immutable_redirectingConstructor_toConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(); C.named(): this(); } -''', [ - lint(69, 1), - ]); +''', + [lint(69, 1)], + ); } test_implementsImmutable() async { @@ -375,7 +388,8 @@ class B implements A { } test_implicitSuperConstructorInvocation_undefined() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable @@ -386,23 +400,31 @@ class A { class B extends A { B(); } -''', [ - error(CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT, - 99, 1), - ]); +''', + [ + error( + CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT, + 99, + 1, + ), + ], + ); } test_macroConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable macro class M { M(); } -''', [ - // TODO(pq): add non-const constructor compilation error when implemented - ]); +''', + [ + // TODO(pq): add non-const constructor compilation error when implemented + ], + ); } test_parameterizedType() async { @@ -421,17 +443,23 @@ class C extends A { } test_returnOfInvalidType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class F { factory F.fc() => null; } -''', [ - // No lint - error( - CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_CONSTRUCTOR, 75, 4), - ]); +''', + [ + // No lint + error( + CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_CONSTRUCTOR, + 75, + 4, + ), + ], + ); } } diff --git a/pkg/linter/test/rules/prefer_const_constructors_test.dart b/pkg/linter/test/rules/prefer_const_constructors_test.dart index cfb8ef8a6808..6e1db2da1ce4 100644 --- a/pkg/linter/test/rules/prefer_const_constructors_test.dart +++ b/pkg/linter/test/rules/prefer_const_constructors_test.dart @@ -21,25 +21,27 @@ class PreferConstConstructorsTest extends LintRuleTest { String get lintRule => LintNames.prefer_const_constructors; test_canBeConst_argumentIsAdjacentStrings() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(String s); } var a = A('adjacent' 'string'); -''', [ - lint(41, 22), - ]); +''', + [lint(41, 22)], + ); } test_canBeConst_argumentIsListLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(List l); } var a = A([]); -''', [ - lint(44, 5), - ]); +''', + [lint(44, 5)], + ); } test_canBeConst_argumentIsMap_nonLiteral() async { @@ -61,36 +63,39 @@ A f(int x) => A({x: x}); } test_canBeConst_argumentIsMapLiteral_instantiated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(Map m); } var a = A({}); -''', [ - lint(48, 5), - ]); +''', + [lint(48, 5)], + ); } test_canBeConst_explicitTypeArgument_dynamic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(); } var a = A(); -''', [ - lint(36, 12), - ]); +''', + [lint(36, 12)], + ); } test_canBeConst_explicitTypeArgument_string() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(); } var a = A(); -''', [ - lint(36, 11), - ]); +''', + [lint(36, 11)], + ); } test_canBeConst_implicitTypeArgument() async { @@ -103,14 +108,15 @@ A f() => A(); } test_canBeConst_implicitTypeArgument_downwardInference() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(); } A f() => A(); -''', [ - lint(42, 3), - ]); +''', + [lint(42, 3)], + ); } test_canBeConst_implicitTypeArgument_inConditional() async { @@ -124,29 +130,32 @@ A f(bool b) => b ? A() : B(); } test_canBeConst_intLiteralArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(int x); } var a = A(5); -''', [ - lint(38, 4), - ]); +''', + [lint(38, 4)], + ); } test_canBeConst_optionalNamedParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A({A? parent}); } var a = A(); -''', [ - lint(44, 3), - ]); +''', + [lint(44, 3)], + ); } test_canBeConst_optionalNamedParameter_nested() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A({A? parent}); const A.a(); @@ -154,21 +163,21 @@ class A { var a = A( parent: A.a(), ); -''', [ - lint(59, 21), - lint(72, 5), - ]); +''', + [lint(59, 21), lint(72, 5)], + ); } test_canBeConst_optionalNamedParameter_newKeyword() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A({A? parent}); } var a = new A(); -''', [ - lint(44, 7), - ]); +''', + [lint(44, 7)], + ); } test_cannotBeConst_argumentIsAdjacentStrings_withInterpolation() async { @@ -314,13 +323,14 @@ void f() { } test_extensionType_constPrimaryConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type const E(int i) {} var e = E(1); -''', [ - lint(42, 4), - ]); +''', + [lint(42, 4)], + ); } test_extensionType_nonConstPrimaryConstructor() async { @@ -332,7 +342,8 @@ var e = E(1); } test_extraPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; class K { @@ -344,10 +355,12 @@ K k() { var kk = K(); return kk; } -''', [ - // No lint - error(WarningCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR, 90, 3), - ]); +''', + [ + // No lint + error(WarningCode.NON_CONST_CALL_TO_LITERAL_CONSTRUCTOR, 90, 3), + ], + ); } test_isConst_intLiteralArgument() async { diff --git a/pkg/linter/test/rules/prefer_const_declarations_test.dart b/pkg/linter/test/rules/prefer_const_declarations_test.dart index 192c27b69130..c9d8566244d4 100644 --- a/pkg/linter/test/rules/prefer_const_declarations_test.dart +++ b/pkg/linter/test/rules/prefer_const_declarations_test.dart @@ -18,25 +18,27 @@ class PreferConstDeclarationsTest extends LintRuleTest { String get lintRule => LintNames.prefer_const_declarations; test_constructorTearoff_inference() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final C Function() c = C.new; } class C {} -''', [ - lint(13, 33), - ]); +''', + [lint(13, 33)], + ); } test_constructorTearoff_instantiatedWithType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final c = C.new; } class C {} -''', [ - lint(13, 20), - ]); +''', + [lint(13, 20)], + ); } @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/2911') @@ -50,14 +52,15 @@ class C {} } test_constructorTearoff_uninstantiated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = C.new; } class C {} -''', [ - lint(13, 15), - ]); +''', + [lint(13, 15)], + ); } test_instanceField_final_listLiteral_const() async { @@ -77,16 +80,17 @@ void f() { } test_localVariable_final_constructorInvocation_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = const C(); } class C { const C(); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_localVariable_final_constructorInvocation_new() async { @@ -101,23 +105,25 @@ class C { } test_localVariable_final_doubleLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = 1.3; } -''', [ - lint(13, 13), - ]); +''', + [lint(13, 13)], + ); } test_localVariable_final_intLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = 1; } -''', [ - lint(13, 11), - ]); +''', + [lint(13, 11)], + ); } test_localVariable_final_intLiteral_multiple() async { @@ -138,23 +144,25 @@ void f() { } test_localVariable_final_listLiteral_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = const []; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_localVariable_final_mapOrSetLiteral_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = const {}; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_localVariable_final_methodInvocation() async { @@ -166,13 +174,14 @@ void f() { } test_localVariable_final_nullLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = null; } -''', [ - lint(13, 14), - ]); +''', + [lint(13, 14)], + ); } test_localVariable_final_prefixedIdentifier() async { @@ -184,7 +193,8 @@ void f() { } test_localVariable_final_staticProperty_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = C.p; } @@ -192,19 +202,20 @@ class C { const C(); static const p = const []; } -''', [ - lint(13, 13), - ]); +''', + [lint(13, 13)], + ); } test_localVariable_final_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = ''; } -''', [ - lint(13, 12), - ]); +''', + [lint(13, 12)], + ); } test_localVariable_listLiteral_final_typed() async { @@ -280,11 +291,12 @@ void f() { } test_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final tuple = const ("first", 2, true); -''', [ - lint(0, 38), - ]); +''', + [lint(0, 38)], + ); } test_staticField_const_listLiteral_const() async { @@ -296,59 +308,64 @@ class C { } test_staticField_final_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static final x = const []; } -''', [ - lint(19, 18), - ]); +''', + [lint(19, 18)], + ); } test_staticField_final_listLiteral_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static final x = const []; } -''', [ - lint(19, 18), - ]); +''', + [lint(19, 18)], + ); } test_staticField_final_nullLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static final x = null; } -''', [ - lint(19, 14), - ]); +''', + [lint(19, 14)], + ); } test_staticFunctionTearoff_inference() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final C Function() c = C.m; } class C { static C m() => C(); } -''', [ - lint(13, 31), - ]); +''', + [lint(13, 31)], + ); } test_staticFunctionTearoff_instantiatedWithType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final c = C.m; } class C { static C m() => C(); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_staticFunctionTearoff_instantiatedWithTypeVariable() async { @@ -363,16 +380,17 @@ class C { } test_staticFunctionTearoff_uninstantiated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = C.m; } class C { static C m() => C(); } -''', [ - lint(13, 13), - ]); +''', + [lint(13, 13)], + ); } test_test_recordLiteral_nonConst() async { @@ -388,11 +406,12 @@ const record = (number: 123, name: "Main", type: "Street"); } test_topLevelVariable_final_doubleLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final x = 1.3; -''', [ - lint(0, 13), - ]); +''', + [lint(0, 13)], + ); } test_topLevelVariable_final_listLiteral() async { @@ -402,11 +421,12 @@ final x = []; } test_topLevelVariable_final_listLiteral_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final x = const []; -''', [ - lint(0, 18), - ]); +''', + [lint(0, 18)], + ); } test_topLevelVariable_final_mapOrSetLiteral() async { @@ -416,28 +436,31 @@ final o9 = {}; } test_topLevelVariable_final_mapOrSetLiteral_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final x = const {}; -''', [ - lint(0, 18), - ]); +''', + [lint(0, 18)], + ); } test_topLevelVariable_final_nullLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = null; -''', [ - lint(0, 14), - ]); +''', + [lint(0, 14)], + ); } test_topLevelVariable_final_topLevelVariable_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const x = const []; final y = x; -''', [ - lint(20, 11), - ]); +''', + [lint(20, 11)], + ); } test_topLevelVariable_listLiteral_const() async { diff --git a/pkg/linter/test/rules/prefer_const_literals_to_create_immutables_test.dart b/pkg/linter/test/rules/prefer_const_literals_to_create_immutables_test.dart index 12c5e99ba072..41a1ceab3245 100644 --- a/pkg/linter/test/rules/prefer_const_literals_to_create_immutables_test.dart +++ b/pkg/linter/test/rules/prefer_const_literals_to_create_immutables_test.dart @@ -40,16 +40,17 @@ int e() => 7; } test_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable extension type E(List i) { } var e = E([1]); -''', [ - lint(90, 3), - ]); +''', + [lint(90, 3)], + ); } test_listLiteral_const() async { @@ -77,7 +78,8 @@ var x = C(const [ } test_listLiteral_nested_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { @@ -86,23 +88,23 @@ class C { var x = C([ [], ]); -''', [ - lint(93, 9), - lint(97, 2), - ]); +''', + [lint(93, 9), lint(97, 2)], + ); } test_listLiteral_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(List p); } var x = C([]); -''', [ - lint(93, 2), - ]); +''', + [lint(93, 2)], + ); } test_listLiteral_notConstable_noConst() async { @@ -140,98 +142,106 @@ var x = C(((const {}))); } test_mapLiteral_inParens_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Object? p); } var x = C((({}))); -''', [ - lint(90, 2), - ]); +''', + [lint(90, 2)], + ); } test_mapLiteral_intToDouble_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Map p); } var x = C({1: 1.0}); -''', [ - lint(98, 8), - ]); +''', + [lint(98, 8)], + ); } test_mapLiteral_intToInstantiation_const() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Object? p); } var x = C({1: const C(null)}); -''', [ - lint(88, 18), - ]); +''', + [lint(88, 18)], + ); } test_mapLiteral_intToInt_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Map p); } var x = C({1: 1}); -''', [ - lint(98, 6), - ]); +''', + [lint(98, 6)], + ); } test_mapLiteral_intToNull_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Map p); } var x = C({1: null}); -''', [ - lint(98, 9), - ]); +''', + [lint(98, 9)], + ); } test_mapLiteral_intToString_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Map p); } var x = C({1: ''}); -''', [ - lint(98, 7), - ]); +''', + [lint(98, 7)], + ); } test_mapLiteral_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C(Map p); } var x = C({1: 2}); -''', [ - lint(94, 6), - ]); +''', + [lint(94, 6)], + ); } test_missingRequiredArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable @@ -243,32 +253,38 @@ class K { final k = K( children: [for (var i = 0; i < 5; ++i) K()], // OK ); -''', [ - // No lint - error(CompileTimeErrorCode.MISSING_REQUIRED_ARGUMENT, 178, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.MISSING_REQUIRED_ARGUMENT, 178, 1), + ], + ); } test_namedParameter_noConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @immutable class C { const C({Object? p}); } var x = C(p: []); -''', [ - lint(93, 2), - ]); +''', + [lint(93, 2)], + ); } test_newWithNonType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var e1 = new B([]); // OK -''', [ - // No lint - error(CompileTimeErrorCode.NEW_WITH_NON_TYPE, 13, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.NEW_WITH_NON_TYPE, 13, 1), + ], + ); } test_notImmutable_noConst() async { diff --git a/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart b/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart index 7e40ffbb5871..f6e7c3dec61b 100644 --- a/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart +++ b/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart @@ -40,37 +40,40 @@ class A { } test_staticGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named(); static A get getter => A.named(); } -''', [ - lint(38, 6), - ]); +''', + [lint(38, 6)], + ); } test_staticMethod_expressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named(); static A staticM() => A.named(); } -''', [ - lint(34, 7), - ]); +''', + [lint(34, 7)], + ); } test_staticMethod_expressionBody_extensionType() async { // Since the check logic is shared, one test should be sufficient to verify // extension types are supported. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { static E make(int i) => E(i); } -''', [ - lint(37, 4), - ]); +''', + [lint(37, 4)], + ); } test_staticMethod_generic() async { @@ -83,7 +86,8 @@ class A { } test_staticMethod_referenceToConstructedInstanceOfClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named(); static A instanceM() { @@ -91,9 +95,9 @@ class A { return a; } } -''', [ - lint(34, 9), - ]); +''', + [lint(34, 9)], + ); } test_staticMethod_referenceToExistingInstanceOfClass() async { diff --git a/pkg/linter/test/rules/prefer_contains_test.dart b/pkg/linter/test/rules/prefer_contains_test.dart index 604e30ec8c88..70f18df043bf 100644 --- a/pkg/linter/test/rules/prefer_contains_test.dart +++ b/pkg/linter/test/rules/prefer_contains_test.dart @@ -18,36 +18,41 @@ class PreferContainsTest extends LintRuleTest { String get lintRule => LintNames.prefer_contains; test_argumentTypeNotAssignable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List list = []; condition() { var next; while ((next = list.indexOf('{')) != -1) {} } -''', [ - // No lint - error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 77, 3), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 77, 3), + ], + ); } test_list_indexOf_greaterThan_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.indexOf(1) > -1; } -''', [ - lint(27, 20), - ]); +''', + [lint(27, 20)], + ); } test_list_indexOf_notEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.indexOf(1) != -1; } -''', [ - lint(27, 21), - ]); +''', + [lint(27, 21)], + ); } test_listConcatenation_indexOfWithDifferentArguments() async { @@ -59,23 +64,25 @@ void f(List list) { } test_listLiteral_indexOf_equalEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) == -1; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_equalEqual_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) == -2; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_equalEqual_zero() async { @@ -87,53 +94,58 @@ void f() { } test_listLiteral_indexOf_greater_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) > -2; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_listLiteral_indexOf_greaterOr_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) >= -2; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_greaterOrEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) >= -1; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_greaterOrEqual_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) >= 0; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_listLiteral_indexOf_greaterThan_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) > -1; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_listLiteral_indexOf_greaterThan_one() async { @@ -153,23 +165,25 @@ void f() { } test_listLiteral_indexOf_lessOrEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) <= -1; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_lessOrEqual_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) <= -2; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_lessOrEqual_zero() async { @@ -181,64 +195,70 @@ void f() { } test_listLiteral_indexOf_lessThan_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) < -1; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_listLiteral_indexOf_lessThan_negativeOneConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const int MINUS_ONE = -1; void f() { [].indexOf(1) < MINUS_ONE; } -''', [ - lint(39, 25), - ]); +''', + [lint(39, 25)], + ); } test_listLiteral_indexOf_lessThan_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) < -2; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_listLiteral_indexOf_lessThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) < 0; } -''', [ - lint(13, 17), - ]); +''', + [lint(13, 17)], + ); } test_listLiteral_indexOf_notEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) != -1; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_notEqual_negativeTwo() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [].indexOf(1) != -2; } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_listLiteral_indexOf_notEqual_zero() async { @@ -250,164 +270,180 @@ void f() { } test_listTypedef_indexOf_equalEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef F = List; void f(F list) { list.indexOf(1) == -1; } -''', [ - lint(42, 21), - ]); +''', + [lint(42, 21)], + ); } test_negativeOne_equalEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 == [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeOne_greaterOrEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 >= [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeOne_greaterThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 > [].indexOf(1); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_negativeOne_lessOrEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 <= [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeOne_lessThan_list_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { -1 < list.indexOf(1); } -''', [ - lint(27, 20), - ]); +''', + [lint(27, 20)], + ); } test_negativeOne_lessThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 < [].indexOf(1); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_negativeOne_notEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -1 != [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeOneConst_lessThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const int MINUS_ONE = -1; void f() { MINUS_ONE < [].indexOf(1); } -''', [ - lint(39, 25), - ]); +''', + [lint(39, 25)], + ); } test_negativeTwo_equalEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 == [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeTwo_greaterOrEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 >= [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeTwo_greaterThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 > [].indexOf(1); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_negativeTwo_lessOrEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 <= [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_negativeTwo_lessThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 < [].indexOf(1); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_negativeTwo_notEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { -2 != [].indexOf(1); } -''', [ - lint(13, 19), - ]); +''', + [lint(13, 19)], + ); } test_promotedToList_indexOf_lessThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f(T list) => list is List && list.indexOf(1) < 0; -''', [ - lint(44, 19), - ]); +''', + [lint(44, 19)], + ); } /// https://github.com/dart-lang/linter/issues/3546 @@ -419,21 +455,23 @@ bool b = '11'.indexOf('2', 1) == -1; /// https://github.com/dart-lang/linter/issues/3546 test_secondArgZero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool b = '11'.indexOf('2', 0) == -1; -''', [ - lint(9, 26), - ]); +''', + [lint(9, 26)], + ); } test_stringLiteral_indexOf_equalEqual_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { 'aaa'.indexOf('a') == -1; } -''', [ - lint(13, 24), - ]); +''', + [lint(13, 24)], + ); } test_stringLiteral_indexOf_twoArguments() async { @@ -445,21 +483,22 @@ void f() { } test_typeVariableExtendingList_indexOf_lessThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f>(T list) => list.indexOf(1) < 0; -''', [ - lint(41, 19), - ]); +''', + [lint(41, 19)], + ); } test_unnecessaryCast() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool le3 = ([].indexOf(1) as int) > -1; -''', [ - lint(11, 27), - error(WarningCode.UNNECESSARY_CAST, 12, 20), - ]); +''', + [lint(11, 27), error(WarningCode.UNNECESSARY_CAST, 12, 20)], + ); } test_zero_equalEqual_listLiteral_indexOf() async { @@ -479,23 +518,25 @@ void f() { } test_zero_greaterThan_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { 0 > [].indexOf(1); } -''', [ - lint(13, 17), - ]); +''', + [lint(13, 17)], + ); } test_zero_lessOrEqual_listLiteral_indexOf() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { 0 <= [].indexOf(1); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_zero_lessThan_listLiteral_indexOf() async { diff --git a/pkg/linter/test/rules/prefer_double_quotes_test.dart b/pkg/linter/test/rules/prefer_double_quotes_test.dart index 54246f6845d7..8458b67eafd3 100644 --- a/pkg/linter/test/rules/prefer_double_quotes_test.dart +++ b/pkg/linter/test/rules/prefer_double_quotes_test.dart @@ -50,11 +50,12 @@ var s = "foo ${x == 'x'} bar"; } test_singleQuote() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = 'no quote'; -''', [ - lint(8, 10), - ]); +''', + [lint(8, 10)], + ); } test_singleQuote_hasDoubleQuote_withInterpolation() async { @@ -71,11 +72,12 @@ var s = 'has double quote "'; } test_singleQuote_raw() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = r'no double quote'; -''', [ - lint(8, 18), - ]); +''', + [lint(8, 18)], + ); } test_singleQuote_raw_hasDoubleQuotes() async { @@ -85,11 +87,12 @@ var s = r'has double quote "'; } test_singleQuote_triple_raw() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var s = r'''no double quote'''; -""", [ - lint(8, 22), - ]); +""", + [lint(8, 22)], + ); } test_singleQuote_triple_raw_hasDouble() async { @@ -99,12 +102,13 @@ var s = r'''has double quote "'''; } test_singleQuote_withInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = "x"; var s = 'no double quote $x'; -''', [ - lint(21, 20), - ]); +''', + [lint(21, 20)], + ); } test_singleQuote_withInterpolationWithDoubleQuotes() async { diff --git a/pkg/linter/test/rules/prefer_expression_function_bodies_test.dart b/pkg/linter/test/rules/prefer_expression_function_bodies_test.dart index c32d6215061a..edb024a60d2e 100644 --- a/pkg/linter/test/rules/prefer_expression_function_bodies_test.dart +++ b/pkg/linter/test/rules/prefer_expression_function_bodies_test.dart @@ -27,13 +27,14 @@ int f() { } test_function_returnStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int f() { return 1; } -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_getter_expressionFunctionBody() async { @@ -45,15 +46,16 @@ class A { } test_getter_returnStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { get f { return 7 - 6; } } -''', [ - lint(18, 23), - ]); +''', + [lint(18, 23)], + ); } test_method_multipleStatements() async { @@ -70,15 +72,16 @@ class A { } test_method_returnStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int m() { return 1; } } -''', [ - lint(20, 19), - ]); +''', + [lint(20, 19)], + ); } test_setter_expressionFunctionBody() async { diff --git a/pkg/linter/test/rules/prefer_final_fields_test.dart b/pkg/linter/test/rules/prefer_final_fields_test.dart index fd99ac174eef..8fe97d52f742 100644 --- a/pkg/linter/test/rules/prefer_final_fields_test.dart +++ b/pkg/linter/test/rules/prefer_final_fields_test.dart @@ -20,40 +20,50 @@ class PreferFinalFieldsExtensionTypesTest extends LintRuleTest { String get lintRule => LintNames.prefer_final_fields; test_field_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { int _i = 0; } -''', [ - // No Lint. - error(CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, 35, 2), - error(WarningCode.UNUSED_FIELD, 35, 2), - ]); +''', + [ + // No Lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, + 35, + 2, + ), + error(WarningCode.UNUSED_FIELD, 35, 2), + ], + ); } test_field_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { static int _i = 0; } -''', [ - error(WarningCode.UNUSED_FIELD, 42, 2), - lint(42, 6), - ]); +''', + [error(WarningCode.UNUSED_FIELD, 42, 2), lint(42, 6)], + ); } test_field_static_writtenInConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { static Object _o = 0; E.e(this.o) { _o = o; } } -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 45, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 45, 2), + ], + ); } } @@ -61,22 +71,23 @@ extension type E(Object o) { class PreferFinalFieldsTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.prefer_final_fields; test_assignedInConstructorInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x; C() : _x = 7; } -''', [ - lint(16, 2), - ]); +''', + [lint(16, 2)], + ); } test_assignedInConstructorInitializer_butNotAll() async { @@ -146,16 +157,19 @@ int f(C c) { } test_enum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; int _x = 0; int get x => _x; } -''', [ - // No Lint. - error(CompileTimeErrorCode.NON_FINAL_FIELD_IN_ENUM, 24, 2), - ]); +''', + [ + // No Lint. + error(CompileTimeErrorCode.NON_FINAL_FIELD_IN_ENUM, 24, 2), + ], + ); } test_final_multiple() async { @@ -175,7 +189,8 @@ class C { } test_indexAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var _x = []; @@ -183,9 +198,9 @@ class C { _x[0] = 3; } } -''', [ - lint(16, 7), - ]); +''', + [lint(16, 7)], + ); } test_overrideField_extends() async { @@ -320,46 +335,50 @@ class C { } test_prefixExpression_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { bool _x = false; void f() { !_x; } } -''', [ - lint(17, 10), - ]); +''', + [lint(17, 10)], + ); } test_prefixExpression_tilde() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x = 0xffff; void f() { ~_x; } } -''', [ - lint(16, 11), - ]); +''', + [lint(16, 11)], + ); } test_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x = 1; void f() { _x.isEven; } } -''', [ - lint(16, 6), - ]); +''', + [lint(16, 6)], + ); } test_readInInstanceMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x = 0; @@ -367,9 +386,9 @@ class C { var a = _x; } } -''', [ - lint(16, 6), - ]); +''', + [lint(16, 6)], + ); } test_reassigned() async { @@ -384,15 +403,16 @@ class C { } test_referencedInFieldFormalParameters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int _x; C(this._x); C.named(this._x); } -''', [ - lint(16, 2), - ]); +''', + [lint(16, 2)], + ); } test_subclassOnGenericClass() async { @@ -410,26 +430,28 @@ class D extends C { } test_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var _x = 1; } -''', [ - lint(16, 6), - ]); +''', + [lint(16, 6)], + ); } test_unused_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var _x = 1, _y = 2; void f() { _x = 2; } } -''', [ - lint(24, 6), - ]); +''', + [lint(24, 6)], + ); } test_unused_public() async { diff --git a/pkg/linter/test/rules/prefer_final_in_for_each_test.dart b/pkg/linter/test/rules/prefer_final_in_for_each_test.dart index 110975861b50..19ab0912b68f 100644 --- a/pkg/linter/test/rules/prefer_final_in_for_each_test.dart +++ b/pkg/linter/test/rules/prefer_final_in_for_each_test.dart @@ -18,13 +18,14 @@ class PreferFinalInForEachTestLanguage300 extends LintRuleTest { String get lintRule => LintNames.prefer_final_in_for_each; test_int() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var i in [1, 2, 3]) { } } -''', [ - lint(17, 1), - ]); +''', + [lint(17, 1)], + ); } test_int_final_ok() async { @@ -46,13 +47,14 @@ f() { } test_list() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var [i, j] in [[1, 2]]) { } } -''', [ - lint(17, 6), - ]); +''', + [lint(17, 6)], + ); } test_list_final() async { @@ -75,13 +77,14 @@ f() { /// https://github.com/dart-lang/linter/issues/4353 test_listLiteral_forEach() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f() => [ for (var i in [1, 2]) i + 3 ]; -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_listLiteral_forEach_mutated() async { @@ -93,13 +96,14 @@ List f() => [ } test_map() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var {'i' : j} in [{'i' : 1}]) { } } -''', [ - lint(17, 9), - ]); +''', + [lint(17, 9)], + ); } test_map_final() async { @@ -121,7 +125,8 @@ f() { } test_object() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -130,9 +135,9 @@ class A { f() { for (var A(:a) in [A(1)]) { } } -''', [ - lint(52, 5), - ]); +''', + [lint(52, 5)], + ); } test_object_final() async { @@ -173,13 +178,14 @@ f() { } test_record() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var (i, j) in [(1, 2)]) { } } -''', [ - lint(17, 6), - ]); +''', + [lint(17, 6)], + ); } test_record_final() async { diff --git a/pkg/linter/test/rules/prefer_final_locals_test.dart b/pkg/linter/test/rules/prefer_final_locals_test.dart index 4cf69a952bc5..47fe7f6e61c4 100644 --- a/pkg/linter/test/rules/prefer_final_locals_test.dart +++ b/pkg/linter/test/rules/prefer_final_locals_test.dart @@ -18,13 +18,14 @@ class PreferFinalLocalsTest extends LintRuleTest { String get lintRule => LintNames.prefer_final_locals; test_destructured_listPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [a, b] = ['a', 'b']; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_listPattern_final() async { @@ -45,23 +46,25 @@ f() { } test_destructured_listPattern_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [_, b] = ['a', 'b']; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_listPattern_wildcard_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [(_), b] = ['a', 'b']; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_listPattern_wildcard_single() async { @@ -81,13 +84,14 @@ f() { } test_destructured_listPatternWithRest() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var [a, b, ...rest] = [1, 2, 3, 4, 5, 6, 7]; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_listPatternWithRest_mutated() async { @@ -100,13 +104,14 @@ f() { } test_destructured_mapPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var {'first': a, 'second': b} = {'first': 1, 'second': 2}; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_mapPattern_final() async { @@ -127,13 +132,14 @@ f() { } test_destructured_mapPattern_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var {'first': a, 'second': _} = {'first': 1, 'second': 2}; } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_mapPattern_wildcard_single() async { @@ -145,7 +151,8 @@ f() { } test_destructured_objectPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -153,9 +160,9 @@ class A { f() { var A(a: b) = A(1); } -''', [ - lint(42, 3), - ]); +''', + [lint(42, 3)], + ); } test_destructured_objectPattern_final() async { @@ -196,7 +203,8 @@ f() { } test_destructured_objectPattern_wildcard_multipleFields() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a, b; A(this.a, this.b); @@ -204,9 +212,9 @@ class A { f() { var A(a: x, b: _) = A(1, 2); } -''', [ - lint(53, 3), - ]); +''', + [lint(53, 3)], + ); } test_destructured_parenthesizedPattern_wildcard() async { @@ -218,13 +226,14 @@ f() { } test_destructured_recordPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var (a, b) = ('a', 'b'); } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_recordPattern_final() async { @@ -236,14 +245,14 @@ f() { } test_destructured_recordPattern_forLoop() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var (a, b) in [(1, 2)]) { } } -''', [ - lint(18, 1), - lint(21, 1), - ]); +''', + [lint(18, 1), lint(21, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4286 @@ -267,13 +276,14 @@ f() { } test_destructured_recordPattern_forLoop_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var (_, b) in [(1, 2)]) { } } -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_destructured_recordPattern_mutated() async { @@ -286,13 +296,14 @@ f() { } test_destructured_recordPattern_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var (_, b) = ('a', 'b'); } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_destructured_recordPattern_wildcard_multipleWildcards() async { @@ -304,13 +315,14 @@ f() { } test_destructured_recordPattern_withParenthesizedPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var ((a, b)) = ('a', 'b'); } -''', [ - lint(8, 3), - ]); +''', + [lint(8, 3)], + ); } test_field() async { @@ -322,13 +334,14 @@ class C { } test_ifPatternList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case [int x, final int y]) x; } -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_ifPatternList_final() async { @@ -340,23 +353,25 @@ f(Object o) { } test_ifPatternList_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case [int x, int _]) x; } -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_ifPatternMap() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case {'x': var x}) print('$x'); } -''', [ - lint(33, 5), - ]); +''', + [lint(33, 5)], + ); } test_ifPatternMap_final() async { @@ -376,7 +391,8 @@ f(Object o) { } test_ifPatternObject() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int c; C(this.c); @@ -385,9 +401,9 @@ class C { f(Object o) { if (o case C(c: var x)) x; } -''', [ - lint(67, 5), - ]); +''', + [lint(67, 5)], + ); } test_ifPatternObject_final() async { @@ -417,14 +433,14 @@ f(Object o) { } test_ifPatternRecord() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (int x, int y)) x; } -''', [ - lint(28, 5), - lint(35, 5), - ]); +''', + [lint(28, 5), lint(35, 5)], + ); } test_ifPatternRecord_final() async { @@ -436,13 +452,14 @@ f(Object o) { } test_ifPatternRecord_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (int x, int _)) x; } -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_nonDeclaration_destructured_recordPattern() async { @@ -463,38 +480,41 @@ void f() { } test_notReassigned_withType_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { String a = 'hello', b = 'world'; print(a); print(b); } -''', [ - lint(13, 6), - ]); +''', + [lint(13, 6)], + ); } test_notReassigned_withVar() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var a = ''; print(a); } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_notReassigned_withVar_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var a = 'hello', b = 'world'; print(a); print(b); } -''', [ - lint(13, 3), - ]); +''', + [lint(13, 3)], + ); } test_notReassigned_withVar_wildcard() async { @@ -524,7 +544,8 @@ void f() { } test_switch_objectPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -535,9 +556,9 @@ f() { case A(a: >0 && var b): b; } } -''', [ - lint(79, 5), - ]); +''', + [lint(79, 5)], + ); } test_switch_objectPattern_final() async { @@ -571,7 +592,8 @@ f() { } test_switch_objectPattern_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -582,23 +604,25 @@ f() { case A(a: >0 && var _): print(''); } } -''', [ - // No lint. - error(WarningCode.UNNECESSARY_WILDCARD_PATTERN, 83, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNNECESSARY_WILDCARD_PATTERN, 83, 1), + ], + ); } test_switch_recordPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ((1, 2)) { case (var a, int b): a; } } -''', [ - lint(36, 5), - lint(43, 5), - ]); +''', + [lint(36, 5), lint(43, 5)], + ); } test_switch_recordPattern_final() async { @@ -622,15 +646,16 @@ f() { } test_switch_recordPattern_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ((1, 2)) { case (var a, int _): a; } } -''', [ - lint(36, 5), - ]); +''', + [lint(36, 5)], + ); } test_wildcardLocal() async { diff --git a/pkg/linter/test/rules/prefer_final_parameters_test.dart b/pkg/linter/test/rules/prefer_final_parameters_test.dart index 84186b4fdc63..81ae585f37e4 100644 --- a/pkg/linter/test/rules/prefer_final_parameters_test.dart +++ b/pkg/linter/test/rules/prefer_final_parameters_test.dart @@ -27,13 +27,14 @@ void f(String p) { } test_closure() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = (Object p) { print(p); }; -''', [ - lint(9, 8), - ]); +''', + [lint(9, 8)], + ); } test_closure_final() async { @@ -53,13 +54,14 @@ void f(final List x) { } test_closure_untyped() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(final List x) { x.forEach((e) => print(e + 4)); } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_closure_wildcard() async { @@ -77,27 +79,29 @@ class C { } test_constructor_usedInBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x = 0; C(String p) { x = p.length; } } -''', [ - lint(27, 8), - ]); +''', + [lint(27, 8)], + ); } test_constructor_usedInInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String x = ''; C(String x): this.x = x; } -''', [ - lint(31, 8), - ]); +''', + [lint(31, 8)], + ); } test_constructor_usedInInitializer_final() async { @@ -151,15 +155,16 @@ void f(int p) { } test_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(String p) { print(p); } } -''', [ - lint(19, 8), - ]); +''', + [lint(19, 8)], + ); } test_method_final() async { @@ -189,15 +194,16 @@ class C { } test_operator() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C operator +(C other) { return other; } } -''', [ - lint(25, 7), - ]); +''', + [lint(25, 7)], + ); } test_operator_final() async { @@ -229,14 +235,15 @@ void f(int a, int b) { } test_setter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x = 0; void set f(int y) => x = y; } -''', [ - lint(36, 5), - ]); +''', + [lint(36, 5)], + ); } test_setter_final() async { @@ -282,11 +289,12 @@ class B extends A { } test_topLevelFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) => print(p); -''', [ - lint(7, 5), - ]); +''', + [lint(7, 5)], + ); } test_topLevelFunction_final() async { @@ -305,13 +313,14 @@ void f(final String p, final String p2) { } test_topLevelFunction_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({String? p}) { print(p); } -''', [ - lint(8, 9), - ]); +''', + [lint(8, 9)], + ); } test_topLevelFunction_named_final() async { @@ -323,23 +332,27 @@ void f({final String? p}) { } test_topLevelFunction_named_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({final String? _}) { } -''', [ - // No lint. - // https://github.com/dart-lang/language/blob/main/working/wildcards/feature-specification.md#declarations-that-are-capable-of-declaring-a-wildcard - error(CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, 22, 1), - ]); +''', + [ + // No lint. + // https://github.com/dart-lang/language/blob/main/working/wildcards/feature-specification.md#declarations-that-are-capable-of-declaring-a-wildcard + error(CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, 22, 1), + ], + ); } test_topLevelFunction_namedRequired() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({required String p}) { print(p); } -''', [ - lint(8, 17), - ]); +''', + [lint(8, 17)], + ); } test_topLevelFunction_namedRequired_final() async { @@ -351,23 +364,27 @@ void f({required final String p}) { } test_topLevelFunction_namedRequired_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({required String _}) { } -''', [ - // No lint. - // https://github.com/dart-lang/language/blob/main/working/wildcards/feature-specification.md#declarations-that-are-capable-of-declaring-a-wildcard - error(CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, 24, 1), - ]); +''', + [ + // No lint. + // https://github.com/dart-lang/language/blob/main/working/wildcards/feature-specification.md#declarations-that-are-capable-of-declaring-a-wildcard + error(CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER, 24, 1), + ], + ); } test_topLevelFunction_optional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f([String? p]) { print(p); } -''', [ - lint(8, 9), - ]); +''', + [lint(8, 9)], + ); } test_topLevelFunction_optional_final() async { diff --git a/pkg/linter/test/rules/prefer_for_elements_to_map_fromIterable_test.dart b/pkg/linter/test/rules/prefer_for_elements_to_map_fromIterable_test.dart index f205c72eb3ad..20f03201796c 100644 --- a/pkg/linter/test/rules/prefer_for_elements_to_map_fromIterable_test.dart +++ b/pkg/linter/test/rules/prefer_for_elements_to_map_fromIterable_test.dart @@ -22,33 +22,36 @@ class PreferForElementsToMapFromIterableTest extends LintRuleTest { String get lintRule => LintNames.prefer_for_elements_to_map_fromIterable; test_hasKeyAndValue_closuresAreSimple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Iterable i) { Map.fromIterable(i, key: (k) => k * 2, value: (v) => 0); } -''', [ - lint(28, 55), - ]); +''', + [lint(28, 55)], + ); } test_hasKeyAndValue_closuresReferenceE() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Iterable i, int e) { Map.fromIterable(i, key: (k) => k * e, value: (v) => v + e); } -''', [ - lint(35, 59), - ]); +''', + [lint(35, 59)], + ); } test_hasKeyAndValue_closuresShadowVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Iterable i, int k) { Map.fromIterable(i, key: (k) => k * 2, value: (v) => k); } -''', [ - lint(35, 55), - ]); +''', + [lint(35, 55)], + ); } test_missingKey() async { diff --git a/pkg/linter/test/rules/prefer_foreach_test.dart b/pkg/linter/test/rules/prefer_foreach_test.dart index 6e1ba74e6228..250101f34d31 100644 --- a/pkg/linter/test/rules/prefer_foreach_test.dart +++ b/pkg/linter/test/rules/prefer_foreach_test.dart @@ -20,19 +20,21 @@ class PreferForeachTest extends LintRuleTest { String get lintRule => LintNames.prefer_foreach; test_blockBody_singleStatement_functionCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list, void Function(int) fn) { for (final a in list) { fn(a); } } -''', [ - lint(50, 38), - ]); +''', + [lint(50, 38)], + ); } test_blockBody_singleStatement_functionTypedExpressionCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(int) fn() => (int a) {}; void f(List list) { @@ -40,13 +42,14 @@ void f(List list) { fn()(a); } } -''', [ - lint(67, 40), - ]); +''', + [lint(67, 40)], + ); } test_blockBody_singleStatement_methodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void f(int o) {} @@ -56,13 +59,14 @@ class C { } } } -''', [ - lint(63, 41), - ]); +''', + [lint(63, 41)], + ); } test_blockBody_singleStatement_methodCall_explicitTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(D d, List list) { for (final a in list) { d.f(a); @@ -71,9 +75,9 @@ void f(D d, List list) { class D { void f(int a) {} } -''', [ - lint(32, 39), - ]); +''', + [lint(32, 39)], + ); } test_blockBody_singleStatement_methodCall_forVariableIsInTarget() async { @@ -103,19 +107,21 @@ class D { } test_blockBody_singleStatement_parenthesizedFunctionCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list, void Function(int) fn) { for (final a in list) { (fn(a)); } } -''', [ - lint(50, 40), - ]); +''', + [lint(50, 40)], + ); } test_blockBody_singleStatement_staticMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { for (final a in list) { C.f(a); @@ -124,8 +130,8 @@ void f(List list) { class C { static void f(int a) {} } -''', [ - lint(27, 39), - ]); +''', + [lint(27, 39)], + ); } } diff --git a/pkg/linter/test/rules/prefer_function_declarations_over_variables_test.dart b/pkg/linter/test/rules/prefer_function_declarations_over_variables_test.dart index 86a9d96a0f31..cdde9c3e3779 100644 --- a/pkg/linter/test/rules/prefer_function_declarations_over_variables_test.dart +++ b/pkg/linter/test/rules/prefer_function_declarations_over_variables_test.dart @@ -18,13 +18,14 @@ class PreferFunctionDeclarationsOverVariablesTest extends LintRuleTest { String get lintRule => LintNames.prefer_function_declarations_over_variables; test_instanceVariable_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final f = () {}; } -''', [ - lint(18, 9), - ]); +''', + [lint(18, 9)], + ); } test_instanceVariable_public() async { @@ -45,13 +46,14 @@ void f() { } test_localVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var g = () {}; } -''', [ - lint(17, 9), - ]); +''', + [lint(17, 9)], + ); } test_localVariable_nonFunctionLiteral() async { @@ -72,11 +74,12 @@ void f() { } test_topLevelVariable_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final f = () {}; -''', [ - lint(6, 9), - ]); +''', + [lint(6, 9)], + ); } test_topLevelVariable_public() async { diff --git a/pkg/linter/test/rules/prefer_generic_function_type_aliases_test.dart b/pkg/linter/test/rules/prefer_generic_function_type_aliases_test.dart index 816026c2289d..b3afc88b5799 100644 --- a/pkg/linter/test/rules/prefer_generic_function_type_aliases_test.dart +++ b/pkg/linter/test/rules/prefer_generic_function_type_aliases_test.dart @@ -17,10 +17,13 @@ class PreferGenericFunctionTypeAliasesTest extends LintRuleTest { @override String get lintRule => LintNames.prefer_generic_function_type_aliases; - @FailingTest(reason: ''' + @FailingTest( + reason: ''' ParserErrorCode.EXTRANEOUS_MODIFIER [27, 7, Can't have modifier 'augment' here.] CompileTimeErrorCode.DUPLICATE_DEFINITION [48, 1, The name 'F' is already defined.] -''', issue: 'https://github.com/dart-lang/linter/issues/4942') +''', + issue: 'https://github.com/dart-lang/linter/issues/4942', + ) test_augmentedTypeAlias() async { newFile('$testPackageLibPath/a.dart', r''' part 'test.dart'; @@ -36,11 +39,12 @@ augment typedef void F(); } test_classicTypedef() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef void F(); -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_genericFunctionType() async { @@ -51,12 +55,15 @@ typedef F = void Function(); /// https://github.com/dart-lang/linter/issues/2777 test_undefinedFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef Cb2 -''', [ - // No lint - error(ParserErrorCode.EXPECTED_TOKEN, 8, 3), - error(ParserErrorCode.MISSING_TYPEDEF_PARAMETERS, 12, 0), - ]); +''', + [ + // No lint + error(ParserErrorCode.EXPECTED_TOKEN, 8, 3), + error(ParserErrorCode.MISSING_TYPEDEF_PARAMETERS, 12, 0), + ], + ); } } diff --git a/pkg/linter/test/rules/prefer_if_elements_to_conditional_expressions_test.dart b/pkg/linter/test/rules/prefer_if_elements_to_conditional_expressions_test.dart index de23ae5217ec..3239a1d6676a 100644 --- a/pkg/linter/test/rules/prefer_if_elements_to_conditional_expressions_test.dart +++ b/pkg/linter/test/rules/prefer_if_elements_to_conditional_expressions_test.dart @@ -20,23 +20,25 @@ class PreferIfElementsToConditionalExpressionsTest extends LintRuleTest { LintNames.prefer_if_elements_to_conditional_expressions; test_conditionalInList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f(bool b) { return ['a', b ? 'c' : 'd', 'e']; } -''', [ - lint(40, 13), - ]); +''', + [lint(40, 13)], + ); } test_conditionalInList_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f(bool b) { return ['a', (b ? 'c' : 'd'), 'e']; } -''', [ - lint(40, 15), - ]); +''', + [lint(40, 15)], + ); } test_conditionalInMap() async { @@ -48,22 +50,24 @@ Map f(bool b) { } test_conditionalInSet() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Set f(bool b) { return {'a', b ? 'c' : 'd', 'e'}; } -''', [ - lint(39, 13), - ]); +''', + [lint(39, 13)], + ); } test_conditionalInSet_parenthesizedTwice() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Set f(bool b) { return {'a', ((b ? 'c' : 'd')), 'e'}; } -''', [ - lint(39, 17), - ]); +''', + [lint(39, 17)], + ); } } diff --git a/pkg/linter/test/rules/prefer_if_null_operators_test.dart b/pkg/linter/test/rules/prefer_if_null_operators_test.dart index b1e649bcd8fb..9275650d3743 100644 --- a/pkg/linter/test/rules/prefer_if_null_operators_test.dart +++ b/pkg/linter/test/rules/prefer_if_null_operators_test.dart @@ -18,55 +18,60 @@ class PreferIfNullOperatorsTest extends LintRuleTest { String get lintRule => LintNames.prefer_if_null_operators; test_null_eqEq_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? p) { null == p ? 1 : p; } -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_null_notEq_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? p) { null != p ? p : 2; } -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_nullable_eqEq_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? p) { p == null ? 1 : p; } -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_nullable_notEq_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? p) { p != null ? p : 2; } -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_nullablePrefixedIdentifier_notEq_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.d != null ? c.d : 7; } class C { int? get d => 7; } -''', [ - lint(16, 21), - ]); +''', + [lint(16, 21)], + ); } } diff --git a/pkg/linter/test/rules/prefer_initializing_formals_test.dart b/pkg/linter/test/rules/prefer_initializing_formals_test.dart index be8ae1f0bcc9..6f17bf88ef15 100644 --- a/pkg/linter/test/rules/prefer_initializing_formals_test.dart +++ b/pkg/linter/test/rules/prefer_initializing_formals_test.dart @@ -17,28 +17,30 @@ main() { class PreferInitializingFormalsTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_LOCAL_VARIABLE, - WarningCode.UNUSED_FIELD, - ]; + WarningCode.UNUSED_LOCAL_VARIABLE, + WarningCode.UNUSED_FIELD, + ]; @override String get lintRule => LintNames.prefer_initializing_formals; test_assignedInBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { num x = 0; C(num x) { this.x = x; } } -''', [ - lint(40, 10), - ]); +''', + [lint(40, 10)], + ); } test_assignedInBody_andHasSuperInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a, b; A(this.a, this.b); @@ -50,10 +52,9 @@ class C extends A { this.d = d; } } -''', [ - lint(116, 10), - lint(132, 10), - ]); +''', + [lint(116, 10), lint(132, 10)], + ); } test_assignedInBody_justSetters() async { @@ -70,7 +71,8 @@ class C { } test_assignedInBody_namedParameters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { num? x, y; C({num? x, num y = 1}) { @@ -78,10 +80,9 @@ class C { this.y = y; } } -''', [ - lint(54, 10), - lint(70, 10), - ]); +''', + [lint(54, 10), lint(70, 10)], + ); } test_assignedInBody_namedParameters_renamed() async { @@ -97,7 +98,8 @@ class C { } test_assignedInBody_subsequent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { num x = 0, y = 0; C(num x, num y) { @@ -105,14 +107,14 @@ class C { this.y = y; } } -''', [ - lint(54, 10), - lint(70, 10), - ]); +''', + [lint(54, 10), lint(70, 10)], + ); } test_assignedInInitializer_andHasSuperInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a, b; A(this.a, this.b); @@ -124,10 +126,9 @@ class C extends A { this.d = d, super(c, d); } -''', [ - lint(103, 10), - lint(123, 10), - ]); +''', + [lint(103, 10), lint(123, 10)], + ); } test_assignedInInitializer_assignmentWithCalculation() async { @@ -141,17 +142,17 @@ class C { } test_assignedInInitializer_namedParameters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { num? x, y; C({num? x, num y = 1}) : this.x = x, this.y = y; } -''', [ - lint(56, 10), - lint(76, 10), - ]); +''', + [lint(56, 10), lint(76, 10)], + ); } test_assignedInInitializer_renamedParameter() async { diff --git a/pkg/linter/test/rules/prefer_inlined_adds_test.dart b/pkg/linter/test/rules/prefer_inlined_adds_test.dart index 5cbacdd6b935..0fe75a1b0a0c 100644 --- a/pkg/linter/test/rules/prefer_inlined_adds_test.dart +++ b/pkg/linter/test/rules/prefer_inlined_adds_test.dart @@ -25,26 +25,29 @@ var y = ['a']..addAll(x ?? const []); } test_listLiteral_cascadeAdd() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ['a']..add('b'); -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_listLiteral_cascadeAdd_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ['a']..add('b')..add('c'); -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_listLiteral_cascadeAddAll_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ['a']..addAll(['b', 'c']); -''', [ - lint(15, 6), - ]); +''', + [lint(15, 6)], + ); } } diff --git a/pkg/linter/test/rules/prefer_int_literals_test.dart b/pkg/linter/test/rules/prefer_int_literals_test.dart index dba9fe6f1857..541b70ff0154 100644 --- a/pkg/linter/test/rules/prefer_int_literals_test.dart +++ b/pkg/linter/test/rules/prefer_int_literals_test.dart @@ -17,34 +17,36 @@ main() { class PreferIntLiteralsTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.prefer_int_literals; test_argumentPassedToTypeVariableParameter_explicitlyTypedDouble_integer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math'; f(double d) { double x = max(d, 7.0); } -''', [ - lint(54, 3), - ]); +''', + [lint(54, 3)], + ); } test_argumentPassedToTypeVariableParameter_inferredType_integer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:math'; f(double d) { var a = max(d, 7.0); } -''', [ - lint(51, 3), - ]); +''', + [lint(51, 3)], + ); } test_argumentToNamedParameter_implicitlyTyped() async { @@ -56,13 +58,14 @@ void f({d}) { } test_argumentToNamedParameter_withDefaultValue_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({double d = 0.0}) { f(d: 1.0); } -''', [ - lint(34, 3), - ]); +''', + [lint(34, 3)], + ); } test_argumentToNamedParameter_withDefaultValue_implicitlyTyped() async { @@ -74,13 +77,14 @@ void f({d = 0.0}) { } test_argumentToPositionalParameter_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(double d) { f(1.0); } -''', [ - lint(23, 3), - ]); +''', + [lint(23, 3)], + ); } test_argumentToSuperParameter_decimal() async { @@ -106,16 +110,17 @@ class B extends A { } test_argumentToSuperParameter_integer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(double x); } class B extends A { B() : super(1.0); } -''', [ - lint(61, 3), - ]); +''', + [lint(61, 3)], + ); } test_binaryExpression_multipliedByInt_explicitlyTypedDouble() async { @@ -154,11 +159,12 @@ void f() { } test_canBeInt_explicitlyTypedDouble_decimalWithExponent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = 7.1e2; -''', [ - lint(11, 5), - ]); +''', + [lint(11, 5)], + ); } test_cannotBeInt_explicitlyTypedDouble_decimalWithExponent() async { @@ -180,43 +186,48 @@ double a = 1_234.567_8; } test_explicitTypeDouble_integer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = 8.0; -''', [ - lint(11, 3), - ]); +''', + [lint(11, 3)], + ); } test_explicitTypeDouble_integer_negative() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = -8.0; -''', [ - lint(12, 3), - ]); +''', + [lint(12, 3)], + ); } test_explicitTypeDouble_integerWithExponent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = 7.0e2; -''', [ - lint(11, 5), - ]); +''', + [lint(11, 5)], + ); } test_explicitTypeDouble_integerWithExponentAndSeparators() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = 7_000.0e2; -''', [ - lint(11, 9), - ]); +''', + [lint(11, 9)], + ); } test_explicitTypeDouble_integerWithSeparators() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double a = 8_000.000_0; -''', [ - lint(11, 11), - ]); +''', + [lint(11, 11)], + ); } test_explicitTypeDynamic_integer() async { @@ -232,13 +243,14 @@ Object a = 8.0; } test_functionExpressionBody_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { double g() => 6.0; } -''', [ - lint(27, 3), - ]); +''', + [lint(27, 3)], + ); } test_functionExpressionBody_implicitlyTypedDynamic() async { @@ -250,13 +262,14 @@ void f() { } test_functionExpressionBody_method_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { double f() => 6.0; } -''', [ - lint(26, 3), - ]); +''', + [lint(26, 3)], + ); } test_inBinaryExpression_explicitlyTypedInt_integer() async { @@ -285,11 +298,12 @@ var a = 7.0e2; } test_inListLiteral_explicitTypeDouble_integer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = [50.0]; -''', [ - lint(17, 4), - ]); +''', + [lint(17, 4)], + ); } test_inListLiteral_inferredType_integer() async { @@ -299,13 +313,14 @@ var a = [50.0]; } test_returnExpression_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' double f() { return 6.0; } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_returnExpression_implicitlyTypedDynamic() async { @@ -317,14 +332,15 @@ f() { } test_returnExpression_method_explicitlyTypedDouble() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { double f() { return 6.0; } } -''', [ - lint(36, 3), - ]); +''', + [lint(36, 3)], + ); } } diff --git a/pkg/linter/test/rules/prefer_interpolation_to_compose_strings_test.dart b/pkg/linter/test/rules/prefer_interpolation_to_compose_strings_test.dart index 294dfcc8a079..eac0aae972dc 100644 --- a/pkg/linter/test/rules/prefer_interpolation_to_compose_strings_test.dart +++ b/pkg/linter/test/rules/prefer_interpolation_to_compose_strings_test.dart @@ -30,11 +30,12 @@ final a = 'foo' + 'bar' + 'baz'; } test_stringLiteral_toStringInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final b = 'foo' + 7.toString(); -''', [ - lint(10, 20), - ]); +''', + [lint(10, 20)], + ); } test_stringLiteral_toStringInvocation_withArguments() async { @@ -50,42 +51,48 @@ class A { } test_stringLiteral_variableString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = 'bar' + a; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } test_stringLiteral_variableString_insideInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = '${'bar' + a}' + a; -''', [ - // `'${'bar' + a}' + a` is reported. - lint(27, 18), - // As is `'bar' + a`; separate diagnostic. - lint(30, 9), - ]); +''', + [ + // `'${'bar' + a}' + a` is reported. + lint(27, 18), + // As is `'bar' + a`; separate diagnostic. + lint(30, 9), + ], + ); } test_stringLiteral_variableString_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = 'bar' + a + 'baz'; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } test_stringLiteral_variableString_variableString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = 'bar' + a + a; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } /// #2490 @@ -132,40 +139,43 @@ void f() { } test_variableString_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = a + 'bar'; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } test_variableString_stringLiteral_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = a + 'bar' + 'baz'; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } test_variableString_stringLiteral_stringLiteral_variableString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = a + 'bar' + 'baz' + a; -''', [ - lint(27, 9), - lint(39, 9), - ]); +''', + [lint(27, 9), lint(39, 9)], + ); } test_variableString_stringLiteral_variableString() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final b = a + 'bar' + a; -''', [ - lint(27, 9), - ]); +''', + [lint(27, 9)], + ); } /// #2490 @@ -185,12 +195,13 @@ final c = a + a; } test_variableString_variableString_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final a = 'foo'; final c = a + a + 'bar'; -''', [ - lint(31, 9), - ]); +''', + [lint(31, 9)], + ); } test_variableString_variableString_variableString() async { diff --git a/pkg/linter/test/rules/prefer_is_empty_test.dart b/pkg/linter/test/rules/prefer_is_empty_test.dart index b845358a8491..8bb44dca3d27 100644 --- a/pkg/linter/test/rules/prefer_is_empty_test.dart +++ b/pkg/linter/test/rules/prefer_is_empty_test.dart @@ -18,29 +18,31 @@ class PreferIsEmptyTest extends LintRuleTest { String get lintRule => LintNames.prefer_is_empty; test_iterableLength_notEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var i = Iterable.empty(); var x = i.length != 0; -''', [ - lint(34, 13), - ]); +''', + [lint(34, 13)], + ); } test_listLength_asInt_greaterThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ([].length as int) > 0; -''', [ - lint(8, 22), - error(WarningCode.UNNECESSARY_CAST, 9, 16), - ]); +''', + [lint(8, 22), error(WarningCode.UNNECESSARY_CAST, 9, 16)], + ); } test_listLength_eqEq_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length == -1; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_listLength_eqEq_one() async { @@ -50,19 +52,21 @@ var x = [].length == 1; } test_listLength_eqEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length == 0; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_greaterThan_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length > -1; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_greaterThan_one() async { @@ -78,19 +82,21 @@ bool x = [].length > 1; } test_listLength_greaterThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length > 0; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_listLength_greaterThan_zero_inConditional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length > 0 ? 7 : 6; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_listLength_greaterThan_zero_inConstructorAssertInitializer() async { @@ -103,43 +109,48 @@ class A { } test_listLength_greaterThanEq_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length >= -1; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_listLength_greaterThanEq_one() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length >= 1; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_greaterThanEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length >= 0; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_lessThan_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length < -1; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_lessThan_one() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length < 1; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_listLength_lessThan_variable() async { @@ -150,19 +161,21 @@ var x = [].length < zero; } test_listLength_lessThan_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length < 0; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_listLength_lessThanEq_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length <= -1; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_listLength_lessThanEq_one() async { @@ -172,19 +185,21 @@ var x = [].length <= 1; } test_listLength_lessThanEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length <= 0; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_notEq_negativeOne() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length != -1; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_listLength_notEq_one() async { @@ -194,11 +209,12 @@ var x = [].length != 1; } test_listLength_notEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].length != 0; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_listLength_plusExpression_greaterThan_zero() async { @@ -208,59 +224,66 @@ var x = [].length + 1 > 0; } test_mapLength_parenthesized_eqEq_zero() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ({1: 2}.length) == 0; -''', [ - lint(8, 20), - ]); +''', + [lint(8, 20)], + ); } test_negativeOne_eqEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 == [].length; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_negativeOne_greaterThan_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 > [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_negativeOne_greaterThanEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 >= [].length; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_negativeOne_lessThan_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 < [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_negativeOne_lessThanEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 <= [].length; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_negativeOne_notEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = -1 != [].length; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_one_eqEq_listLength() async { @@ -270,11 +293,12 @@ var x = 1 == [].length; } test_one_greaterThan_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 > [].length; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_one_greaterThanEq_listLength() async { @@ -290,11 +314,12 @@ var x = 1 < [].length; } test_one_lessThanEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 <= [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_one_notEq_listLength() async { @@ -304,14 +329,15 @@ var x = 1 != [].length; } test_stringLength_eqEq_zero_inConstructorInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final bool x; C(String s) : x = s.length == 0; } -''', [ - lint(46, 13), - ]); +''', + [lint(46, 13)], + ); } test_stringLength_greaterThan_zero_constructorAssertInitializer() async { @@ -331,50 +357,56 @@ var x = zero < [].length; } test_zero_eqEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 == [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_zero_greaterThan_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 > [].length; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_zero_greaterThanEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 >= [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_zero_lessThan_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 < [].length; -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_zero_lessThanOrEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 <= [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_zero_notEq_listLength() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 0 != [].length; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } } diff --git a/pkg/linter/test/rules/prefer_is_not_empty_test.dart b/pkg/linter/test/rules/prefer_is_not_empty_test.dart index 615fc3c04b35..eda47146da9c 100644 --- a/pkg/linter/test/rules/prefer_is_not_empty_test.dart +++ b/pkg/linter/test/rules/prefer_is_not_empty_test.dart @@ -26,13 +26,14 @@ void f(Iterable p) { } test_iterable_isEmpty_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Iterable p) { !p.isEmpty; } -''', [ - lint(28, 10), - ]); +''', + [lint(28, 10)], + ); } test_list_isEmpty() async { @@ -42,27 +43,30 @@ var x = [].isEmpty; } test_list_isEmpty_doubleParens_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = !(([4].isEmpty)); -''', [ - lint(8, 16), - ]); +''', + [lint(8, 16)], + ); } test_list_isEmpty_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = ![1].isEmpty; -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_list_isEmpty_parens_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = !([3].isEmpty); -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_map_isEmpty() async { @@ -72,10 +76,11 @@ var x = {}.isEmpty; } test_map_isEmpty_not() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = !{2: 'a'}.isEmpty; -''', [ - lint(8, 17), - ]); +''', + [lint(8, 17)], + ); } } diff --git a/pkg/linter/test/rules/prefer_is_not_operator_test.dart b/pkg/linter/test/rules/prefer_is_not_operator_test.dart index 2144d51308c7..3c4b9ed3d9c3 100644 --- a/pkg/linter/test/rules/prefer_is_not_operator_test.dart +++ b/pkg/linter/test/rules/prefer_is_not_operator_test.dart @@ -18,13 +18,14 @@ class PreferIsNotOperatorTest extends LintRuleTest { String get lintRule => 'prefer_is_not_operator'; test_is_wrappedInNot() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object p) { !(p is int); } -''', [ - lint(21, 11), - ]); +''', + [lint(21, 11)], + ); } test_isNot() async { diff --git a/pkg/linter/test/rules/prefer_iterable_whereType_test.dart b/pkg/linter/test/rules/prefer_iterable_whereType_test.dart index 176c39762594..7db376e8e655 100644 --- a/pkg/linter/test/rules/prefer_iterable_whereType_test.dart +++ b/pkg/linter/test/rules/prefer_iterable_whereType_test.dart @@ -20,22 +20,24 @@ class PreferIterableWhereTypeTest extends LintRuleTest { String get lintRule => LintNames.prefer_iterable_whereType; test_closureWithIs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [42].where((e) => e is String); -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_closureWithIs_blockBodySingleStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [42].where( (e) { return e is String; }); -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_closureWithIs_multipleStatements() async { @@ -48,11 +50,12 @@ var x = [42].where((e) { } test_closureWithIs_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [42].where((e) => (e is String)); -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_closureWithIs_wrongSimpleTarget() async { diff --git a/pkg/linter/test/rules/prefer_mixin_test.dart b/pkg/linter/test/rules/prefer_mixin_test.dart index 20174946271e..5272cd1c3181 100644 --- a/pkg/linter/test/rules/prefer_mixin_test.dart +++ b/pkg/linter/test/rules/prefer_mixin_test.dart @@ -65,25 +65,27 @@ class Z with M { } class PreferMixinTestLanguage219 extends BasePreferMixinTest with LanguageVersion219Mixin { test_mixedInClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} class B extends Object with A {} -''', [ - lint(40, 1), - ]); +''', + [lint(40, 1)], + ); } test_mixedInClass_typAlias() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} typedef AA = A; abstract class CC with AA { } -''', [ - lint(52, 2), - ]); +''', + [lint(52, 2)], + ); } test_mixedInIterableMixin() async { diff --git a/pkg/linter/test/rules/prefer_null_aware_method_calls_test.dart b/pkg/linter/test/rules/prefer_null_aware_method_calls_test.dart index 3b01a952fae9..00fd1872c105 100644 --- a/pkg/linter/test/rules/prefer_null_aware_method_calls_test.dart +++ b/pkg/linter/test/rules/prefer_null_aware_method_calls_test.dart @@ -35,24 +35,26 @@ void f(dynamic p) { } test_conditional_propertyAccess_sameProperty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { p.m != null ? p.m!() : null; } -''', [ - lint(36, 6), - ]); +''', + [lint(36, 6)], + ); } test_conditional_sameTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Function()? func; void f() { func != null ? func!() : null; } -''', [ - lint(46, 7), - ]); +''', + [lint(46, 7)], + ); } test_ifNotNull_propertyAccess_differentProperties() async { @@ -66,38 +68,41 @@ void f(dynamic p) { } test_ifNotNull_propertyAccess_sameProperty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { if (p.m != null) { p.m!(); } } -''', [ - lint(45, 6), - ]); +''', + [lint(45, 6)], + ); } test_ifNotNull_sameTarget_blockStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Function()? func; void f() { if (func != null) { func!(); } } -''', [ - lint(55, 7), - ]); +''', + [lint(55, 7)], + ); } test_ifNotNull_sameTarget_expressionStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Function()? func; void f() { if (func != null) func!(); } -''', [ - lint(49, 7), - ]); +''', + [lint(49, 7)], + ); } } diff --git a/pkg/linter/test/rules/prefer_null_aware_operators_test.dart b/pkg/linter/test/rules/prefer_null_aware_operators_test.dart index af561e7793cb..fef5b7ec1b29 100644 --- a/pkg/linter/test/rules/prefer_null_aware_operators_test.dart +++ b/pkg/linter/test/rules/prefer_null_aware_operators_test.dart @@ -30,7 +30,8 @@ abstract class A { } test_identifierEqualEqualNull_null_elseMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { a == null ? null : a.b(); } @@ -38,13 +39,14 @@ void f(A? a) { abstract class A { void b(); } -''', [ - lint(17, 24), - ]); +''', + [lint(17, 24)], + ); } test_identifierEqualEqualNull_null_elsePrefixedIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { a == null ? null : a.b; } @@ -52,13 +54,14 @@ void f(A? a) { abstract class A { int get b; } -''', [ - lint(17, 22), - ]); +''', + [lint(17, 22)], + ); } test_identifierEqualEqualNull_null_elsePropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { a == null ? null : a.b.c; } @@ -67,9 +70,9 @@ abstract class A { A get b; int get c; } -''', [ - lint(17, 24), - ]); +''', + [lint(17, 24)], + ); } test_identifierEqualEqualNull_unrelatedBranch() async { @@ -90,7 +93,8 @@ void f(int? a, int b) { } test_identifierNotEqualNull_prefixedIdentifier_elseNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { a != null ? a.b : null; } @@ -98,13 +102,14 @@ void f(A? a) { abstract class A { int get b; } -''', [ - lint(17, 22), - ]); +''', + [lint(17, 22)], + ); } test_identifierNotEqualNull_prefixedIdentifier_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { a != null ? a.b : null; } @@ -112,13 +117,14 @@ void f(A? a) { abstract class A { int get b; } -''', [ - lint(17, 22), - ]); +''', + [lint(17, 22)], + ); } test_nullEqualEqualIdentifier_null_elseMethodInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { null == a ? null : a.b(); } @@ -126,13 +132,14 @@ void f(A? a) { abstract class A { void b(); } -''', [ - lint(17, 24), - ]); +''', + [lint(17, 24)], + ); } test_nullEqualEqualIdentifier_null_elsePrefixedIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { null == a ? null : a.b; } @@ -140,13 +147,14 @@ void f(A? a) { abstract class A { int get b; } -''', [ - lint(17, 22), - ]); +''', + [lint(17, 22)], + ); } test_nullEqualEqualPrefixedIdentifier_null_elsePropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { null == a.b ? null : a.b!.c; } @@ -155,13 +163,14 @@ abstract class A { A? get b; int get c; } -''', [ - lint(16, 27), - ]); +''', + [lint(16, 27)], + ); } test_nullNotEqualIdentifier_prefixedIdentifier_elseNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A? a) { null != a ? a.b : null; } @@ -169,13 +178,14 @@ void f(A? a) { abstract class A { int get b; } -''', [ - lint(17, 22), - ]); +''', + [lint(17, 22)], + ); } test_nullNotEqualPrefixedIdentifier_propertyAccess_elseNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { null != a.b ? a.b!.c : null; } @@ -184,13 +194,14 @@ abstract class A { A? get b; int get c; } -''', [ - lint(16, 27), - ]); +''', + [lint(16, 27)], + ); } test_prefixedIdentifierEqualEqualNull_null_elseMethodInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { a.b == null ? null : a.b!.c(); } @@ -199,13 +210,14 @@ abstract class A { A? get b; void c(); } -''', [ - lint(16, 29), - ]); +''', + [lint(16, 29)], + ); } test_prefixedIdentifierEqualEqualNull_null_elsePropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { a.b == null ? null : a.b!.c; } @@ -214,9 +226,9 @@ abstract class A { A? get b; int get c; } -''', [ - lint(16, 27), - ]); +''', + [lint(16, 27)], + ); } test_prefixedIdentifierNotEqualNull_prefixedIdentifier_elseNull() async { @@ -232,7 +244,8 @@ abstract class A { } test_prefixedIdentifierNotEqualNull_propertyAccess_elseNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a) { a.b != null ? a.b!.c : null; } @@ -241,8 +254,8 @@ abstract class A { A? get b; int get c; } -''', [ - lint(16, 27), - ]); +''', + [lint(16, 27)], + ); } } diff --git a/pkg/linter/test/rules/prefer_relative_imports_test.dart b/pkg/linter/test/rules/prefer_relative_imports_test.dart index 8786568002a5..cfa64d595b9e 100644 --- a/pkg/linter/test/rules/prefer_relative_imports_test.dart +++ b/pkg/linter/test/rules/prefer_relative_imports_test.dart @@ -48,12 +48,13 @@ import 'package:internal_package/lib.dart'; newFile('$testPackageLibPath/lib.dart', r''' class C {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// This provides [C]. import 'package:test/lib.dart'; -''', [ - lint(30, 23), - ]); +''', + [lint(30, 23)], + ); } test_samePackage_packageSchema_fromOutsideLib() async { @@ -77,14 +78,15 @@ class C {} part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; /// This provides [C]. import 'package:test/lib.dart'; -''', [ - lint(49, 23), - ]); +''', + [lint(49, 23)], + ); } test_samePackage_relativeUri() async { diff --git a/pkg/linter/test/rules/prefer_single_quotes_test.dart b/pkg/linter/test/rules/prefer_single_quotes_test.dart index 0366f36819b3..98f2e06cdb29 100644 --- a/pkg/linter/test/rules/prefer_single_quotes_test.dart +++ b/pkg/linter/test/rules/prefer_single_quotes_test.dart @@ -18,19 +18,21 @@ class PreferSingleQuotesTest extends LintRuleTest { String get lintRule => LintNames.prefer_single_quotes; test_doubleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = "no quote"; -''', [ - lint(8, 10), - ]); +''', + [lint(8, 10)], + ); } test_doubleQuotes_import() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import "dart:core"; -''', [ - lint(7, 11), - ]); +''', + [lint(7, 11)], + ); } test_doubleQuotes_innerSingleQuote() async { @@ -48,13 +50,14 @@ void f(String p) { } test_doubleQuotes_interpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(String p) { "no quote $p"; } -''', [ - lint(21, 13), - ]); +''', + [lint(21, 13)], + ); } test_doubleQuotes_interpolationWithSingleQuote() async { @@ -64,11 +67,12 @@ var x = "foo ${1 == 'x'} bar"; } test_doubleQuotes_raw() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = r"no quote"; -''', [ - lint(8, 11), - ]); +''', + [lint(8, 11)], + ); } test_doubleQuotes_raw_innerSingleQuote() async { @@ -78,11 +82,12 @@ var x = r"has quote '"; } test_doubleQuotes_triple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = r"""no quote"""; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_doubleQuotes_triple_innerSingleQuote() async { diff --git a/pkg/linter/test/rules/prefer_spread_collections_test.dart b/pkg/linter/test/rules/prefer_spread_collections_test.dart index 6c45299b45b4..192b91ee62dc 100644 --- a/pkg/linter/test/rules/prefer_spread_collections_test.dart +++ b/pkg/linter/test/rules/prefer_spread_collections_test.dart @@ -22,59 +22,70 @@ class PreferSpreadCollectionsTest extends LintRuleTest { String get lintRule => LintNames.prefer_spread_collections; test_constInitializedWithNonConstantValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const thangs = []; const cc = []..addAll(thangs); -''', [ - // No lint - error(CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE, 30, - 18), - ]); +''', + [ + // No lint + error( + CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE, + 30, + 18, + ), + ], + ); } test_listLiteralTarget_conditional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic x; var y = ['a']..addAll(1 == 2 ? x : []); -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_listLiteralTarget_conditional_constList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic x; var y = ['a']..addAll(1 == 2 ? x : const []); -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_listLiteralTarget_identifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic x; var y = []..addAll(x); -''', [ - lint(23, 6), - ]); +''', + [lint(23, 6)], + ); } test_listLiteralTarget_ifNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic x; var y = ['a']..addAll(x ?? []); -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_listLiteralTarget_ifNull_constList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic x; var y = ['a']..addAll(x ?? const []); -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_listLiteralTarget_listLiteral() async { @@ -85,13 +96,14 @@ var l = ['a']..addAll(['b']); } test_listLiteralTarget_multipleCascades() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List p) { ['a']..addAll(p.map((i) => i.toString()))..addAll(['c']); } -''', [ - lint(31, 6), - ]); +''', + [lint(31, 6)], + ); } test_nonCollection() async { diff --git a/pkg/linter/test/rules/prefer_typing_uninitialized_variables_test.dart b/pkg/linter/test/rules/prefer_typing_uninitialized_variables_test.dart index 7317fd7b9266..9463df64621b 100644 --- a/pkg/linter/test/rules/prefer_typing_uninitialized_variables_test.dart +++ b/pkg/linter/test/rules/prefer_typing_uninitialized_variables_test.dart @@ -34,21 +34,20 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(32, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(32, 1)]); await assertNoDiagnosticsInFile(b.path); } test_field_final_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final x; C(this.x); } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_field_typed() async { @@ -60,34 +59,37 @@ class C { } test_field_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var x; } -''', [ - lint(16, 1), - ]); +''', + [lint(16, 1)], + ); } test_field_var_noInitializer_notFirst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var a = 5, b; } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_field_var_noInitializer_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static var x; } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_forEachLoopVariable_final() async { @@ -99,13 +101,14 @@ void f() { } test_forLoopVariable_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i, j = 0; j < 5; i = j, j++) {} } -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_localVariable_var_initializer() async { @@ -118,14 +121,15 @@ void f() { } test_localVariable_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { // ignore: unused_local_variable var x; } -''', [ - lint(52, 1), - ]); +''', + [lint(52, 1)], + ); } test_topLevelVariable_augmented() async { @@ -141,9 +145,7 @@ part of 'a.dart'; augment var x; '''); - await assertDiagnosticsInFile(a.path, [ - lint(20, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(20, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -154,10 +156,11 @@ var x = 4; } test_topLevelVariable_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x; -''', [ - lint(4, 1), - ]); +''', + [lint(4, 1)], + ); } } diff --git a/pkg/linter/test/rules/prefer_void_to_null_test.dart b/pkg/linter/test/rules/prefer_void_to_null_test.dart index 05636c9dfac5..4f2398b676f4 100644 --- a/pkg/linter/test/rules/prefer_void_to_null_test.dart +++ b/pkg/linter/test/rules/prefer_void_to_null_test.dart @@ -126,15 +126,16 @@ void f(int a) { /// https://github.com/dart-lang/linter/issues/4201 test_castPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { switch (a) { case var _ as Null: } } -''', [ - error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 49, 4), - ]); +''', + [error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 49, 4)], + ); } test_extension() async { @@ -152,34 +153,37 @@ extension type N(Null _) implements B {} } test_instanceField_futureOfNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { Future? x; } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_instanceField_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { Null x; } -''', [ - lint(12, 4), - ]); +''', + [lint(12, 4)], + ); } test_instanceField_null_prefixed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:core' as core; class C { core.Null x; } -''', [ - lint(45, 4), - ]); +''', + [lint(45, 4)], + ); } test_instanceGetter_overrideChangingType() async { @@ -197,7 +201,8 @@ class D extends C { } test_instanceMethod_returnType_overrideChangingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; abstract class C { FutureOr? m(); @@ -207,9 +212,9 @@ class D implements C { @override Null m() {} } -''', [ - lint(103, 4), - ]); +''', + [lint(103, 4)], + ); } test_instanceMethod_returnType_overrideChangingType_generic() async { @@ -235,13 +240,14 @@ void f() { } test_listLiteralTypeArg_null_nonEmpty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { [null]; } -''', [ - lint(14, 4), - ]); +''', + [lint(14, 4)], + ); } test_localVariable() async { @@ -253,13 +259,14 @@ void f() { } test_localVariable_futureOfNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { Future x; } -''', [ - lint(20, 4), - ]); +''', + [lint(20, 4)], + ); } test_mapLiteralTypeArg_nullKey_empty() async { @@ -271,13 +278,14 @@ void f() { } test_mapLiteralTypeArg_nullKey_nonEmpty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { {null: "foo"}; } -''', [ - lint(14, 4), - ]); +''', + [lint(14, 4)], + ); } test_mapLiteralTypeArg_nullValue_empty() async { @@ -289,88 +297,97 @@ void f() { } test_mapLiteralTypeArg_nullValue_nonEmpty() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { {"foo": null}; } -''', [ - lint(22, 4), - ]); +''', + [lint(22, 4)], + ); } test_methodInvocation_typeArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Future p) { p.then((_) {}); } -''', [ - lint(34, 4), - ]); +''', + [lint(34, 4)], + ); } test_methodParameter_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(Null x) {} } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_methodReturnType_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { Null m() {} } -''', [ - lint(12, 4), - ]); +''', + [lint(12, 4)], + ); } test_methodReturnType_null_prefixed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:core' as core; class C { core.Null m() {} } -''', [ - lint(45, 4), - ]); +''', + [lint(45, 4)], + ); } test_topLevelFunction_parameterType_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Null x) {} -''', [ - lint(7, 4), - ]); +''', + [lint(7, 4)], + ); } test_topLevelFunction_parameterType_null_prefixed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:core' as core; void f(core.Null x) {} -''', [ - lint(40, 4), - ]); +''', + [lint(40, 4)], + ); } test_topLevelFunction_returnType_null() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Null f() {} -''', [ - lint(0, 4), - ]); +''', + [lint(0, 4)], + ); } test_topLevelFunction_returnType_null_prefixed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:core' as core; core.Null f() {} -''', [ - lint(33, 4), - ]); +''', + [lint(33, 4)], + ); } test_topLevelVariable() async { @@ -380,11 +397,12 @@ Null a; } test_topLevelVariable_functionReturnType_functionParameterType_futureOfNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void Function(Future)? f; -''', [ - lint(21, 4), - ]); +''', + [lint(21, 4)], + ); } test_topLevelVariable_functionReturnType_functionParameterType_null() async { @@ -394,11 +412,12 @@ void Function(Null)? f; } test_topLevelVariable_functionReturnType_functionReturnType_futureOfNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future Function()? f; -''', [ - lint(7, 4), - ]); +''', + [lint(7, 4)], + ); } test_topLevelVariable_functionReturnType_functionReturnType_null() async { @@ -408,11 +427,12 @@ Null Function()? f; } test_topLevelVariable_futureOfNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future? x; -''', [ - lint(7, 4), - ]); +''', + [lint(7, 4)], + ); } test_topLevelVariable_null() async { diff --git a/pkg/linter/test/rules/provide_deprecation_message_test.dart b/pkg/linter/test/rules/provide_deprecation_message_test.dart index 4fa3fb474c16..d420c4febdcf 100644 --- a/pkg/linter/test/rules/provide_deprecation_message_test.dart +++ b/pkg/linter/test/rules/provide_deprecation_message_test.dart @@ -25,11 +25,12 @@ class C {} } test_withoutMessage() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' @deprecated class C {} -''', [ - lint(0, 11), - ]); +''', + [lint(0, 11)], + ); } } diff --git a/pkg/linter/test/rules/public_member_api_docs_test.dart b/pkg/linter/test/rules/public_member_api_docs_test.dart index 6895e4110595..609171c078a7 100644 --- a/pkg/linter/test/rules/public_member_api_docs_test.dart +++ b/pkg/linter/test/rules/public_member_api_docs_test.dart @@ -24,57 +24,70 @@ class PublicMemberApiDocsExtensionTypesTest extends LintRuleTest { String get lintRule => LintNames.public_member_api_docs; test_extensionTypeDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { } -''', [ - lint(15, 1), - ]); +''', + [lint(15, 1)], + ); } test_field_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Doc. extension type E(int i) { int? f; } -''', [ - // No lint. - error(CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, 42, 1), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, + 42, + 1, + ), + ], + ); } test_field_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Doc. extension type E(int i) { static int? f; } -''', [ - lint(49, 1), - ]); +''', + [lint(49, 1)], + ); } test_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Doc. extension type E(int i) { void m() { } } -''', [ - lint(42, 1), - ]); +''', + [lint(42, 1)], + ); } test_method_private() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Doc. extension type E(int i) { void _m() { } } -''', [ - // No lint - error(WarningCode.UNUSED_ELEMENT, 42, 2), - ]); +''', + [ + // No lint + error(WarningCode.UNUSED_ELEMENT, 42, 2), + ], + ); } } @@ -88,32 +101,38 @@ class PublicMemberApiDocsTest extends LintRuleTest { /// https://github.com/dart-lang/linter/issues/4526 test_abstractFinalConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract final class S { S(); } final class A extends S {} -''', [ - lint(21, 1), - // No lint on `S()` declaration - lint(47, 1), - ]); +''', + [ + lint(21, 1), + // No lint on `S()` declaration + lint(47, 1), + ], + ); } /// https://github.com/dart-lang/linter/issues/4526 test_abstractInterfaceConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract interface class S { S(); } final class A extends S {} -''', [ - lint(25, 1), - // No lint on `S()` declaration - lint(51, 1), - ]); +''', + [ + lint(25, 1), + // No lint on `S()` declaration + lint(51, 1), + ], + ); } test_annotatedEnumValue() async { @@ -131,67 +150,73 @@ enum A { } test_constructor_namedGenerative() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.c(); } -''', [ - lint(6, 1), - lint(14, 1), - ]); +''', + [lint(6, 1), lint(14, 1)], + ); } test_constructor_unnamedFactory() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C._(); factory C() => C._(); } -''', [ - lint(6, 1), - lint(30, 1), - ]); +''', + [lint(6, 1), lint(30, 1)], + ); } test_constructor_unnamedGenerative() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(); } -''', [ - lint(6, 1), - lint(12, 1), - ]); +''', + [lint(6, 1), lint(12, 1)], + ); } test_enum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; int x() => 0; int get y => 1; } -''', [ - lint(5, 1), - lint(11, 1), - lint(13, 1), - lint(15, 1), - lint(24, 1), - lint(44, 1), - ]); +''', + [ + lint(5, 1), + lint(11, 1), + lint(13, 1), + lint(15, 1), + lint(24, 1), + lint(44, 1), + ], + ); } test_enum_privateConstant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Documented. enum A { _a; } -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 27, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 27, 2), + ], + ); } test_enumConstructor() async { @@ -211,19 +236,20 @@ enum A { /// https://github.com/dart-lang/linter/issues/3525 test_extension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on Object { void f() { } } -''', [ - lint(10, 1), - lint(31, 1), - ]); +''', + [lint(10, 1), lint(31, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4521 test_internalClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @internal @@ -233,15 +259,18 @@ class C { C(); void m() {} } -''', [ - // Technically not in the private API but we can ignore that for testing. - error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), - ]); +''', + [ + // Technically not in the private API but we can ignore that for testing. + error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), + ], + ); } /// https://github.com/dart-lang/linter/issues/4521 test_internalEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @internal @@ -252,15 +281,18 @@ enum E { const E(); } -''', [ - // Technically not in the private API but we can ignore that for testing. - error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), - ]); +''', + [ + // Technically not in the private API but we can ignore that for testing. + error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), + ], + ); } /// https://github.com/dart-lang/linter/issues/4521 test_internalExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @internal @@ -269,28 +301,34 @@ extension X on Object { static int get i => 0; void e() {} } -''', [ - // Technically not in the private API but we can ignore that for testing. - error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), - ]); +''', + [ + // Technically not in the private API but we can ignore that for testing. + error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), + ], + ); } /// https://github.com/dart-lang/linter/issues/5030 test_internalFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @internal void f() {} -''', [ - // Technically not in the private API but we can ignore that for testing. - error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), - ]); +''', + [ + // Technically not in the private API but we can ignore that for testing. + error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), + ], + ); } /// https://github.com/dart-lang/linter/issues/4521 test_internalMixin() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:meta/meta.dart'; @internal @@ -299,20 +337,23 @@ mixin M { int get i => 0; void m() {} } -''', [ - // Technically not in the private API but we can ignore that for testing. - error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), - ]); +''', + [ + // Technically not in the private API but we can ignore that for testing. + error(WarningCode.INVALID_INTERNAL_ANNOTATION, 35, 8), + ], + ); } test_mixin_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// A mixin M. mixin M { String m() => ''; -}''', [ - lint(34, 1), - ]); +}''', + [lint(34, 1)], + ); } test_mixin_overridingMethod_OK() async { @@ -329,53 +370,59 @@ mixin M { part 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; class A { } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } /// https://github.com/dart-lang/linter/issues/4526 test_sealedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' sealed class S { S(); } final class A extends S {} -''', [ - lint(13, 1), - // No lint on `S()` declaration - lint(39, 1), - ]); +''', + [ + lint(13, 1), + // No lint on `S()` declaration + lint(39, 1), + ], + ); } test_topLevelMembers() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int g = 1; typedef T = void Function(); int get z => 0; -''', [ - lint(4, 1), - lint(19, 1), - lint(48, 1), - ]); +''', + [lint(4, 1), lint(19, 1), lint(48, 1)], + ); } test_topLevelMembers_private() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int _h = 1; typedef _T = void Function(); int get _z => 0; -''', [ - // No lint - error(WarningCode.UNUSED_ELEMENT, 4, 2), - error(WarningCode.UNUSED_ELEMENT, 20, 2), - error(WarningCode.UNUSED_ELEMENT, 50, 2), - ]); +''', + [ + // No lint + error(WarningCode.UNUSED_ELEMENT, 4, 2), + error(WarningCode.UNUSED_ELEMENT, 20, 2), + error(WarningCode.UNUSED_ELEMENT, 50, 2), + ], + ); } } @@ -414,15 +461,18 @@ class PublicMemberApiDocsTestPackageTest extends LintRuleTest { PackageConfigFileBuilder(), ); newPubspecYamlFile( - myPackageRootPath, pubspecYamlContent(name: 'myPackage')); + myPackageRootPath, + pubspecYamlContent(name: 'myPackage'), + ); newAnalysisOptionsYamlFile( myPackageRootPath, analysisOptionsContent(experiments: experiments, rules: [lintRule]), ); newFolder(fixturePackageLibPath); writePackageConfig( - '$myPackageRootPath/test/fixture/.dart_tool/package_config.json', - PackageConfigFileBuilder()..add(name: 'fixture', rootPath: '../lib')); + '$myPackageRootPath/test/fixture/.dart_tool/package_config.json', + PackageConfigFileBuilder()..add(name: 'fixture', rootPath: '../lib'), + ); } test_inTestLibDir() async { diff --git a/pkg/linter/test/rules/recursive_getters_test.dart b/pkg/linter/test/rules/recursive_getters_test.dart index a45487aa5ee2..d7b991324ba5 100644 --- a/pkg/linter/test/rules/recursive_getters_test.dart +++ b/pkg/linter/test/rules/recursive_getters_test.dart @@ -61,26 +61,28 @@ class C { } test_instanceGetter_blockBody_recursiveWithImplicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f { return f; } } -''', [ - lint(35, 1), - ]); +''', + [lint(35, 1)], + ); } test_instanceGetter_expressionBody_innerRecursiveCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f => p(f); } int p(int arg) => 0; -''', [ - lint(27, 1), - ]); +''', + [lint(27, 1)], + ); } test_instanceGetter_expressionBody_nonRecursive() async { @@ -93,23 +95,25 @@ class C { } test_instanceGetter_expressionBody_recursiveWithExplicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f => this.f; } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_instanceGetter_expressionBody_recursiveWithImplicitThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f => f; } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_instanceGetter_recursiveCallOnOtherInstance() async { @@ -154,56 +158,61 @@ class Nested { } test_referenceInListLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { List get f => [1, 2, ...f]; } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_referenceInMapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { Map get f => {}..addAll(f); } -''', [ - lint(46, 1), - ]); +''', + [lint(46, 1)], + ); } test_referenceInMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f { print(f); return 0; } } -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_simpleGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f => f; } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_simpleGetter_thisPrefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int get f => this.f; } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_staticMemberReference() async { @@ -225,13 +234,14 @@ int get f { } test_topLevelGetter_blockBody_recursiveCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int get f { return f; } -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_topLevelGetter_expressionBody_nonRecursive() async { @@ -242,19 +252,21 @@ int get f => _f; } test_topLevelGetter_expressionBody_recursiveCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int get f => f; -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_topLevelGetter_innerRecursiveCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? _f = 1; int get f => _f == null ? 0 : f; -''', [ - lint(43, 1), - ]); +''', + [lint(43, 1)], + ); } } diff --git a/pkg/linter/test/rules/require_trailing_commas_test.dart b/pkg/linter/test/rules/require_trailing_commas_test.dart index 0eeb6a4b59a2..5a42bc9b6c97 100644 --- a/pkg/linter/test/rules/require_trailing_commas_test.dart +++ b/pkg/linter/test/rules/require_trailing_commas_test.dart @@ -18,15 +18,16 @@ class RequireTrailingCommasTest extends LintRuleTest { String get lintRule => LintNames.require_trailing_commas; test_argumentList_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', 'Text'); } void g(Object p1, Object p2) {} -''', [ - lint(35, 1), - ]); +''', + [lint(35, 1)], + ); } test_argumentList_multiLine_containsFunctionalBlockBody_trailingComma() async { @@ -44,27 +45,29 @@ void g(Object p1, Object p2, {Object? p3}) {} } test_argumentList_multiLine_containsFunctionBlockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(() { }, 'Text'); } void g(Object p1, Object p2) {} -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_argumentList_multiLine_containsFunctionBlockBody_endsWithNamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', () { }, p3: 'Text'); } void g(Object p1, Object p2, {Object? p3}) {} -''', [ - lint(43, 1), - ]); +''', + [lint(43, 1)], + ); } test_argumentList_multiLine_containsFunctionBlockBody_trailingComma() async { @@ -81,7 +84,8 @@ void g(Object p1, Object p2) {} } test_argumentList_multiLine_containsListLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g([ 'one', @@ -89,13 +93,14 @@ void f() { ], 'Text'); } void g(Object p1, Object p2) {} -''', [ - lint(50, 1), - ]); +''', + [lint(50, 1)], + ); } test_argumentList_multiLine_containsMapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g({ 'one': 'Text', @@ -103,9 +108,9 @@ void f() { }, 'Text'); } void g(Object p1, Object p2) {} -''', [ - lint(66, 1), - ]); +''', + [lint(66, 1)], + ); } test_argumentList_multiLine_containsMapLiteral_withTrailingComma() async { @@ -121,7 +126,8 @@ void g(Object p1, Object p2) {} } test_argumentList_multiLine_containsSetLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g({ 'one', @@ -129,9 +135,9 @@ void f() { }, 'Text'); } void g(Object p1, Object p2) {} -''', [ - lint(50, 1), - ]); +''', + [lint(50, 1)], + ); } test_argumentList_multiLine_endsWithConstantListLiteral() async { @@ -147,15 +153,16 @@ void g(Object p1, Object p2) {} } test_argumentList_multiLine_endsWithFunctionBlockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', () {}); // LINT } void g(Object p1, Object p2) {} -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_argumentList_multiLine_endsWithFunctionBlockBody_multiLine() async { @@ -169,15 +176,16 @@ void g(Object p1, Object p2, {Object? p3}) {} } test_argumentList_multiLine_endsWithFunctionBlockBody_multiLine_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', 'Text', p3: () { }); } void g(Object p1, Object p2, {Object? p3}) {} -''', [ - lint(43, 1), - ]); +''', + [lint(43, 1)], + ); } test_argumentList_multiLine_endsWithFunctionBlockBody_multiLine_named_trailingComma() async { @@ -219,15 +227,16 @@ void g(Object p1, Object p2) {} } test_argumentList_multiLine_endsWithListLiteral_onSingleLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', const ['one', 'two']); } void g(Object p1, Object p2) {} -''', [ - lint(49, 1), - ]); +''', + [lint(49, 1)], + ); } test_argumentList_multiLine_endsWithListLiteral_withTrailingComma() async { @@ -243,15 +252,16 @@ void g(Object p1, Object p2) {} } test_argumentList_multiLine_endsWithMapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g('Text', const {'one': '1', 'two': '2', 'three': '3'}); // LINT } void g(Object p1, Object p2) {} -''', [ - lint(73, 1), - ]); +''', + [lint(73, 1)], + ); } test_argumentList_multiLine_endsWithMapLiteral_trailingComma() async { @@ -355,15 +365,16 @@ void f() { } test_assertStatement_closure_message() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { assert(() { return true; }(), 'Text'); } -''', [ - lint(55, 1), - ]); +''', + [lint(55, 1)], + ); } test_assertStatement_closure_message_trailingComma() async { @@ -388,25 +399,27 @@ void f() { } test_assertStatement_multiLine_message() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { assert(false, 'Text'); } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_assertStatement_oneArgument_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { assert('Text' .isNotEmpty); } -''', [ - lint(44, 1), - ]); +''', + [lint(44, 1)], + ); } test_assertStatement_trailingComma() async { @@ -420,15 +433,16 @@ void f() { } test_constructorAssertInitializer_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C() : assert(true, 'Text'); } -''', [ - lint(55, 1), - ]); +''', + [lint(55, 1)], + ); } test_constructorAssertInitializer_multiLine_trailingComma() async { @@ -444,12 +458,13 @@ class C { } test_function_parameters_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void method4(int one, int two) {} -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_function_parameters_multiLine_withComma() async { @@ -471,12 +486,13 @@ void f( } test_function_parameters_withNamed_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int one, {int two = 2}) {} -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_function_parameters_withNamed_singleLine() async { @@ -486,15 +502,16 @@ void f(int one, } test_functionLiteral_parameters_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (int one, int two) {}; } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_functionLiteral_parameters_singleLine() async { @@ -506,16 +523,17 @@ void f() { } test_listLiteral_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = [ 1, if (true) 2 ]; } -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_listLiteral_singleLine() async { @@ -527,16 +545,17 @@ void f() { } test_mapLiteral_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = { 1: 1, if (true) 2: 2 }; } -''', [ - lint(54, 1), - ]); +''', + [lint(54, 1)], + ); } test_mapLiteral_singleLine() async { @@ -560,16 +579,17 @@ class C { } test_parameterList_multiLineDefaultValue_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(Object p1, Object p2, [Object p3 = const [ 'Text', ]]); } -''', [ - lint(86, 1), - ]); +''', + [lint(86, 1)], + ); } test_parameterList_multiLineDefaultValue_multiLine_trailingComma() async { @@ -595,27 +615,29 @@ class C { } test_parameterList_singleLine_blankLineBefore() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C( Object p1, Object p2, Object p3); } -''', [ - lint(52, 1), - ]); +''', + [lint(52, 1)], + ); } test_setLiteral_multiLine() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = { 1, if (true) 2 }; } -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_setLiteral_singleLine() async { diff --git a/pkg/linter/test/rules/secure_pubspec_urls_test.dart b/pkg/linter/test/rules/secure_pubspec_urls_test.dart index 1c4f6da0a541..4881210db2bd 100644 --- a/pkg/linter/test/rules/secure_pubspec_urls_test.dart +++ b/pkg/linter/test/rules/secure_pubspec_urls_test.dart @@ -21,7 +21,8 @@ class SecurePubspecUrlsTest extends LintRuleTest { String get lintRule => LintNames.secure_pubspec_urls; test_dependencyGit_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -29,13 +30,14 @@ version: 1.1.1 dependencies: kittens: git: http://github.com/munificent/kittens.git -''', [ - lint(81, 40), - ]); +''', + [lint(81, 40)], + ); } test_dependencyGitUrl_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -45,13 +47,14 @@ dependencies: git: url: http://github.com/munificent/kittens2.git ref: main -''', [ - lint(93, 41), - ]); +''', + [lint(93, 41)], + ); } test_dependencyHosted_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -59,13 +62,14 @@ version: 1.1.1 dependencies: transmogrify: hosted: http://some-package-server.com -''', [ - lint(89, 30), - ]); +''', + [lint(89, 30)], + ); } test_dependencyHostedUrl_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -76,13 +80,14 @@ dependencies: name: transmogrify url: http://some-package-server.com version: ^1.0.0 -''', [ - lint(125, 30), - ]); +''', + [lint(125, 30)], + ); } test_dependencyOverridesGit_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -90,13 +95,14 @@ version: 1.1.1 dependency_overrides: kittens: git: http://github.com/munificent/kittens.git -''', [ - lint(89, 40), - ]); +''', + [lint(89, 40)], + ); } test_devDependencyGit_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -104,20 +110,21 @@ version: 1.1.1 dev_dependencies: kittens: git: http://github.com/munificent/kittens.git -''', [ - lint(85, 40), - ]); +''', + [lint(85, 40)], + ); } test_homepage_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 homepage: http://github.com/dart-lang/linter -''', [ - lint(56, 34), - ]); +''', + [lint(56, 34)], + ); } test_homepage_secure() async { @@ -130,18 +137,20 @@ homepage: https://github.com/dart-lang/linter } test_issueTracker_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 issue_tracker: http://github.com/dart-lang/linter/issues -''', [ - lint(61, 41), - ]); +''', + [lint(61, 41)], + ); } test_repository_insecure() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy description: Text. version: 1.1.1 @@ -149,8 +158,8 @@ repository: http://github.com/dart-lang/linter environment: sdk: ">=2.15.2 <3.0.0" -''', [ - lint(58, 34), - ]); +''', + [lint(58, 34)], + ); } } diff --git a/pkg/linter/test/rules/sized_box_for_whitespace_test.dart b/pkg/linter/test/rules/sized_box_for_whitespace_test.dart index b8a0c6b4f115..285d74b5d930 100644 --- a/pkg/linter/test/rules/sized_box_for_whitespace_test.dart +++ b/pkg/linter/test/rules/sized_box_for_whitespace_test.dart @@ -33,7 +33,8 @@ Widget f() { } test_hasHeight_andChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { @@ -42,9 +43,9 @@ Widget f() { child: Row(), ); } -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_hasHeight_noChild() async { @@ -60,7 +61,8 @@ Widget f() { } test_hasWidth_andChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { @@ -69,9 +71,9 @@ Widget f() { child: Row(), ); } -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_hasWidth_noChild() async { @@ -87,7 +89,8 @@ Widget f() { } test_hasWidthAndHeight_andChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { @@ -97,13 +100,14 @@ Widget f() { child: Row(), ); } -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_hasWidthAndHeight_andKey_noChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { @@ -113,13 +117,14 @@ Widget f() { height: 10, ); } -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_hasWidthAndHeight_noChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { @@ -128,9 +133,9 @@ Widget f() { height: 10, ); } -''', [ - lint(62, 9), - ]); +''', + [lint(62, 9)], + ); } test_noArguments() async { diff --git a/pkg/linter/test/rules/sized_box_shrink_expand_test.dart b/pkg/linter/test/rules/sized_box_shrink_expand_test.dart index 76028cd06eb6..a5f2ca4d7166 100644 --- a/pkg/linter/test/rules/sized_box_shrink_expand_test.dart +++ b/pkg/linter/test/rules/sized_box_shrink_expand_test.dart @@ -30,7 +30,8 @@ Widget f() { } test_infiniteWidth_infiniteHeight() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { return SizedBox( @@ -39,9 +40,9 @@ Widget f() { child: Container(), ); } -''', [ - lint(61, 8), - ]); +''', + [lint(61, 8)], + ); } test_infiniteWidth_noHeight() async { @@ -111,13 +112,14 @@ Widget f() { } test_zeroWidth_zeroHeight() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { return SizedBox(height: 0, width: 0,child: Container()); } -''', [ - lint(61, 8), - ]); +''', + [lint(61, 8)], + ); } } diff --git a/pkg/linter/test/rules/slash_for_doc_comments_test.dart b/pkg/linter/test/rules/slash_for_doc_comments_test.dart index db67d80a874d..1b4d88a16ade 100644 --- a/pkg/linter/test/rules/slash_for_doc_comments_test.dart +++ b/pkg/linter/test/rules/slash_for_doc_comments_test.dart @@ -18,119 +18,130 @@ class SlashForDocCommentsTest extends LintRuleTest { String get lintRule => LintNames.slash_for_doc_comments; test_class() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** C */ class C {} -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_constructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { /** C */ C(); } -''', [ - lint(12, 8), - ]); +''', + [lint(12, 8)], + ); } test_enum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** E */ enum E { A, B } -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_enumConstant() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { /** A */ A, B } -''', [ - lint(11, 8), - ]); +''', + [lint(11, 8)], + ); } test_extension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** A */ extension on int {} -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { /** x */ var x; } -''', [ - lint(12, 8), - ]); +''', + [lint(12, 8)], + ); } test_library() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** l */ library l; -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_localFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { /** g */ // ignore: unused_element void g() {} } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } test_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { /** f */ void f() {} } -''', [ - lint(12, 8), - ]); +''', + [lint(12, 8)], + ); } test_mixin() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** M */ mixin M {} -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_mixinApplication() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** C */ class C = Object with M; mixin M {} -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_noComment() async { @@ -161,47 +172,52 @@ class C {} } test_topLevelFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** f */ void f() {} -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_topLevelVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** x */ var x = 1; -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_typedef_genericFunctionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** T */ typedef T = bool Function(); -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_typedef_legacy() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** F */ typedef bool F(); -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } test_typedef_nonFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** T */ typedef T = Object; -''', [ - lint(0, 8), - ]); +''', + [lint(0, 8)], + ); } } diff --git a/pkg/linter/test/rules/sort_child_properties_last_test.dart b/pkg/linter/test/rules/sort_child_properties_last_test.dart index 10ae5fcef177..06762bb8d295 100644 --- a/pkg/linter/test/rules/sort_child_properties_last_test.dart +++ b/pkg/linter/test/rules/sort_child_properties_last_test.dart @@ -21,7 +21,8 @@ class SortChildPropertiesLastTest extends LintRuleTest { String get lintRule => LintNames.sort_child_properties_last; test_childArgumentBeforeKeyArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void f() { SizedBox( @@ -29,9 +30,9 @@ void f() { key: Key(''), ); } -''', [ - lint(66, 15), - ]); +''', + [lint(66, 15)], + ); } test_childArgumentOnly() async { @@ -46,7 +47,8 @@ void f() { } test_childrenArgumentBeforeKeyArgument_insideOtherChildArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void f() { SizedBox( @@ -59,9 +61,9 @@ void f() { ), ); } -''', [ - lint(130, 12), - ]); +''', + [lint(130, 12)], + ); } test_keyArgumentBeforeChildArgument() async { @@ -113,7 +115,8 @@ void f() { test_nestedChildren() async { // See https://dart-review.googlesource.com/c/sdk/+/161624. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void f() { Column( @@ -131,9 +134,8 @@ void f() { key: Key(''), ); } -''', [ - lint(64, 165), - lint(98, 42), - ]); +''', + [lint(64, 165), lint(98, 42)], + ); } } diff --git a/pkg/linter/test/rules/sort_constructors_first_test.dart b/pkg/linter/test/rules/sort_constructors_first_test.dart index 154c0772215c..265d4e16eab1 100644 --- a/pkg/linter/test/rules/sort_constructors_first_test.dart +++ b/pkg/linter/test/rules/sort_constructors_first_test.dart @@ -27,51 +27,54 @@ abstract class A { } test_fieldBeforeConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { final a = 0; A(); } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_methodBeforeConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { void f(); const A(); } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_methodBeforeConstructor_extensionType() async { // Since the check logic is shared w/ classes and enums, one test should // provide sufficient coverage for extension types. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { void f() {} E.e(this.o); } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_methodBeforeConstructors() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { void f(); A(); A.named(); } -''', [ - lint(33, 1), - lint(40, 1), - ]); +''', + [lint(33, 1), lint(40, 1)], + ); } test_ok() async { @@ -85,25 +88,27 @@ enum A { } test_staticFieldBeforeConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { static final a = 0; A(); } -''', [ - lint(43, 1), - ]); +''', + [lint(43, 1)], + ); } test_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; int f() => 0; const A(); } -''', [ - lint(42, 1), - ]); +''', + [lint(42, 1)], + ); } } diff --git a/pkg/linter/test/rules/sort_pub_dependencies_test.dart b/pkg/linter/test/rules/sort_pub_dependencies_test.dart index ebc85e6e9ec9..c42e5bf7f4a7 100644 --- a/pkg/linter/test/rules/sort_pub_dependencies_test.dart +++ b/pkg/linter/test/rules/sort_pub_dependencies_test.dart @@ -48,7 +48,8 @@ dependencies: } test_dependencies_unsorted() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy version: 1.1.1 @@ -57,13 +58,14 @@ dependencies: flutter: sdk: flutter bbb: ^0.15.8 -''', [ - lint(86, 3), - ]); +''', + [lint(86, 3)], + ); } test_dependencyOverrides_unsorted() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy version: 1.1.1 @@ -72,13 +74,14 @@ dependency_overrides: flutter: sdk: flutter bbb: ^0.15.8 -''', [ - lint(94, 3), - ]); +''', + [lint(94, 3)], + ); } test_devDependencies_unsorted() async { - await assertPubspecDiagnostics(r''' + await assertPubspecDiagnostics( + r''' name: fancy version: 1.1.1 @@ -87,8 +90,8 @@ dev_dependencies: flutter: sdk: flutter bbb: ^0.15.8 -''', [ - lint(90, 3), - ]); +''', + [lint(90, 3)], + ); } } diff --git a/pkg/linter/test/rules/sort_unnamed_constructors_first_test.dart b/pkg/linter/test/rules/sort_unnamed_constructors_first_test.dart index 8ce53e25ff53..8a0f73276c4d 100644 --- a/pkg/linter/test/rules/sort_unnamed_constructors_first_test.dart +++ b/pkg/linter/test/rules/sort_unnamed_constructors_first_test.dart @@ -29,16 +29,17 @@ class C { } test_class_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C.named(); C(); // ignore: unused_element C._(); } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_enum_sorted() async { @@ -52,38 +53,43 @@ enum A { } test_enum_unsorted() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c.aa(); const A.aa(); const A(); } -''', [ - lint(47, 1), - ]); +''', + [lint(47, 1)], + ); } test_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E.a(Object o) { void m() { } E.b(this.o); E(this.o); } -''', [ - lint(63, 1), - ]); +''', + [lint(63, 1)], + ); } test_extensionType_invalidConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { void m() { } E(this.o); } -''', [ - // No lint. - error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 46, 1), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 46, 1), + ], + ); } } diff --git a/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart b/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart index d80f12bf2353..dd7543f26417 100644 --- a/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart +++ b/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart @@ -46,26 +46,28 @@ class A { } test_forEach_inferredList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (var i in [1, 2, 'Hello'.length]) { print(i); } } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_forEach_listWithNonObviousElement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { int j = "Hello".length; for (var i in [j, 1, j + 1]) { } } -''', [ - lint(39, 5), - ]); +''', + [lint(39, 5)], + ); } test_forEach_noDeclaredType() async { @@ -94,16 +96,17 @@ f() { } test_genericInvocation_paramIsType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String f() { final h = bar(''); return h; } T bar(T d) => d; -''', [ - lint(15, 17), - ]); +''', + [lint(15, 17)], + ); } test_genericInvocation_paramIsType_ok() async { @@ -118,16 +121,17 @@ T bar(T d) => d; } test_genericInvocation_typeNeededForInference() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var h = bar(''); return h; } T bar(dynamic d) => d; -''', [ - lint(8, 15), - ]); +''', + [lint(8, 15)], + ); } test_genericInvocation_typeNeededForInference_ok() async { @@ -142,16 +146,17 @@ T bar(dynamic d) => d; } test_genericInvocation_typeParamProvided() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String f() { var h = bar(''); return h; } T bar(dynamic d) => d; -''', [ - lint(15, 23), - ]); +''', + [lint(15, 23)], + ); } test_genericInvocation_typeParamProvided_ok() async { @@ -166,7 +171,8 @@ T bar(dynamic d) => d; } test_instanceCreation_generic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var a = A(1); } @@ -174,9 +180,9 @@ f() { class A { A(X x); } -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_instanceCreation_generic_ok1() async { @@ -268,14 +274,14 @@ f() { } test_local_multiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { var a = 'a' + 'a', b = 'b' * 2; } -''', [ - lint(12, 13), - lint(27, 11), - ]); +''', + [lint(12, 13), lint(27, 11)], + ); } test_local_multiple_ok() async { @@ -297,16 +303,17 @@ f() { } test_local_promotion() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { num local = 2; if (local is! int) return; var x = local; return x; } -''', [ - lint(54, 13), - ]); +''', + [lint(54, 13)], + ); } test_pattern_list_destructured() async { diff --git a/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart b/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart index 5f62584046b1..1c9fe49359d2 100644 --- a/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart +++ b/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart @@ -96,15 +96,16 @@ class A { } test_genericInvocation_paramIsType_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { final h = bar(''); } T bar(T d) => d; -''', [ - lint(12, 17), - ]); +''', + [lint(12, 17)], + ); } test_genericInvocation_paramIsType_ok_instance() async { @@ -135,37 +136,40 @@ T bar(T d) => d; } test_genericInvocation_paramIsType_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static final h = bar(''); } T bar(T d) => d; -''', [ - lint(19, 17), - ]); +''', + [lint(19, 17)], + ); } test_genericInvocation_paramIsType_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final h = bar(''); T bar(T d) => d; -''', [ - lint(0, 17), - ]); +''', + [lint(0, 17)], + ); } test_genericInvocation_typeNeededForInference_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static var h = bar(''); } T bar(dynamic d) => d; -''', [ - lint(19, 15), - ]); +''', + [lint(19, 15)], + ); } test_genericInvocation_typeNeededForInference_ok_instance() async { @@ -196,36 +200,39 @@ T bar(dynamic d) => d; } test_genericInvocation_typeNeededForInference_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static var h = bar(''); } T bar(dynamic d) => d; -''', [ - lint(19, 15), - ]); +''', + [lint(19, 15)], + ); } test_genericInvocation_typeNeededForInference_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var h = bar(''); T bar(dynamic d) => d; -''', [ - lint(0, 15), - ]); +''', + [lint(0, 15)], + ); } test_genericInvocation_typeParamProvided_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var h = bar(''); } T bar(dynamic d) => d; -''', [ - lint(12, 23), - ]); +''', + [lint(12, 23)], + ); } test_genericInvocation_typeParamProvided_ok_instance() async { @@ -256,28 +263,31 @@ T bar(dynamic d) => d; } test_genericInvocation_typeParamProvided_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static var h = bar(''); } T bar(dynamic d) => d; -''', [ - lint(19, 23), - ]); +''', + [lint(19, 23)], + ); } test_genericInvocation_typeParamProvided_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var h = bar(''); T bar(dynamic d) => d; -''', [ - lint(0, 23), - ]); +''', + [lint(0, 23)], + ); } test_instanceCreation_generic_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var c = C(1); } @@ -285,9 +295,9 @@ class A { class C { C(X x); } -''', [ - lint(12, 12), - ]); +''', + [lint(12, 12)], + ); } test_instanceCreation_generic_ok1_instance() async { @@ -347,7 +357,8 @@ class A {} } test_instanceCreation_generic_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static var c = C(1); } @@ -355,21 +366,22 @@ class A { class C { C(X x); } -''', [ - lint(19, 12), - ]); +''', + [lint(19, 12)], + ); } test_instanceCreation_generic_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = A(1); class A { A(X x); } -''', [ - lint(0, 12), - ]); +''', + [lint(0, 12)], + ); } test_instanceCreation_nonGeneric_instance() async { @@ -561,14 +573,14 @@ Symbol s = #print; } test_multiple_instance() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var a = 'a' + 'a', b = 'b' * 2; } -''', [ - lint(16, 13), - lint(31, 11), - ]); +''', + [lint(16, 13), lint(31, 11)], + ); } test_multiple_ok_instance() async { @@ -594,23 +606,23 @@ String a = 'a' + 'a', b = 'b'.toString(); } test_multiple_static() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static var a = 'a' + 'a', b = 'b' * 2; } -''', [ - lint(23, 13), - lint(38, 11), - ]); +''', + [lint(23, 13), lint(38, 11)], + ); } test_multiple_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = 'a' + 'a', b = 'b' * 2; -''', [ - lint(4, 13), - lint(19, 11), - ]); +''', + [lint(4, 13), lint(19, 11)], + ); } test_override_getter_initialized() async { diff --git a/pkg/linter/test/rules/strict_top_level_inference_test.dart b/pkg/linter/test/rules/strict_top_level_inference_test.dart index c0a3b91729e7..c445e8527e22 100644 --- a/pkg/linter/test/rules/strict_top_level_inference_test.dart +++ b/pkg/linter/test/rules/strict_top_level_inference_test.dart @@ -16,30 +16,34 @@ main() { @reflectiveTest class StrictTopLevelInferenceTest extends LintRuleTest { @override - List get ignoredErrorCodes => - [WarningCode.UNUSED_ELEMENT, WarningCode.UNUSED_LOCAL_VARIABLE]; + List get ignoredErrorCodes => [ + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.strict_top_level_inference; test_constructorParameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({p1}) {} } -''', [ - lint(15, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(15, 2, correctionContains: 'Try adding a type annotation')], + ); } test_constructorParameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({final p1}); } -''', [ - lint(21, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(21, 2, correctionContains: 'Try adding a type annotation')], + ); } test_constructorParameter_named_initializingFormal() async { @@ -71,34 +75,42 @@ class C { } test_constructorParameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C({var p1}); } -''', [ - lint(19, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 19, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_constructorParameter_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(p1); } -''', [ - lint(14, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(14, 2, correctionContains: 'Try adding a type annotation')], + ); } test_constructorParameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(final p1); } -''', [ - lint(20, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(20, 2, correctionContains: 'Try adding a type annotation')], + ); } test_constructorParameter_positional_initializingFormal() async { @@ -130,14 +142,20 @@ class C { } test_constructorParameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { C(var p1); } -''', [ - lint(18, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 18, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceField_final() async { @@ -149,14 +167,15 @@ class C { } test_instanceField_final_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final f; C(this.f); } -''', [ - lint(18, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(18, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceField_final_override_noInitializer() async { @@ -180,13 +199,14 @@ class C { } test_instanceField_multiple_someMissingInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var x = '', y = '', z; } -''', [ - lint(32, 1, correctionContains: 'Try splitting the declaration'), - ]); +''', + [lint(32, 1, correctionContains: 'Try splitting the declaration')], + ); } test_instanceField_multiple_someMissingInitializer_butOverride() async { @@ -217,14 +237,20 @@ class C { } test_instanceField_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { var x; } -''', [ - lint(16, 1, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 16, + 1, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceField_var_noInitializer_override() async { @@ -239,54 +265,64 @@ class D implements C { } test_instanceGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { get g => 1; } -''', [ - lint(16, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(16, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceGetter_inExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { get g => 1; } -''', [ - lint(27, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(27, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m({p1}) {} } -''', [ - lint(20, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(20, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m({final p1}) {} } -''', [ - lint(26, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(26, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_named_hasDefault() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m({var p1 = false}) {} } -''', [ - lint(24, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 24, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceMethod_parameter_named_hasDefault_typed() async { @@ -306,27 +342,34 @@ class C { } test_instanceMethod_parameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m({var p1}) {} } -''', [ - lint(24, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 24, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceMethod_parameter_override_additionalNamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(int p1) {} } class D implements C { void m(p1, {p2}) {} } -''', [ - lint(69, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(69, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_override_additionalNamed_typed() async { @@ -341,16 +384,17 @@ class D implements C { } test_instanceMethod_parameter_override_additionalPositional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(int p1) {} } class D implements C { void m(p1, [p2]) {} } -''', [ - lint(69, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(69, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_override_additionalPositional_typed() async { @@ -387,34 +431,42 @@ class D implements C { } test_instanceMethod_parameter_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(p1) {} } -''', [ - lint(19, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(19, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(final p1) {} } -''', [ - lint(25, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(25, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_positional_hasDefault() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m([var p1 = false]) {} } -''', [ - lint(24, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 24, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceMethod_parameter_positional_hasDefault_typed() async { @@ -426,23 +478,25 @@ class C { } test_instanceMethod_parameter_positional_onExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { void m(p1) {} } -''', [ - lint(30, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(30, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_positional_onExtensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type ET(int it) { void m(p1) {} } -''', [ - lint(37, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(37, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_parameter_positional_typed() async { @@ -454,44 +508,53 @@ class C { } test_instanceMethod_parameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void m(var p1) {} } -''', [ - lint(23, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 23, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_instanceMethod_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m() {} } -''', [ - lint(12, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(12, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_returnType_onExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { m() {} } -''', [ - lint(23, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(23, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_returnType_onExtensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type ET(int it) { m() {} } -''', [ - lint(30, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(30, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceMethod_returnType_override() async { @@ -509,7 +572,8 @@ abstract class C implements I, J { } test_instanceMethod_returnType_override_inconsistentCombinedSuperSignature() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class I { int m(); } @@ -519,10 +583,12 @@ abstract class J { abstract class C implements I, J { m(); } -''', [ - // In the presense of this error, we do not report. - error(CompileTimeErrorCode.NO_COMBINED_SUPER_SIGNATURE, 104, 1), - ]); +''', + [ + // In the presense of this error, we do not report. + error(CompileTimeErrorCode.NO_COMBINED_SUPER_SIGNATURE, 104, 1), + ], + ); } test_instanceMethod_returnType_typed() async { @@ -534,13 +600,14 @@ class C { } test_instanceOperator_parameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { void operator +(p1) {} } -''', [ - lint(28, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(28, 2, correctionContains: 'Try adding a type annotation')], + ); } test_instanceOperator_parameter_typed() async { @@ -552,13 +619,14 @@ class C { } test_instanceOperator_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { operator +(int p1) {} } -''', [ - lint(21, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(21, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceOperator_returnType_typed() async { @@ -570,23 +638,25 @@ class C { } test_instanceSetter_parameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { set s(value) {} } -''', [ - lint(16, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(16, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceSetter_parameterType_inExtension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { set s(value) {} } -''', [ - lint(27, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(27, 1, correctionContains: 'Try adding a type annotation')], + ); } test_instanceSetter_returnType() async { @@ -630,13 +700,14 @@ class C { } test_staticField_multiple_someMissingInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static var x = '', y = '', z; } -''', [ - lint(39, 1, correctionContains: 'Try splitting the declaration'), - ]); +''', + [lint(39, 1, correctionContains: 'Try splitting the declaration')], + ); } test_staticField_typed() async { @@ -656,34 +727,42 @@ class C { } test_staticField_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static var f; } -''', [ - lint(23, 1, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 23, + 1, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_staticMethod_parameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m({p1}) {} } -''', [ - lint(27, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(27, 2, correctionContains: 'Try adding a type annotation')], + ); } test_staticMethod_parameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m({final p1}) {} } -''', [ - lint(33, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(33, 2, correctionContains: 'Try adding a type annotation')], + ); } test_staticMethod_parameter_named_typed() async { @@ -695,34 +774,42 @@ class C { } test_staticMethod_parameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m({var p1}) {} } -''', [ - lint(31, 2, - correctionContains: "Try replacing 'var' with a type annotation."), - ]); +''', + [ + lint( + 31, + 2, + correctionContains: "Try replacing 'var' with a type annotation.", + ), + ], + ); } test_staticMethod_parameter_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m(p1) {} } -''', [ - lint(26, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(26, 2, correctionContains: 'Try adding a type annotation')], + ); } test_staticMethod_parameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m(final p1) {} } -''', [ - lint(32, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(32, 2, correctionContains: 'Try adding a type annotation')], + ); } test_staticMethod_parameter_positional_typed() async { @@ -734,24 +821,31 @@ class C { } test_staticMethod_parameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static void m(var p1) {} } -''', [ - lint(30, 2, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 30, + 2, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } test_staticMethod_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static m() {} } -''', [ - lint(19, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(19, 1, correctionContains: 'Try adding a type annotation')], + ); } test_staticMethod_returnType_typed() async { @@ -763,19 +857,21 @@ class C { } test_topLevelFunction_parameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m({p1}) {} -''', [ - lint(8, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(8, 2, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelFunction_parameter_named_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m({final p1}) {} -''', [ - lint(14, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(14, 2, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelFunction_parameter_named_typed() async { @@ -785,28 +881,36 @@ void m({int? p1}) {} } test_topLevelFunction_parameter_named_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m({var p1}) {} -''', [ - lint(12, 2, - correctionContains: "Try replacing 'var' with a type annotation."), - ]); +''', + [ + lint( + 12, + 2, + correctionContains: "Try replacing 'var' with a type annotation.", + ), + ], + ); } test_topLevelFunction_parameter_positional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m(p1) {} -''', [ - lint(7, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(7, 2, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelFunction_parameter_positional_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m(final p1) {} -''', [ - lint(13, 2, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(13, 2, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelFunction_parameter_positional_typed() async { @@ -816,19 +920,21 @@ void m(int p1) {} } test_topLevelFunction_parameter_positional_var() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void m(var p1) {} -''', [ - lint(11, 2), - ]); +''', + [lint(11, 2)], + ); } test_topLevelFunction_returnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' m() {} -''', [ - lint(0, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(0, 1, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelFunction_returnType_typed() async { @@ -838,19 +944,21 @@ void m() {} } test_topLevelGetter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' get g => 1; -''', [ - lint(4, 1, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(4, 1, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelSetter_parameterType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' set s(value) {} -''', [ - lint(6, 5, correctionContains: 'Try adding a type annotation'), - ]); +''', + [lint(6, 5, correctionContains: 'Try adding a type annotation')], + ); } test_topLevelVariable_final() async { @@ -872,11 +980,12 @@ var x = '', y = ''; } test_topLevelVariable_multiple_someMissingInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = '', y = '', z; -''', [ - lint(20, 1, correctionContains: 'Try splitting the declaration'), - ]); +''', + [lint(20, 1, correctionContains: 'Try splitting the declaration')], + ); } test_topLevelVariable_typed() async { @@ -892,11 +1001,17 @@ var f = 0; } test_topLevelVariable_var_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f; -''', [ - lint(4, 1, - correctionContains: "Try replacing 'var' with a type annotation"), - ]); +''', + [ + lint( + 4, + 1, + correctionContains: "Try replacing 'var' with a type annotation", + ), + ], + ); } } diff --git a/pkg/linter/test/rules/test_types_in_equals_test.dart b/pkg/linter/test/rules/test_types_in_equals_test.dart index 77e362f5785d..86b6479f7527 100644 --- a/pkg/linter/test/rules/test_types_in_equals_test.dart +++ b/pkg/linter/test/rules/test_types_in_equals_test.dart @@ -18,7 +18,8 @@ class TestTypesInEqualsTest extends LintRuleTest { String get lintRule => LintNames.test_types_in_equals; test_doesNotUseIs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int? x; @@ -28,9 +29,9 @@ class C { return otherC.x == x; } } -''', [ - lint(83, 10), - ]); +''', + [lint(83, 10)], + ); } test_usesIs() async { diff --git a/pkg/linter/test/rules/throw_in_finally_test.dart b/pkg/linter/test/rules/throw_in_finally_test.dart index 2a0fa193d67b..8c02c4db07bc 100644 --- a/pkg/linter/test/rules/throw_in_finally_test.dart +++ b/pkg/linter/test/rules/throw_in_finally_test.dart @@ -47,7 +47,8 @@ class C {} } test_throwInFinally() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try { } catch (e) { @@ -59,9 +60,9 @@ class C {} } } } -''', [ - lint(74, 8), - ]); +''', + [lint(74, 8)], + ); } test_throwInInnerClosureInFinally() async { diff --git a/pkg/linter/test/rules/tighten_type_of_initializing_formals_test.dart b/pkg/linter/test/rules/tighten_type_of_initializing_formals_test.dart index 9407ca988344..4933c6e4bd9f 100644 --- a/pkg/linter/test/rules/tighten_type_of_initializing_formals_test.dart +++ b/pkg/linter/test/rules/tighten_type_of_initializing_formals_test.dart @@ -18,7 +18,8 @@ class TightenTypeOfInitializingFormalsTest extends LintRuleTest { String get lintRule => LintNames.tighten_type_of_initializing_formals; test_superInit() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; A(this.a); @@ -31,26 +32,27 @@ class B extends A { class C extends A { C(super.a) : assert(a != null); } -''', [ - lint(107, 7), - ]); +''', + [lint(107, 7)], + ); } test_thisInit_asserts() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? p; A(this.p) : assert(p != null); A.a(this.p) : assert(null != p); } -''', [ - lint(27, 6), - lint(62, 6), - ]); +''', + [lint(27, 6), lint(62, 6)], + ); } test_thisInit_asserts_positionalParams() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A( this.p1, @@ -69,10 +71,9 @@ class A { String? p4; String? p5; } -''', [ - lint(19, 7), - lint(63, 7), - ]); +''', + [lint(19, 7), lint(63, 7)], + ); } test_thisInit_noAssert() async { @@ -85,16 +86,19 @@ class A { } test_thisInit_tightens() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? p; A(String this.p) : assert(p != null); A.a(String this.p) : assert(null != p); } -''', [ - // No lint - error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 53, 7), - error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 93, 7), - ]); +''', + [ + // No lint + error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 53, 7), + error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_TRUE, 93, 7), + ], + ); } } diff --git a/pkg/linter/test/rules/type_annotate_public_apis_test.dart b/pkg/linter/test/rules/type_annotate_public_apis_test.dart index 947ecb33ef9d..017175cdb4e7 100644 --- a/pkg/linter/test/rules/type_annotate_public_apis_test.dart +++ b/pkg/linter/test/rules/type_annotate_public_apis_test.dart @@ -35,9 +35,7 @@ augment class A { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(43, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(43, 1)]); } test_augmentationClass_method() async { @@ -56,9 +54,7 @@ augment class A { '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(46, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(46, 1)]); } test_augmentationTopLevelFunction() async { @@ -73,9 +69,7 @@ void f(x) { } '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(26, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(26, 1)]); } test_augmentationTopLevelVariable() async { @@ -90,9 +84,7 @@ var x; '''); await assertNoDiagnosticsInFile(a.path); - await assertDiagnosticsInFile(b.path, [ - lint(23, 1), - ]); + await assertDiagnosticsInFile(b.path, [lint(23, 1)]); } test_augmentedField() async { @@ -112,9 +104,7 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(32, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(32, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -135,9 +125,7 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(35, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(35, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -154,9 +142,7 @@ part of 'a.dart'; augment void f(x) { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(23, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(23, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -173,9 +159,7 @@ part of 'a.dart'; augment var x; '''); - await assertDiagnosticsInFile(a.path, [ - lint(20, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(20, 1)]); await assertNoDiagnosticsInFile(b.path); } @@ -188,24 +172,26 @@ class A { } test_instanceField_onClass_hasVar_noInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { var x; } -''', [ - lint(16, 1), - ]); +''', + [lint(16, 1)], + ); } test_instanceField_onClass_inDeclarationList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { // ignore: unused_field var x, _y; } -''', [ - lint(42, 1), - ]); +''', + [lint(42, 1)], + ); } test_instanceField_onClass_noInitializer() async { @@ -217,13 +203,14 @@ class A { } test_instanceField_onClass_nullInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { final n = null; } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_instanceGetter_onClass() async { @@ -235,75 +222,82 @@ class A { } test_instanceGetter_onClass_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { get x => 42; } -''', [ - lint(16, 1), - ]); +''', + [lint(16, 1)], + ); } test_instanceGetter_onExtension_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { get x => 0; } -''', [ - lint(27, 1), - ]); +''', + [lint(27, 1)], + ); } test_instanceMethod_onClass_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { m() {} } -''', [ - lint(12, 1), - ]); +''', + [lint(12, 1)], + ); } test_instanceMethod_onClass_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m(x) {} } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_instanceMethod_onExtension_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { f() {} } -''', [ - lint(23, 1), - ]); +''', + [lint(23, 1)], + ); } test_instanceMethod_onExtension_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { void m(p) {} } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_instanceMethod_onExtensionType_noReturnType() async { // One test should be sufficient to verify extension type // support as the logic is implemented commonly for all members. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { m() {} } -''', [ - lint(28, 1), - ]); +''', + [lint(28, 1)], + ); } test_instanceMethod_parameterNameIsMultipleUnderscores() async { @@ -331,23 +325,25 @@ class A { } test_instanceSetter_onClass_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { set x(p) {} } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_instanceSetter_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int { set x(p) {} } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_instanceSetter_private_parameterMissingType() async { @@ -393,13 +389,14 @@ class A { } test_staticField_nullInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static final x = null; } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_staticField_withInitializer() async { @@ -411,33 +408,36 @@ class A { } test_staticMethod_onClass_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static m() {} } -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_staticMethod_onClass_parameterHasVar() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static void m(var p) {} } -''', [ - lint(26, 5), - ]); +''', + [lint(26, 5)], + ); } test_staticMethod_onClass_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static void m(p) {} } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_topLevelConst() async { @@ -447,19 +447,21 @@ const x = ''; } test_topLevelFunction_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() {} -''', [ - lint(0, 1), - ]); +''', + [lint(0, 1)], + ); } test_topLevelFunction_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(x) {} -''', [ - lint(7, 1), - ]); +''', + [lint(7, 1)], + ); } test_topLevelGetter_hasReturnType() async { @@ -469,11 +471,12 @@ int get x => 42; } test_topLevelGetter_noReturnType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' get x => 42; -''', [ - lint(4, 1), - ]); +''', + [lint(4, 1)], + ); } test_topLevelSetter_parameterHasType() async { @@ -483,19 +486,21 @@ set x(int p) {} } test_topLevelSetter_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' set x(p) {} -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_typedefLegacy_parameterMissingType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef F(x); -''', [ - lint(8, 1), - ]); +''', + [lint(8, 1)], + ); } test_typedefLegacy_private_parameterHasType() async { diff --git a/pkg/linter/test/rules/type_init_formals_test.dart b/pkg/linter/test/rules/type_init_formals_test.dart index 93e8d79af84d..d0d84d1b1386 100644 --- a/pkg/linter/test/rules/type_init_formals_test.dart +++ b/pkg/linter/test/rules/type_init_formals_test.dart @@ -18,29 +18,41 @@ class TypeInitFormalsTest extends LintRuleTest { String get lintRule => LintNames.type_init_formals; test_extraPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? p1; String p2 = ''; A.y({required String? this.p2}); } -''', [ - // No lint - error(CompileTimeErrorCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE, 49, - 24), - ]); +''', + [ + // No lint + error( + CompileTimeErrorCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE, + 49, + 24, + ), + ], + ); } test_initializingFormalForNonExistentField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class Invalid { Invalid(int this.x); // OK } -''', [ - // No lint - error(CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, 26, - 10), - ]); +''', + [ + // No lint + error( + CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD, + 26, + 10, + ), + ], + ); } test_requiredConstructorParam_tightening() async { @@ -53,29 +65,32 @@ class A { } test_requiredConstructorParam_unnecessaryNullableType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? s; A({required String? this.s}); } -''', [ - lint(37, 7), - ]); +''', + [lint(37, 7)], + ); } test_requiredConstructorParam_unnecessaryType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String s = ''; A({required String this.s}); } -''', [ - lint(41, 6), - ]); +''', + [lint(41, 6)], + ); } test_super() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String? a; A({this.a}); @@ -84,9 +99,9 @@ class A { class B extends A { B({String? super.a}); } -''', [ - lint(66, 7), - ]); +''', + [lint(66, 7)], + ); } test_typed_fieldIsDynamic() async { @@ -99,14 +114,15 @@ class C { } test_typed_sameAsField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x; C(int this.x); } -''', [ - lint(23, 3), - ]); +''', + [lint(23, 3)], + ); } test_typed_subtypeOfField() async { diff --git a/pkg/linter/test/rules/type_literal_in_constant_pattern_test.dart b/pkg/linter/test/rules/type_literal_in_constant_pattern_test.dart index 0a188c515da9..fd646b0a5983 100644 --- a/pkg/linter/test/rules/type_literal_in_constant_pattern_test.dart +++ b/pkg/linter/test/rules/type_literal_in_constant_pattern_test.dart @@ -26,53 +26,58 @@ void f(Object? x) { } test_constNotType_matchType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Type x) { if (x case 0) {} } -''', [ - error(WarningCode.CONSTANT_PATTERN_NEVER_MATCHES_VALUE_TYPE, 30, 1), - ]); +''', + [error(WarningCode.CONSTANT_PATTERN_NEVER_MATCHES_VALUE_TYPE, 30, 1)], + ); } test_constType_matchDynamic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic x) { if (x case int) {} } -''', [ - lint(33, 3), - ]); +''', + [lint(33, 3)], + ); } test_constType_matchObject() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object x) { if (x case int) {} } -''', [ - lint(32, 3), - ]); +''', + [lint(32, 3)], + ); } test_constType_matchObjectNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object? x) { if (x case int) {} } -''', [ - lint(33, 3), - ]); +''', + [lint(33, 3)], + ); } test_constType_matchType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Type x) { if (x case int) {} } -''', [ - lint(30, 3), - ]); +''', + [lint(30, 3)], + ); } test_constType_matchType_explicitConst() async { @@ -84,7 +89,8 @@ void f(Type x) { } test_constType_matchType_nested() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A x) { if (x case A(type: int)) {} } @@ -93,29 +99,31 @@ class A { final Type type; A(this.type); } -''', [ - lint(35, 3), - ]); +''', + [lint(35, 3)], + ); } test_constType_matchTypeParameter_boundObjectNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(T x) { if (x case int) {} } -''', [ - lint(46, 3), - ]); +''', + [lint(46, 3)], + ); } /// Nobody will write such code, but just in case. test_constType_matchTypeParameter_boundType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(T x) { if (x case int) {} } -''', [ - lint(43, 3), - ]); +''', + [lint(43, 3)], + ); } } diff --git a/pkg/linter/test/rules/unawaited_futures_test.dart b/pkg/linter/test/rules/unawaited_futures_test.dart index 46c07ca095ae..41fae6fba8d8 100644 --- a/pkg/linter/test/rules/unawaited_futures_test.dart +++ b/pkg/linter/test/rules/unawaited_futures_test.dart @@ -19,15 +19,16 @@ class UnawaitedFuturesTest extends LintRuleTest { test_classImplementsFuture() async { // https://github.com/dart-lang/linter/issues/2211 - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Future2 p) async { g(p); } Future2 g(Future2 p) => p; abstract class Future2 implements Future {} -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_functionCall_assigned() async { @@ -60,14 +61,15 @@ Future g() => Future.value(0); } test_functionCall_interpolated_unawaited() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async { '${g()}'; } Future g() => Future.value(0); -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_functionCall_returnedWithFutureType() async { @@ -80,14 +82,15 @@ Future g() => Future.value(0); } test_functionCall_unawaited() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async { g(); } Future g() => Future.value(0); -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_functionCallInCascade_assignment() async { @@ -103,16 +106,17 @@ class C { } test_functionCallInCascade_inAsync() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async { C()..doAsync(); } class C { Future doAsync() async {} } -''', [ - lint(22, 11), - ]); +''', + [lint(22, 11)], + ); } test_functionCallInCascade_indexAssignment() async { @@ -140,14 +144,17 @@ class C { } test_undefinedIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() async { Duration d = Duration(); Future.delayed(d, bar); } -''', [ - // No lint - error(CompileTimeErrorCode.UNDEFINED_IDENTIFIER, 59, 3), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.UNDEFINED_IDENTIFIER, 59, 3), + ], + ); } } diff --git a/pkg/linter/test/rules/unintended_html_in_doc_comment_test.dart b/pkg/linter/test/rules/unintended_html_in_doc_comment_test.dart index 326e48c27dc1..0e4e3e48a76b 100644 --- a/pkg/linter/test/rules/unintended_html_in_doc_comment_test.dart +++ b/pkg/linter/test/rules/unintended_html_in_doc_comment_test.dart @@ -53,13 +53,16 @@ class C {} } test_codeSpan_backSlashEscaped() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// \\\`List ` class C {} -''', [ - lint(12, 5), // - lint(18, 5), // - ]); +''', + [ + lint(12, 5), // + lint(18, 5), // + ], + ); } test_codeSpan_longQuote() async { @@ -78,12 +81,15 @@ class C {} test_codeSpan_unterminated() async { // An unterminated long code span has no effect. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// A ```List and quoted `` example class C {} -''', [ - lint(13, 5), // - ]); +''', + [ + lint(13, 5), // + ], + ); } test_hangingAngleBracket_left() async { @@ -174,21 +180,27 @@ class C {} } test_unintendedHtml() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text List. class C {} -''', [ - lint(13, 5), // - ]); +''', + [ + lint(13, 5), // + ], + ); } test_unintendedHtml_javaDoc() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** Text List. */ class C {} -''', [ - lint(13, 5), // - ]); +''', + [ + lint(13, 5), // + ], + ); } test_unintendedHtml_javaDoc_codeSpan() async { @@ -199,47 +211,59 @@ class C {} } test_unintendedHtml_javaDoc_multiline() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /** * Text List. */ class C {} -''', [ - lint(17, 5), // - ]); +''', + [ + lint(17, 5), // + ], + ); } test_unintendedHtml_multipleDocComments() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text List. class A {} /// Text List. class C {} -''', [ - lint(40, 5), // - ]); +''', + [ + lint(40, 5), // + ], + ); } test_unintendedHtml_multipleLines() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text List. /// Text List. class C {} -''', [ - lint(28, 5), // - ]); +''', + [ + lint(28, 5), // + ], + ); } test_unintendedHtml_nested() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text List>. class C {} -''', [ - // This is how HTML parses the tag, from the first opening angle bracket - // to the first closing angle bracket. - lint(13, 10), // - ]); +''', + [ + // This is how HTML parses the tag, from the first opening angle bracket + // to the first closing angle bracket. + lint(13, 10), // + ], + ); } test_unintendedHtml_reference_withTypeArgument() async { @@ -250,22 +274,28 @@ class C {} } test_unintendedHtml_spaces() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// Text . class C {} -''', [ - lint(9, 16), // - ]); +''', + [ + lint(9, 16), // + ], + ); } test_unintendedHtml_tags_slash() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// class C {} -''', [ - lint(4, 6), // - lint(11, 6), // - ]); +''', + [ + lint(4, 6), // + lint(11, 6), // + ], + ); } test_unintendedHtml_tagsEntity() async { @@ -283,13 +313,16 @@ class C {} } test_unintendedHtml_tagsMultiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' /// -> = class C {} -''', [ - lint(4, 12), // - lint(20, 10), // - lint(33, 12), // - ]); +''', + [ + lint(4, 12), // + lint(20, 10), // + lint(33, 12), // + ], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_async_test.dart b/pkg/linter/test/rules/unnecessary_async_test.dart index d0c449833522..c4b89dcda7f3 100644 --- a/pkg/linter/test/rules/unnecessary_async_test.dart +++ b/pkg/linter/test/rules/unnecessary_async_test.dart @@ -40,15 +40,16 @@ void useFunction(void Function() x) {} } test_closure_imposedReturnTypeVoid_noAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { useFunction(() async {}); } void useFunction(void Function() x) {} -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_closure_noImposedReturnType_hasAwait() async { @@ -62,60 +63,63 @@ void f() { } test_closure_noImposedReturnType_noAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var v = () async {}; } -''', [ - lint(24, 5), - ]); +''', + [lint(24, 5)], + ); } test_localFunction_void_hasAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { void f() async { await 0; } } -''', [ - error(WarningCode.UNUSED_ELEMENT, 20, 1), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 20, 1)], + ); } test_localFunction_void_noAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { void f() async {} } -''', [ - error(WarningCode.UNUSED_ELEMENT, 20, 1), - lint(24, 5), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 20, 1), lint(24, 5)], + ); } test_localFunction_void_noAwait_outerHasAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future foo() async { void f() async {} await 0; } -''', [ - error(WarningCode.UNUSED_ELEMENT, 34, 1), - lint(38, 5), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 34, 1), lint(38, 5)], + ); } test_method_future_returnFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { Future f() async { return Future.value(0); } } -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_method_future_returnValue() async { @@ -129,7 +133,8 @@ class A { } test_method_futureOr_returnFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; class A { @@ -137,13 +142,14 @@ class A { return Future.value(0); } } -''', [ - lint(52, 5), - ]); +''', + [lint(52, 5)], + ); } test_method_futureOr_returnValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; class A { @@ -151,9 +157,9 @@ class A { return 0; } } -''', [ - lint(52, 5), - ]); +''', + [lint(52, 5)], + ); } test_method_void_hasAwaitExpression() async { @@ -167,13 +173,14 @@ class A { } test_method_void_noAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void f() async {} } -''', [ - lint(21, 5), - ]); +''', + [lint(21, 5)], + ); } test_topLevelFunction_block_future_intNullable_returnNullable() async { @@ -193,7 +200,8 @@ dynamic f() async { } test_topLevelFunction_blockBody_future_int_hasReturn_futureCustom() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { return MyFuture.value(0); } @@ -204,19 +212,20 @@ class MyFuture implements Future { @override noSuchMethod(invocation) => super.noSuchMethod(invocation); } -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_topLevelFunction_blockBody_future_int_returnFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { return Future.value(0); } -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_topLevelFunction_blockBody_future_int_returnValue() async { @@ -236,7 +245,8 @@ Future f() async { } test_topLevelFunction_blockBody_future_void_hasReturn_future() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { return foo(); } @@ -244,9 +254,9 @@ Future f() async { Future foo() { return Future.value(); } -''', [ - lint(17, 5), - ]); +''', + [lint(17, 5)], + ); } test_topLevelFunction_blockBody_future_void_hasReturn_nothing() async { @@ -284,13 +294,14 @@ Future f() async { } test_topLevelFunction_blockBody_futureNullable_int_hasReturn_future() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future? f() async { return Future.value(0); } -''', [ - lint(17, 5), - ]); +''', + [lint(17, 5)], + ); } test_topLevelFunction_blockBody_futureNullable_int_hasReturn_value() async { @@ -310,11 +321,12 @@ Future? f() async { } test_topLevelFunction_blockBody_futureNullable_intNullable_noReturn() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future? f() async {} -''', [ - error(WarningCode.BODY_MIGHT_COMPLETE_NORMALLY_NULLABLE, 14, 1), - ]); +''', + [error(WarningCode.BODY_MIGHT_COMPLETE_NORMALLY_NULLABLE, 14, 1)], + ); } test_topLevelFunction_blockBody_futureNullable_void_hasReturn_nothing() async { @@ -352,27 +364,29 @@ Future? f() async { } test_topLevelFunction_blockBody_futureOr_returnFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; FutureOr f() async { return Future.value(0); } -''', [ - lint(40, 5), - ]); +''', + [lint(40, 5)], + ); } test_topLevelFunction_blockBody_futureOr_returnValue() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; FutureOr f() async { return 0; } -''', [ - lint(40, 5), - ]); +''', + [lint(40, 5)], + ); } test_topLevelFunction_blockBody_object() async { @@ -410,31 +424,34 @@ void f(Stream values) async { } test_topLevelFunction_blockBody_void_hasAwait_nestedFunctionExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async { () async { await 0; }(); } -''', [ - lint(9, 5), - ]); +''', + [lint(9, 5)], + ); } test_topLevelFunction_blockBody_void_noAwait() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() async {} -''', [ - lint(9, 5), - ]); +''', + [lint(9, 5)], + ); } test_topLevelFunction_exprBody_future_int_returnFuture() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async => Future.value(0); -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_topLevelFunction_exprBody_future_int_returnValue() async { diff --git a/pkg/linter/test/rules/unnecessary_await_in_return_test.dart b/pkg/linter/test/rules/unnecessary_await_in_return_test.dart index 041beaaa4bfb..95a65cde063e 100644 --- a/pkg/linter/test/rules/unnecessary_await_in_return_test.dart +++ b/pkg/linter/test/rules/unnecessary_await_in_return_test.dart @@ -18,12 +18,13 @@ class UnnecessaryAwaitInReturnTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_await_in_return; test_asyncArrow_awaited() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async => await future; final future = Future.value(1); -''', [ - lint(25, 5), - ]); +''', + [lint(25, 5)], + ); } test_asyncArrow_awaited_futureOfFuture() async { @@ -34,26 +35,28 @@ final future = Future>.value(Future.value(1)); } test_asyncArrow_awaited_instanceMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { Future f() async => await future; } final future = Future.value(1); -''', [ - lint(37, 5), - ]); +''', + [lint(37, 5)], + ); } test_asyncArrow_awaited_subtype() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { Future foo() async => 1; Future bar() async => await foo() as int; Future buzz() async => await bar(); } -''', [ - lint(121, 5), - ]); +''', + [lint(121, 5)], + ); } test_asyncArrow_awaited_withAs() async { @@ -82,14 +85,15 @@ final future = Future.value(1); } test_asyncBlock_awaited() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { return await future; } final future = Future.value(1); -''', [ - lint(33, 5), - ]); +''', + [lint(33, 5)], + ); } test_asyncBlock_awaited_futureOfFuture() async { @@ -102,20 +106,22 @@ final future = Future>.value(Future.value(1)); } test_asyncBlock_awaited_instanceMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { Future f() async { return await future; } } final future = Future.value(1); -''', [ - lint(47, 5), - ]); +''', + [lint(47, 5)], + ); } test_asyncBlock_awaited_inTry() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f() async { try { return await future; @@ -124,13 +130,14 @@ Future f() async { } } final future = Future.value(1); -''', [ - lint(88, 5), - ]); +''', + [lint(88, 5)], + ); } test_asyncBlock_awaited_inTry_instanceMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { Future f() async { try { @@ -141,9 +148,9 @@ class A { } } final future = Future.value(1); -''', [ - lint(108, 5), - ]); +''', + [lint(108, 5)], + ); } test_asyncBlock_notAwaited() async { diff --git a/pkg/linter/test/rules/unnecessary_brace_in_string_interps_test.dart b/pkg/linter/test/rules/unnecessary_brace_in_string_interps_test.dart index 96eaf2b697de..d375286922cf 100644 --- a/pkg/linter/test/rules/unnecessary_brace_in_string_interps_test.dart +++ b/pkg/linter/test/rules/unnecessary_brace_in_string_interps_test.dart @@ -18,13 +18,14 @@ class UnnecessaryBraceInStringInterpsTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_brace_in_string_interps; test_braces_bangAfter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print('hello ${int}!'); } -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_braces_nonSimpleIdentifier() async { @@ -45,13 +46,14 @@ void f() { } test_braces_simpleIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print('hello ${int}'); } -''', [ - lint(26, 6), - ]); +''', + [lint(26, 6)], + ); } test_braces_simpleIdentifier_numberAfter() async { @@ -95,13 +97,14 @@ void f() { } test_simpleIdentifier() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void hi(String name) { print('hi: ${name}'); } -''', [ - lint(36, 7), - ]); +''', + [lint(36, 7)], + ); } test_simpleIdentifier_suffixed() async { @@ -124,15 +127,16 @@ class A { /// https://github.com/dart-lang/linter/issues/3691 test_thisExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void hi() { print('hi: ${this}'); } } -''', [ - lint(39, 7), - ]); +''', + [lint(39, 7)], + ); } test_thisExpression_suffixed() async { diff --git a/pkg/linter/test/rules/unnecessary_breaks_test.dart b/pkg/linter/test/rules/unnecessary_breaks_test.dart index 5b7e88b089b0..29bb1b844e86 100644 --- a/pkg/linter/test/rules/unnecessary_breaks_test.dart +++ b/pkg/linter/test/rules/unnecessary_breaks_test.dart @@ -18,7 +18,8 @@ class UnnecessaryBreaksTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_breaks; test_default() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch (1) { case 1: @@ -28,9 +29,9 @@ f() { break; } } -''', [ - lint(74, 6), - ]); +''', + [lint(74, 6)], + ); } test_default_empty() async { @@ -55,7 +56,8 @@ f() { test_default_notLast_ok() async { // No lint is needed because there is already a DEAD_CODE warning. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(bool c) { switch (1) { case 1: @@ -65,10 +67,12 @@ f(bool c) { f(true); } } -''', [ - // No lint. - error(WarningCode.DEAD_CODE, 86, 8), - ]); +''', + [ + // No lint. + error(WarningCode.DEAD_CODE, 86, 8), + ], + ); } test_switch_pre30_default_ok() async { @@ -98,7 +102,8 @@ f() { } test_switchPatternCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch (1) { case 1: @@ -108,9 +113,9 @@ f() { f(); } } -''', [ - lint(50, 6), - ]); +''', + [lint(50, 6)], + ); } test_switchPatternCase_default_ok() async { @@ -141,8 +146,7 @@ f() { } test_switchPatternCase_labeled_ok() async { - await assertNoDiagnostics( - r''' + await assertNoDiagnostics(r''' f() { l: switch (1) { @@ -152,8 +156,7 @@ f() { f(); } } -''', - ); +'''); } test_switchPatternCase_notDirectChild_ok() async { @@ -171,7 +174,8 @@ f(bool c) { } test_switchPatternCase_notLast_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(bool c) { switch (1) { case 1: @@ -181,9 +185,11 @@ f(bool c) { f(true); } } -''', [ - // No lint. - error(WarningCode.DEAD_CODE, 58, 8), - ]); +''', + [ + // No lint. + error(WarningCode.DEAD_CODE, 58, 8), + ], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_const_test.dart b/pkg/linter/test/rules/unnecessary_const_test.dart index 99f2bf7667ad..23321ee293fd 100644 --- a/pkg/linter/test/rules/unnecessary_const_test.dart +++ b/pkg/linter/test/rules/unnecessary_const_test.dart @@ -62,38 +62,42 @@ void f(Object o) { } test_constConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { const C(); } const c = const C(); -''', [ - lint(35, 5), - ]); +''', + [lint(35, 5)], + ); } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const l = const []; -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_mapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const m = const {1: 1}; -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_setLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const s = const {1}; -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } } @@ -112,36 +116,39 @@ class A { } test_constVariable_constCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const x = const A(); class A { const A(); } -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_constVariable_constCall_newName_noArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const x = const A.new(); class A { const A(); } -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_constVariable_constCall_nonConstArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const x = const A([]); class A { const A(Object o); } -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_constVariable_nonConstCall() async { @@ -273,11 +280,12 @@ class A { } test_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const r = const (a: 1); -''', [ - lint(10, 5), - ]); +''', + [lint(10, 5)], + ); } test_recordLiteral_ok() async { @@ -287,36 +295,39 @@ const r = (a: 1); } test_variable_constCall_constListArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = const A(const []); class A { const A(Object o); } -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_variable_constCall_constSetArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = const A(const {}); class A { const A(Object o); } -''', [ - lint(16, 5), - ]); +''', + [lint(16, 5)], + ); } test_variable_constCall_newName_constArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = const A.new(const []); class A { const A(Object o); } -''', [ - lint(20, 5), - ]); +''', + [lint(20, 5)], + ); } test_variable_constCall_nonConstArgument() async { diff --git a/pkg/linter/test/rules/unnecessary_constructor_name_test.dart b/pkg/linter/test/rules/unnecessary_constructor_name_test.dart index 6f6664e94bb8..a674ee9ec9d9 100644 --- a/pkg/linter/test/rules/unnecessary_constructor_name_test.dart +++ b/pkg/linter/test/rules/unnecessary_constructor_name_test.dart @@ -26,29 +26,34 @@ class A { } test_constructorDeclaration_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.new(); } -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } @FailingTest( - reason: - 'https://github.com/dart-lang/linter/pull/4677#discussion_r1291784807') + reason: + 'https://github.com/dart-lang/linter/pull/4677#discussion_r1291784807', + ) test_constructorDeclaration_new_alreadyDefined() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(); A.new(); } -''', [ - error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 19, 5), - // A lint should likely not get reported here since we're already - // producing a compilation error. - ]); +''', + [ + error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 19, 5), + // A lint should likely not get reported here since we're already + // producing a compilation error. + ], + ); } test_constructorTearoff_new() async { @@ -60,32 +65,37 @@ var makeA = A.new; } test_extensionTypeDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { E.new(this.i); } -''', [ - // No lint. - error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 28, 5), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT, 28, 5), + ], + ); } test_extensionTypeDeclaration_primaryNamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E.a(int i) { E.new(this.i); } -''', [ - lint(32, 3), - ]); +''', + [lint(32, 3)], + ); } test_extensionTypeDeclaration_primaryNamedNew() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E.new(int i) { } -''', [ - lint(17, 3), - ]); +''', + [lint(17, 3)], + ); } test_instanceCreation_named() async { @@ -98,12 +108,13 @@ var aaa = A.ok(); } test_instanceCreation_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} var a = A.new(); -''', [ - lint(21, 3), - ]); +''', + [lint(21, 3)], + ); } test_instanceCreation_unnamed() async { diff --git a/pkg/linter/test/rules/unnecessary_final_test.dart b/pkg/linter/test/rules/unnecessary_final_test.dart index 590325204d6f..18e7b79e6a6f 100644 --- a/pkg/linter/test/rules/unnecessary_final_test.dart +++ b/pkg/linter/test/rules/unnecessary_final_test.dart @@ -26,13 +26,14 @@ class C { } test_forEachLoopVariable_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (final x in []) {} } -''', [ - lint(18, 5), - ]); +''', + [lint(18, 5)], + ); } test_forEachLoopVariable_var() async { @@ -44,56 +45,61 @@ void f() { } test_listPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final [a] = [1]; } -''', [ - lint(8, 5), - ]); +''', + [lint(8, 5)], + ); } test_listPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case [int x, final int y]) {} } -''', [ - lint(35, 5), - ]); +''', + [lint(35, 5)], + ); } test_localVariable_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final x = 1; } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_localVariable_final_wildcard() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final _ = ''; } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_localVariable_final_wildcard_preWildcards() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // @dart = 3.4 // (pre wildcard-variables) void f() { final _ = ''; } -''', [ - lint(57, 5), - ]); +''', + [lint(57, 5)], + ); } test_localVariable_var() async { @@ -105,27 +111,30 @@ void f() { } test_mapPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final {'a': a} = {'a': 1}; } -''', [ - lint(8, 5), - ]); +''', + [lint(8, 5)], + ); } test_mapPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case {'x': final x, 'y' : var y}) {} } -''', [ - lint(33, 5), - ]); +''', + [lint(33, 5)], + ); } test_objectPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int c; C(this.c); @@ -134,9 +143,9 @@ class C { f() { final C(:c) = C(1); } -''', [ - lint(43, 5), - ]); +''', + [lint(43, 5)], + ); } test_objectPattern_destructured_ok() async { @@ -153,7 +162,8 @@ f() { } test_objectPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int c; int d; @@ -163,13 +173,14 @@ class C { f(Object o) { if (o case C(c: final x, d: var y)) {} } -''', [ - lint(84, 5), - ]); +''', + [lint(84, 5)], + ); } test_objectPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int a; A(this.a); @@ -180,17 +191,18 @@ f() { case A(a: >0 && final b): } } -''', [ - lint(79, 5), - ]); +''', + [lint(79, 5)], + ); } test_parameter_function_finalTyped() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(final int x) {} -''', [ - lint(7, 5), - ]); +''', + [lint(7, 5)], + ); } test_parameter_function_typed() async { @@ -201,13 +213,14 @@ void f(int x) { } test_parameter_functionExpression_final() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (final c) => c.length; } -''', [ - lint(14, 5), - ]); +''', + [lint(14, 5)], + ); } test_parameter_functionExpression_typed() async { @@ -219,23 +232,25 @@ void f() { } test_recordPattern_destructured() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final (a, b) = (1, 2); } -''', [ - lint(8, 5), - ]); +''', + [lint(8, 5)], + ); } test_recordPattern_destructured_forEach() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { for (final (a, b) in [(1, 2)]) { } } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_recordPattern_destructured_ok() async { @@ -247,13 +262,14 @@ f() { } test_recordPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f(Object o) { if (o case (final int x, int y)) {} } -''', [ - lint(28, 5), - ]); +''', + [lint(28, 5)], + ); } test_recordPattern_ifCase_ok() async { @@ -265,15 +281,15 @@ f(Object o) { } test_recordPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { switch ((1, 2)) { case (final a, final b): } } -''', [ - lint(36, 5), - lint(45, 5), - ]); +''', + [lint(36, 5), lint(45, 5)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_getters_setters_test.dart b/pkg/linter/test/rules/unnecessary_getters_setters_test.dart index c98bff3fcdee..cfbc09658d9f 100644 --- a/pkg/linter/test/rules/unnecessary_getters_setters_test.dart +++ b/pkg/linter/test/rules/unnecessary_getters_setters_test.dart @@ -126,14 +126,13 @@ augment class A { } '''); - await assertDiagnosticsInFile(a.path, [ - lint(52, 1), - ]); + await assertDiagnosticsInFile(a.path, [lint(52, 1)]); await assertNoDiagnosticsInFile(b.path); } test_unnecessary_getterAndSetter_extensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { static int? _x; static int? get x => _x; @@ -141,13 +140,14 @@ extension type E(int i) { _x = value; } } -''', [ - lint(62, 1), - ]); +''', + [lint(62, 1)], + ); } test_unnecessary_getterAndSetterHaveBlockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? _x; @@ -158,13 +158,14 @@ class C { _x = value; } } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_unnecessary_getterHasExpressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? _x; @@ -174,13 +175,14 @@ class C { _x = value; } } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_unnecessary_setterHasExpressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { String? _x; @@ -189,8 +191,8 @@ class C { } set x(String? value) => _x = value; } -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_lambdas_test.dart b/pkg/linter/test/rules/unnecessary_lambdas_test.dart index 870034be7383..60541b679856 100644 --- a/pkg/linter/test/rules/unnecessary_lambdas_test.dart +++ b/pkg/linter/test/rules/unnecessary_lambdas_test.dart @@ -45,13 +45,14 @@ var x = [].map((e) => C.new(e)); newFile('$testPackageLibPath/b.dart', r''' class C {} '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'b.dart' as b; var x = [() => b.C()]; -''', [ - lint(32, 11), - ]); +''', + [lint(32, 11)], + ); } test_constructorCall_importedDeferred() async { @@ -84,12 +85,13 @@ var x = [].map((e) => C.named(e)); } test_constructorCall_noArgs() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} var x = [() => C()]; -''', [ - lint(20, 9), - ]); +''', + [lint(20, 9)], + ); } test_constructorCall_noParameter_oneArg() async { @@ -151,22 +153,24 @@ var x = [() => f()]; } test_functionCall_matchingArg() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [].forEach((x) => print(x)); -''', [ - lint(19, 15), - ]); +''', + [lint(19, 15)], + ); } test_functionCall_singleStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final f = () {}; final l = () { f(); }; -''', [ - lint(27, 13), - ]); +''', + [lint(27, 13)], + ); } test_functionTearoff() async { @@ -179,15 +183,16 @@ var x = [].forEach(print); newFile('$testPackageLibPath/b.dart', r''' bool isB(Object o) => true; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'b.dart' as b; void f() { [].where((o) => b.isB(o)); } -''', [ - lint(45, 15), - ]); +''', + [lint(45, 15)], + ); } test_importedFunction_deferred() async { @@ -268,14 +273,15 @@ void f() { } test_methodCallOnFinalLocal_matchingArg() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { final l = []; [].where((e) => l.contains(e)); } -''', [ - lint(38, 20), - ]); +''', + [lint(38, 20)], + ); } test_methodCallOnLateFinalLocal_matchingArg() async { @@ -327,7 +333,8 @@ void f() { } test_noParameter_targetIsFinalField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { final f = 1; Function m() { @@ -336,9 +343,9 @@ class C { }; } } -''', [ - lint(53, 30), - ]); +''', + [lint(53, 30)], + ); } test_noParameter_targetIsGetter() async { @@ -356,13 +363,14 @@ class C { } test_targetIsFinalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List list) { list.where((final e) => ((a) => e.contains(a))(e)); } -''', [ - lint(55, 20), - ]); +''', + [lint(55, 20)], + ); } test_targetIsVarParameter() async { diff --git a/pkg/linter/test/rules/unnecessary_late_test.dart b/pkg/linter/test/rules/unnecessary_late_test.dart index 7e78a804d45a..8da04e530c3e 100644 --- a/pkg/linter/test/rules/unnecessary_late_test.dart +++ b/pkg/linter/test/rules/unnecessary_late_test.dart @@ -28,12 +28,13 @@ class C { } test_multipleVariables_eachHasInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' late String a = '', b = ''; -''', [ - lint(0, 4), - ]); +''', + [lint(0, 4)], + ); } test_multipleVariables_oneHasInitializer_oneHasNoInitializer() async { @@ -43,13 +44,14 @@ late String a, b = ''; } test_static_initializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { static late String a = ''; } -''', [ - lint(19, 4), - ]); +''', + [lint(19, 4)], + ); } test_static_noInitializer() async { @@ -69,11 +71,12 @@ class C { } test_topLevel_initializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' late String a = ''; -''', [ - lint(0, 4), - ]); +''', + [lint(0, 4)], + ); } test_topLevel_noInitializer() async { diff --git a/pkg/linter/test/rules/unnecessary_library_directive_test.dart b/pkg/linter/test/rules/unnecessary_library_directive_test.dart index 3deed35711b7..dde4c87435eb 100644 --- a/pkg/linter/test/rules/unnecessary_library_directive_test.dart +++ b/pkg/linter/test/rules/unnecessary_library_directive_test.dart @@ -50,10 +50,11 @@ part 'part.dart'; } test_unnecessary() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library lib; -''', [ - lint(0, 12), - ]); +''', + [lint(0, 12)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_library_name_test.dart b/pkg/linter/test/rules/unnecessary_library_name_test.dart index c02d7151ad95..2716445f6ee7 100644 --- a/pkg/linter/test/rules/unnecessary_library_name_test.dart +++ b/pkg/linter/test/rules/unnecessary_library_name_test.dart @@ -18,11 +18,12 @@ class UnnecessaryLibraryNameTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_library_name; test_namedLibrary() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library name; -''', [ - lint(8, 4), - ]); +''', + [lint(8, 4)], + ); } test_namedLibrary_preUnnamedLibraries() async { diff --git a/pkg/linter/test/rules/unnecessary_new_test.dart b/pkg/linter/test/rules/unnecessary_new_test.dart index d533025c3c69..1bbfd8aebbc6 100644 --- a/pkg/linter/test/rules/unnecessary_new_test.dart +++ b/pkg/linter/test/rules/unnecessary_new_test.dart @@ -18,7 +18,8 @@ class UnnecessaryNewTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_new; test_named_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named(); } @@ -26,9 +27,9 @@ class A { void f() { new A.named(); } -''', [ - lint(39, 3), - ]); +''', + [lint(39, 3)], + ); } test_named_noNew() async { @@ -56,7 +57,8 @@ void f() { } test_unnamed_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(); } @@ -64,9 +66,9 @@ class A { void f() { new A(); } -''', [ - lint(39, 3), - ]); +''', + [lint(39, 3)], + ); } test_unnamed_newName_const() async { @@ -82,7 +84,8 @@ void f() { } test_unnamed_newName_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(); } @@ -90,9 +93,9 @@ class A { void f() { new A.new(); } -''', [ - lint(39, 3), - ]); +''', + [lint(39, 3)], + ); } test_unnamed_noNew() async { diff --git a/pkg/linter/test/rules/unnecessary_null_aware_assignments_test.dart b/pkg/linter/test/rules/unnecessary_null_aware_assignments_test.dart index b256209c99a4..1b5723e12cfa 100644 --- a/pkg/linter/test/rules/unnecessary_null_aware_assignments_test.dart +++ b/pkg/linter/test/rules/unnecessary_null_aware_assignments_test.dart @@ -29,14 +29,15 @@ void f() { } test_localVariable_nullAssignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x; x ??= null; } -''', [ - lint(28, 10), - ]); +''', + [lint(28, 10)], + ); } test_localVariable_otherAssignment() async { diff --git a/pkg/linter/test/rules/unnecessary_null_aware_operator_on_extension_on_nullable_test.dart b/pkg/linter/test/rules/unnecessary_null_aware_operator_on_extension_on_nullable_test.dart index 31650f909a78..21d7cc2bfd6b 100644 --- a/pkg/linter/test/rules/unnecessary_null_aware_operator_on_extension_on_nullable_test.dart +++ b/pkg/linter/test/rules/unnecessary_null_aware_operator_on_extension_on_nullable_test.dart @@ -9,7 +9,8 @@ import '../rule_test_support.dart'; main() { defineReflectiveSuite(() { defineReflectiveTests( - UnnecessaryNullAwareOperatorOnExtensionOnNullableTest); + UnnecessaryNullAwareOperatorOnExtensionOnNullableTest, + ); }); } @@ -32,16 +33,17 @@ void f(int? i) { } test_extensionOverride_getter_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { int get foo => 1; } void f(int? i) { E(i)?.foo; } -''', [ - lint(67, 2), - ]); +''', + [lint(67, 2)], + ); } test_extensionOverride_indexAssignment() async { @@ -56,16 +58,17 @@ void f(int? i) { } test_extensionOverride_indexAssignment_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { void operator []=(int i, String v) {} } void f(int? i) { E(i)?[0] = ''; } -''', [ - lint(87, 1), - ]); +''', + [lint(87, 1)], + ); } test_extensionOverride_indexOperator() async { @@ -80,16 +83,17 @@ void f(int? i) { } test_extensionOverride_indexOperator_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { String operator [](int i) => ''; } void f(int? i) { E(i)?[0]; } -''', [ - lint(82, 1), - ]); +''', + [lint(82, 1)], + ); } test_extensionOverride_methodCall() async { @@ -104,16 +108,17 @@ void f(int? i) { } test_extensionOverride_methodCall_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { int m() => 1; } void f(int? i) { E(i)?.m(); } -''', [ - lint(63, 2), - ]); +''', + [lint(63, 2)], + ); } test_extensionOverride_setter() async { @@ -128,16 +133,17 @@ void f(int? i) { } test_extensionOverride_setter_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { void set foo(int v) {} } void f(int? i) { E(i)?.foo = 1; } -''', [ - lint(72, 2), - ]); +''', + [lint(72, 2)], + ); } test_getter() async { @@ -152,16 +158,17 @@ void f(int? i) { } test_getter_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { int get foo => 1; } void f(int? i) { i?.foo; } -''', [ - lint(64, 2), - ]); +''', + [lint(64, 2)], + ); } test_indexAssignment() async { @@ -176,16 +183,17 @@ void f(int? i) { } test_indexAssignment_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { void operator []=(int i, String v) {} } void f(int? i) { i?[0] = ''; } -''', [ - lint(84, 1), - ]); +''', + [lint(84, 1)], + ); } test_indexOperator() async { @@ -200,16 +208,17 @@ void f(int? i) { } test_indexOperator_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { String operator [](int i) => ''; } void f(int? i) { i?[0]; } -''', [ - lint(79, 1), - ]); +''', + [lint(79, 1)], + ); } test_methodCall() async { @@ -224,16 +233,17 @@ void f(int? i) { } test_methodCall_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { int m() => 1; } void f(int? i) { i?.m(); } -''', [ - lint(60, 2), - ]); +''', + [lint(60, 2)], + ); } test_setter() async { @@ -248,15 +258,16 @@ void f(int? i) { } test_setter_nullAware() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on int? { void set foo(int v) {} } void f(int? i) { i?.foo = 1; } -''', [ - lint(69, 2), - ]); +''', + [lint(69, 2)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_null_checks_test.dart b/pkg/linter/test/rules/unnecessary_null_checks_test.dart index a5a733784424..c0e12deda5c8 100644 --- a/pkg/linter/test/rules/unnecessary_null_checks_test.dart +++ b/pkg/linter/test/rules/unnecessary_null_checks_test.dart @@ -18,24 +18,28 @@ class UnnecessaryNullChecksTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_null_checks; test_assignment_await_nullableTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f(int? p, int? i, Future future) async { i = await future!; } -''', [ - error(StaticWarningCode.UNNECESSARY_NON_NULL_ASSERTION, 78, 1), - lint(78, 1), - ]); +''', + [ + error(StaticWarningCode.UNNECESSARY_NON_NULL_ASSERTION, 78, 1), + lint(78, 1), + ], + ); } test_assignment_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? v, int? i) { v = i!; } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_assignment_nullable_self() async { @@ -48,31 +52,34 @@ void f(int? v) { } test_assignment_nullableTarget() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? j = i!; int? i; -''', [ - lint(10, 1), - ]); +''', + [lint(10, 1)], + ); } test_assignment_nullableTarget_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? j2 = (i!); int? i; -''', [ - lint(12, 1), - ]); +''', + [lint(12, 1)], + ); } test_binaryOperator_argument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { operator +(int? p) => A() + p!; } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_completerComplete() async { @@ -92,40 +99,44 @@ void f(int? v, int? p) { } test_constructorCall_optionalPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A([int? p]); } void f(int? i) => A(i!); -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_functionCall_namedArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({int? p, int? i}) => f(p: i!); -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_functionCall_positionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? i; void f(int? p) => f(i!); -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_functionCall_positionalArgument_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? i; void f(int? p) => f((i!)); -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_futureValue() async { @@ -135,13 +146,14 @@ void f(int? i) => Future.value(i!); } test_listPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? a, int? b) { [b!, ] = [a, ]; } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_nullableAssignment_nullable() async { @@ -153,25 +165,27 @@ void f(int? v, int? p) { } test_recordPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int? a, int? b) { (b!, ) = (a, ); } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_return_function_dynamic() async { // TODO(srawlins): Why does a dynamic-returning function result in a // diagnostic, but a dynamic-returning method does not? - await assertDiagnostics(r''' + await assertDiagnostics( + r''' dynamic f(int? p) { return p!; } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_return_list_nonNullable() async { @@ -181,11 +195,12 @@ List f7ok(int? p) => [p!]; } test_return_list_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f7(int? p) => [p!]; -''', [ - lint(27, 1), - ]); +''', + [lint(27, 1)], + ); } test_return_mapKey_nonNullable() async { @@ -195,11 +210,12 @@ Map f(int? p) => {p!: ''}; } test_return_mapKey_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(int? p) => {p!: ''}; -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_return_mapValue_forElement_nonNullable() async { @@ -209,11 +225,12 @@ Map f(int? p) => {for (var a in []) '': p!}; } test_return_mapValue_forElement_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(int? p) => {for (var a in []) '': p!}; -''', [ - lint(60, 1), - ]); +''', + [lint(60, 1)], + ); } test_return_mapValue_ifElement_nonNullable() async { @@ -223,19 +240,21 @@ Map f(int? p) => {if (1 != 0) '': p!}; // OK } test_return_mapValue_ifElement_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(int? p) => {if (1 != 0) '': p!}; -''', [ - lint(49, 1), - ]); +''', + [lint(49, 1)], + ); } test_return_mapValue_ifElementNested_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(int? p) => {if (1 != 0) if (1 != 0) '': p!}; -''', [ - lint(61, 1), - ]); +''', + [lint(61, 1)], + ); } test_return_mapValue_nonNullable() async { @@ -245,11 +264,12 @@ Map f(int? p) => {'': p!}; } test_return_mapValue_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Map f(int? p) => {'': p!}; -''', [ - lint(37, 1), - ]); +''', + [lint(37, 1)], + ); } test_return_method_dynamic() async { @@ -263,11 +283,12 @@ class A { } test_return_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? f(int? i) { return i!; } -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_return_set_nonNullable() async { @@ -277,11 +298,12 @@ Set f(int? p) => {p!}; } test_return_set_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Set f(int? p) => {p!}; -''', [ - lint(25, 1), - ]); +''', + [lint(25, 1)], + ); } test_returnAsync_dynamic() async { @@ -310,47 +332,54 @@ F f(int? p) async => p!; } test_returnAsync_futureOfNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f(int? p) async => p!; -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_returnAsync_futureOfNullable_await() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Future f(int? p) async => await p!; -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } test_returnAsync_futureOfNullable_typedef() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' typedef F = Future; F f(int? p) async => p!; -''', [ - lint(48, 1), - ]); +''', + [lint(48, 1)], + ); } test_returnExpressionBody_nullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int? f(int? i) => i!; -''', [ - lint(19, 1), - ]); +''', + [lint(19, 1)], + ); } test_undefinedFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f6(int? p) { return B() + p!; // OK } -''', [ - // No lint - error(CompileTimeErrorCode.UNDEFINED_FUNCTION, 22, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.UNDEFINED_FUNCTION, 22, 1), + ], + ); } test_yieldAsyncStar_streamOfNonNullable() async { @@ -360,11 +389,12 @@ Stream f13ok(int? p) async* {yield p!;} } test_yieldAsyncStar_streamOfNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Stream f(int? p) async* {yield p!;} -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_yieldSyncStar_iterableOfNonNullable() async { @@ -374,10 +404,11 @@ Iterable f(int? p) sync* {yield p!;} } test_yieldSyncStar_iterableOfNullable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Iterable f(int? p) sync* {yield p!;} -''', [ - lint(39, 1), - ]); +''', + [lint(39, 1)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_null_in_if_null_operators_test.dart b/pkg/linter/test/rules/unnecessary_null_in_if_null_operators_test.dart index 4b808af0a0cd..6b82929913a8 100644 --- a/pkg/linter/test/rules/unnecessary_null_in_if_null_operators_test.dart +++ b/pkg/linter/test/rules/unnecessary_null_in_if_null_operators_test.dart @@ -18,106 +18,122 @@ class UnnecessaryNullInIfNullOperatorsTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_null_in_if_null_operators; test_localVariableDeclaration_noNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 1 ?? 1; } -''', [ - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 26, 1), - ]); +''', + [error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 26, 1)], + ); } test_localVariableDeclaration_nullOnLeft() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = null ?? 1; } -''', [ - lint(21, 4), - ]); +''', + [lint(21, 4)], + ); } test_localVariableDeclaration_nullOnRight() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = 1 ?? null; } -''', [ - lint(26, 4), - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 26, 4), - ]); +''', + [lint(26, 4), error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 26, 4)], + ); } test_methodBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m() { var x = 1 ?? null; var y = null ?? 1; } } -''', [ - lint(35, 4), - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 35, 4), - lint(53, 4), - ]); +''', + [ + lint(35, 4), + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 35, 4), + lint(53, 4), + ], + ); } test_methodBody_noNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { m() { var x = 1 ?? 1; } } -''', [ - // No lint. - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 35, 1), - ]); +''', + [ + // No lint. + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 35, 1), + ], + ); } test_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 ?? null; var y = null ?? 1; -''', [ - lint(13, 4), - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 4), - lint(27, 4), - ]); +''', + [ + lint(13, 4), + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 4), + lint(27, 4), + ], + ); } test_topLevel_noNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 ?? 1; -''', [ - // No lint. - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 1), - ]); +''', + [ + // No lint. + error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 1), + ], + ); } test_topLevelVariableDeclaration_noNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 ?? 1; -''', [ - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 1), - ]); +''', + [error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 1)], + ); } test_topLevelVariableDeclaration_nullOnLeft() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = null ?? 1; -''', [ - lint(8, 4), - ]); +''', + [lint(8, 4)], + ); } test_topLevelVariableDeclaration_nullOnRight() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = 1 ?? null; -''', [ - lint(13, 4), - error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 4), - ]); +''', + [lint(13, 4), error(StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION, 13, 4)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart b/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart index f1958a6c6d2a..bae04769e2c3 100644 --- a/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart +++ b/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart @@ -19,14 +19,15 @@ class UnnecessaryNullableForFinalVariableDeclarationsTest extends LintRuleTest { LintNames.unnecessary_nullable_for_final_variable_declarations; test_list() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final [int a, num? c] = [0, 1]; print('$a$c'); } -''', [ - lint(27, 1), - ]); +''', + [lint(27, 1)], + ); } test_list_dynamic_ok() async { @@ -89,66 +90,65 @@ f() { } test_nullableType_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { // ignore: unused_field final int? _i = 1; final int? i = 1; static final int? j = 1; } -''', [ - lint(49, 2), - lint(97, 1), - ]); +''', + [lint(49, 2), lint(97, 1)], + ); } test_nullableType_field_extension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension E on Object { // ignore: unused_field static final int? _e = 1; static final int? e = 1; } -''', [ - lint(70, 2), - lint(98, 1), - ]); +''', + [lint(70, 2), lint(98, 1)], + ); } test_nullableType_topLevel() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' // ignore: unused_element final int? _i = 1; final int? i = 1; const int? ic = 1; -''', [ - lint(37, 2), - lint(56, 1), - lint(74, 2), - ]); +''', + [lint(37, 2), lint(56, 1), lint(74, 2)], + ); } test_nullableType_variable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final int? _i = 1; final int? i = 1; } -''', [ - lint(19, 2), - lint(40, 1), - ]); +''', + [lint(19, 2), lint(40, 1)], + ); } test_record() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { final (List? a, num? c) = ([], 1); print('$a$c'); } -''', [ - lint(26, 1), - lint(34, 1), - ]); +''', + [lint(26, 1), lint(34, 1)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_overrides_test.dart b/pkg/linter/test/rules/unnecessary_overrides_test.dart index f2fc6de81d73..a779589914b4 100644 --- a/pkg/linter/test/rules/unnecessary_overrides_test.dart +++ b/pkg/linter/test/rules/unnecessary_overrides_test.dart @@ -21,7 +21,8 @@ class UnnecessaryOverridesTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_overrides; test_binaryOperator_expressionFunctionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int operator +(int other) => 0; } @@ -29,9 +30,9 @@ class C extends A { @override int operator +(int other) => super + other; } -''', [ - lint(93, 1), - ]); +''', + [lint(93, 1)], + ); } test_class_augmentation_method_withoutOverride_noSuper() async { @@ -54,27 +55,29 @@ augment class A { } test_enum_field() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; @override Type get runtimeType => super.runtimeType; } -''', [ - lint(41, 11), - ]); +''', + [lint(41, 11)], + ); } test_enum_method() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum A { a,b,c; @override String toString() => super.toString(); } -''', [ - lint(39, 8), - ]); +''', + [lint(39, 8)], + ); } test_getter_expressionFunctionBody_otherTarget() async { @@ -91,7 +94,8 @@ class C extends A { } test_getter_expressionFunctionBody_superCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int get x => 0; } @@ -99,9 +103,9 @@ class C extends A { @override int get x => super.x; } -''', [ - lint(72, 1), - ]); +''', + [lint(72, 1)], + ); } test_getter_returnTypeChanged() async { @@ -117,7 +121,8 @@ class C extends A { } test_method_blockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m() {} } @@ -127,9 +132,9 @@ class C extends A { super.m(); } } -''', [ - lint(65, 1), - ]); +''', + [lint(65, 1)], + ); } test_method_blockBody_noSuper() async { @@ -175,7 +180,8 @@ class E extends C { } test_method_expressionFunctionBody_everythingTheSame() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int m(int a, int b) => 0; } @@ -183,9 +189,9 @@ class C extends A { @override int m(int a, int b) => super.m(a, b); } -''', [ - lint(78, 1), - ]); +''', + [lint(78, 1)], + ); } test_method_expressionFunctionBody_mismatchedAguments() async { @@ -201,7 +207,8 @@ class C extends A { } test_method_expressionFunctionBody_namedParameters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int m({int a = 0, int b = 0}) => 0; } @@ -209,9 +216,9 @@ class C extends A { @override int m({int a = 0, int b = 0}) => super.m(a: a, b: b); } -''', [ - lint(88, 1), - ]); +''', + [lint(88, 1)], + ); } test_method_expressionFunctionBody_namedParameters_mismatchedArguments() async { @@ -227,7 +234,8 @@ class C extends A { } test_method_expressionFunctionBody_namedParameters_outOfOrder() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int m({int a = 0, int b = 0}) => 0; } @@ -235,9 +243,9 @@ class C extends A { @override int m({int a = 0, int b = 0}) => super.m(b: b, a: a); } -''', [ - lint(88, 1), - ]); +''', + [lint(88, 1)], + ); } test_method_hasOtherAnnotations() async { @@ -456,7 +464,8 @@ class C extends A { } test_setter_blockBody_superCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { set x(other) {} } @@ -466,9 +475,9 @@ class C extends A { super.x = other; } } -''', [ - lint(68, 1), - ]); +''', + [lint(68, 1)], + ); } test_setter_expressionFunctionBody_otherTarget() async { @@ -509,7 +518,8 @@ class C extends A { } test_unaryOperator_expressionFunctionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A operator ~() => A(); } @@ -517,8 +527,8 @@ class C extends A { @override A operator ~() => ~super; } -''', [ - lint(82, 1), - ]); +''', + [lint(82, 1)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_parenthesis_test.dart b/pkg/linter/test/rules/unnecessary_parenthesis_test.dart index 02338eeb5189..95fa4c45b1ae 100644 --- a/pkg/linter/test/rules/unnecessary_parenthesis_test.dart +++ b/pkg/linter/test/rules/unnecessary_parenthesis_test.dart @@ -99,14 +99,15 @@ void f() { } test_binaryExpressionInside_constructorFieldInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { bool f; C() : f = (true && false); } -''', [ - lint(32, 15), - ]); +''', + [lint(32, 15)], + ); } test_binaryExpressionInside_isExpression() async { @@ -118,23 +119,25 @@ void f(num a, num b) { } test_binaryExpressionInside_namedArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f({required int p}) { f(p: (1 + 3)); } -''', [ - lint(34, 7), - ]); +''', + [lint(34, 7)], + ); } test_binaryExpressionInside_positionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { f((1 + 3)); } -''', [ - lint(20, 7), - ]); +''', + [lint(20, 7)], + ); } test_binaryExpressionInside_prefixExpression() async { @@ -144,27 +147,30 @@ var x = ~(1 | 2); } test_binaryExpressionInside_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Record f() { return (1, (2 + 2)); } -''', [ - lint(26, 7), - ]); +''', + [lint(26, 7)], + ); } test_binaryExpressionInside_returnExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f() { return (1 > 1); } -''', [ - lint(20, 7), - ]); +''', + [lint(20, 7)], + ); } test_binaryExpressionInside_switchStatementVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { switch ((5 == 6)) { case true: @@ -173,9 +179,9 @@ void f() { return; } } -''', [ - lint(21, 8), - ]); +''', + [lint(21, 8)], + ); } test_binaryExpressionInside_variableDeclarationInitializer() async { @@ -187,13 +193,14 @@ void f() { } test_binaryExpressionInside_whileCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { while ((1 == 1)) {} } -''', [ - lint(20, 8), - ]); +''', + [lint(20, 8)], + ); } test_binaryOperationInside_binaryOperation() async { @@ -247,13 +254,14 @@ abstract class A { } test_conditionalExpressionInside_argument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int p) { print((1 == 1 ? 2 : 3)); } -''', [ - lint(24, 16), - ]); +''', + [lint(24, 16)], + ); } test_conditionalExpressionInside_argumentList() async { @@ -271,13 +279,14 @@ int f() => (1 == 1 ? 2 : 3); } test_conditionalExpressionInside_ifCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if ((1 == 1 ? true : false)) {} } -''', [ - lint(17, 23), - ]); +''', + [lint(17, 23)], + ); } test_conditionalExpressionInside_listLiteral() async { @@ -289,13 +298,14 @@ void f() { } test_conditionalExpressionInside_stringInterpolation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { '${(1 == 1 ? 2 : 3)}'; } -''', [ - lint(16, 16), - ]); +''', + [lint(16, 16)], + ); } test_conditionalExpressionInside_targetOfMethodInvocation() async { @@ -360,14 +370,15 @@ class C { } test_constructorTearoffInside() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} void f() { (C.new)(); } -''', [ - lint(24, 7), - ]); +''', + [lint(24, 7)], + ); } test_constructorTearoffInside_instantiatedThenCalled() async { @@ -379,33 +390,36 @@ void f() { } test_constructorTearoffInstantiatedInside() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (List.filled)(3, 0); } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_constructorTearoffInstantiatedInside_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = (List.filled); -''', [ - lint(8, 18), - ]); +''', + [lint(8, 18)], + ); } test_constructorTearoffReferenceInside() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} void f() { var cNew = C.new; (cNew)(); } -''', [ - lint(44, 6), - ]); +''', + [lint(44, 6)], + ); } test_equalityInside_constructorFieldInitializer() async { @@ -418,11 +432,12 @@ class C { } test_equalityInside_expressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f() => (1 == 1); -''', [ - lint(12, 8), - ]); +''', + [lint(12, 8)], + ); } test_expressionInside_targetOfMethodInvocation() async { @@ -457,11 +472,12 @@ class C { } test_functionExpressionInside_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = (() => null); -''', [ - lint(8, 12), - ]); +''', + [lint(8, 12)], + ); } test_functionExpressionInside_binaryExpression() async { @@ -518,21 +534,23 @@ void f() { } test_intLiteralInside_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = (1, (2)); } -''', [ - lint(25, 3), - ]); +''', + [lint(25, 3)], + ); } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' final items = [1, (DateTime.now())]; -''', [ - lint(18, 16), - ]); +''', + [lint(18, 16)], + ); } test_notEqualInside_returnExpression() async { @@ -617,23 +635,25 @@ void f(bool? b) { @FailingTest(issue: 'https://github.com/dart-lang/linter/issues/4062') test_parenthesizedPattern_nonPatternOutside() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(num n) { if (1 case (int())) {} } -''', [ - lint(20, 7), - ]); +''', + [lint(20, 7)], + ); } test_positionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print((1 + 2)); } -''', [ - lint(19, 7), - ]); +''', + [lint(19, 7)], + ); } test_postfixExpressionInside_targetOfMethodInvocation() async { @@ -664,33 +684,36 @@ abstract class A { } test_prefixedIdentifierInside_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = ((''.isEmpty), 2); } -''', [ - lint(22, 12), - ]); +''', + [lint(22, 12)], + ); } test_prefixedIdentifierInside_targetOfMethodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (0.isEven).toString(); } -''', [ - lint(13, 10), - ]); +''', + [lint(13, 10)], + ); } test_prefixedIdentifierInside_targetOfPropertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (0.sign).isEven; } -''', [ - lint(13, 8), - ]); +''', + [lint(13, 8)], + ); } test_prefixExpressionInside_targetOfMethodInvocation() async { @@ -702,57 +725,62 @@ void f(bool b) { } test_propertyAccessInside_prefixExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { !([].isEmpty); } -''', [ - lint(14, 12), - ]); +''', + [lint(14, 12)], + ); } test_propertyAccessInside_recordLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Record f() { return (1.isEven, (2.isEven)); } -''', [ - lint(33, 10), - ]); +''', + [lint(33, 10)], + ); } test_recordInside_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (int,) r = ((3,)); } -''', [ - lint(24, 6), - ]); +''', + [lint(24, 6)], + ); } test_recordInside_namedParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(i: ((3,))); } void g({required (int,) i}) {} -''', [ - lint(18, 6), - ]); +''', + [lint(18, 6)], + ); } test_recordInside_param() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(((3,))); } void g((int,) i) {} -''', [ - lint(15, 6), - ]); +''', + [lint(15, 6)], + ); } test_setLiteralInside_binaryExpression() async { @@ -776,13 +804,14 @@ void f() { } test_setLiteralInside_propertyAccess_functionArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { print(({1, 2, 3}).length); } -''', [ - lint(19, 11), - ]); +''', + [lint(19, 11)], + ); } test_setLiteralInside_targetOfGenericTearoff() async { @@ -794,119 +823,136 @@ void f() { } test_simpleIdentifierInside_assignmentRightSide() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { a = (a); } -''', [ - lint(22, 3), - ]); +''', + [lint(22, 3)], + ); } test_simpleIdentifierInside_conditionalExpressionCondition() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(bool a) { (a) ? 2 : 3; } -''', [ - lint(19, 3), - ]); +''', + [lint(19, 3)], + ); } test_simpleIdentifierInside_conditionalExpressionElseExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { 1 == 2 ? true : (a); // LINT } -''', [ - lint(34, 3), - ]); +''', + [lint(34, 3)], + ); } test_simpleIdentifierInside_conditionalExpressionThenExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { 1 == 2 ? (a) : false; // LINT } -''', [ - lint(27, 3), - ]); +''', + [lint(27, 3)], + ); } test_simpleIdentifierInside_expressionStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { (a); } -''', [ - lint(18, 3), - ]); +''', + [lint(18, 3)], + ); } test_simpleIdentifierInside_functionArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int a) { print((a)); } -''', [ - lint(24, 3), - ]); +''', + [lint(24, 3)], + ); } test_simpleIdentifierInside_methodInvocation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Function fn) { (fn)(3); } -''', [ - lint(24, 4), - ]); +''', + [lint(24, 4)], + ); } test_singleElementRecordWithNoTrailingCommaInside_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { (int,) r = (3); } -''', [ - error( +''', + [ + error( CompileTimeErrorCode.RECORD_LITERAL_ONE_POSITIONAL_NO_TRAILING_COMMA, 24, - 3), - ]); + 3, + ), + ], + ); } test_singleElementRecordWithNoTrailingCommaInside_namedArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(i: (3)); } void g({required (int,) i}) {} -''', [ - error( - CompileTimeErrorCode.RECORD_LITERAL_ONE_POSITIONAL_NO_TRAILING_COMMA, - 18, - 3, - ), - ]); +''', + [ + error( + CompileTimeErrorCode.RECORD_LITERAL_ONE_POSITIONAL_NO_TRAILING_COMMA, + 18, + 3, + ), + ], + ); } /// https://github.com/dart-lang/linter/issues/4876 test_singleElementRecordWithNoTrailingCommaInside_positionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g((3)); } void g((int,) i) {} -''', [ - error( - CompileTimeErrorCode.RECORD_LITERAL_ONE_POSITIONAL_NO_TRAILING_COMMA, - 15, - 3, - ), - ]); +''', + [ + error( + CompileTimeErrorCode.RECORD_LITERAL_ONE_POSITIONAL_NO_TRAILING_COMMA, + 15, + 3, + ), + ], + ); } test_spread() async { @@ -958,33 +1004,36 @@ void f() { } test_stringLiteralInside() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { '' + (''); } -''', [ - lint(18, 4), - ]); +''', + [lint(18, 4)], + ); } test_stringLiteralInside_variableDeclarationInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var x = (''); } -''', [ - lint(21, 4), - ]); +''', + [lint(21, 4)], + ); } test_switchExpressionInside_argument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object? x) { print((switch (x) { _ => 0 })); } -''', [ - lint(28, 23), - ]); +''', + [lint(28, 23)], + ); } test_switchExpressionInside_expressionStatement() async { @@ -1005,13 +1054,14 @@ void f(Object v) { } test_switchExpressionInside_variableDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Object? x) { final v = (switch (x) { _ => 0 }); } -''', [ - lint(32, 23), - ]); +''', + [lint(32, 23)], + ); } test_targetOfGetterInNullableExtension() async { diff --git a/pkg/linter/test/rules/unnecessary_raw_strings_test.dart b/pkg/linter/test/rules/unnecessary_raw_strings_test.dart index db619d72389a..576206e079b8 100644 --- a/pkg/linter/test/rules/unnecessary_raw_strings_test.dart +++ b/pkg/linter/test/rules/unnecessary_raw_strings_test.dart @@ -18,11 +18,12 @@ class UnnecessaryRawStringsTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_raw_strings; test_doubleQuotes_raw() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = r"a b c d"; -''', [ - lint(8, 10), - ]); +''', + [lint(8, 10)], + ); } test_doubleQuotes_raw_containsBackslash() async { @@ -44,11 +45,12 @@ var s = 'a b c d'; } test_singleQuote_raw() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = r'a b c d'; -''', [ - lint(8, 10), - ]); +''', + [lint(8, 10)], + ); } test_singleQuote_raw_containsBackslash() async { @@ -64,11 +66,12 @@ var s = r'a b c$d'; } test_tripleDoubleQuotes_raw() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = r"""a b c d"""; -''', [ - lint(8, 14), - ]); +''', + [lint(8, 14)], + ); } test_tripleDoubleQuotes_raw_containsBackslash() async { @@ -84,11 +87,12 @@ var s = r"""a b c$d"""; } test_tripleSingleQuote_raw() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var s = r'''a b c d'''; -""", [ - lint(8, 14), - ]); +""", + [lint(8, 14)], + ); } test_tripleSingleQuote_raw_containsBackslash() async { diff --git a/pkg/linter/test/rules/unnecessary_statements_test.dart b/pkg/linter/test/rules/unnecessary_statements_test.dart index 4015670e6607..bebab7e073f0 100644 --- a/pkg/linter/test/rules/unnecessary_statements_test.dart +++ b/pkg/linter/test/rules/unnecessary_statements_test.dart @@ -27,33 +27,36 @@ void f(Object o) { } test_binaryExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { 1 + 1; } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_binaryExpression_andAnd() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { true && 1 == 2; } -''', [ - lint(21, 6), - ]); +''', + [lint(21, 6)], + ); } test_binaryExpression_or() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { false || 1 == 2; } -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_binaryExpression_or_rightSideHasEffect() async { @@ -65,23 +68,25 @@ void f() { } test_construcorTearoff_new() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { ArgumentError.new; } -''', [ - lint(13, 17), - ]); +''', + [lint(13, 17)], + ); } test_constructorTearoff_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { DateTime.now; } -''', [ - lint(13, 12), - ]); +''', + [lint(13, 12)], + ); } test_doStatement() async { @@ -101,13 +106,14 @@ void f() { } test_forLoopUpdaters_subsequent() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (; 1 == 2; print(7), []) {} } -''', [ - lint(38, 2), - ]); +''', + [lint(38, 2)], + ); } test_forStatement() async { @@ -119,24 +125,26 @@ void f() { } test_functionTearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g; } void g() {} -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_ifNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { null ?? 7; } -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_ifNull_rightSideHasEffect() async { @@ -158,59 +166,64 @@ void f() { } test_inDoWhile() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { do { []; } while (1 == 2); } -''', [ - lint(22, 2), - ]); +''', + [lint(22, 2)], + ); } test_inForLoop() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var i in []) { ~1; } } -''', [ - lint(37, 2), - ]); +''', + [lint(37, 2)], + ); } test_inForLoopInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (7; 1 == 2;) {} } -''', [ - lint(18, 1), - ]); +''', + [lint(18, 1)], + ); } test_inForLoopUpdaters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (; 1 == 2; []) {} } -''', [ - lint(28, 2), - ]); +''', + [lint(28, 2)], + ); } test_inIfBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if (1 == 2) { []; } } -''', [ - lint(31, 2), - ]); +''', + [lint(31, 2)], + ); } test_instanceCreationExpression() async { @@ -222,7 +235,8 @@ void f() { } test_instanceField() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { C().g; } @@ -230,22 +244,23 @@ void f() { class C { int g = 1; } -''', [ - lint(13, 5), - ]); +''', + [lint(13, 5)], + ); } test_instanceField2() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(C c) { c.g; } class C { int g = 1; } -''', [ - lint(16, 3), - ]); +''', + [lint(16, 3)], + ); } test_instanceGetter() async { @@ -265,16 +280,17 @@ void f(List list) { } test_inSwitchStatement_case() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { switch (7) { case 6: []; } } -''', [ - lint(44, 2), - ]); +''', + [lint(44, 2)], + ); } test_inSwitchStatement_case_break() async { @@ -289,57 +305,62 @@ void f() { } test_inSwitchStatement_default() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { switch (7) { default: []; } } -''', [ - lint(45, 2), - ]); +''', + [lint(45, 2)], + ); } test_intLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { 1; } -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_listLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { []; } -''', [ - lint(13, 2), - ]); +''', + [lint(13, 2)], + ); } test_localVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var g = 1; g; } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_mapLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { {}; } -''', [ - lint(13, 20), - ]); +''', + [lint(13, 20)], + ); } test_methodInvocation() async { @@ -360,64 +381,70 @@ void f(List list) { } test_methodTearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { List.empty().where; } -''', [ - lint(13, 18), - ]); +''', + [lint(13, 18)], + ); } test_methodTearoff_cascaded() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { List.empty()..where; } -''', [ - lint(25, 7), - ]); +''', + [lint(25, 7)], + ); } test_methodTearoff_cascaded_followOn() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { List.empty() ..forEach((_) {}) ..where; } -''', [ - lint(51, 7), - ]); +''', + [lint(51, 7)], + ); } test_methodTearoff_cascaded_returned_InLocalFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { // ignore: unused_element g() => List.empty()..where; } -''', [ - lint(60, 7), - ]); +''', + [lint(60, 7)], + ); } test_methodTearoff_cascaded_returned_InTopLevelFunction() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f() => List.empty()..where; -''', [ - lint(29, 7), - ]); +''', + [lint(29, 7)], + ); } test_methodTearoff_returned_inFunctionLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { () => List.empty().where; } -''', [ - lint(13, 24), - ]); +''', + [lint(13, 24)], + ); } test_methodTearoff_returned_InLocalFunction() async { @@ -465,23 +492,25 @@ int f() { } test_returnStatement_cascadedTearoff() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' List f() { return List.empty()..where; } -''', [ - lint(37, 7), - ]); +''', + [lint(37, 7)], + ); } test_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { "blah"; } -''', [ - lint(13, 6), - ]); +''', + [lint(13, 6)], + ); } test_switchStatement() async { @@ -510,24 +539,26 @@ int get g => 1; } test_topLevelVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g; } int g = 1; -''', [ - lint(13, 1), - ]); +''', + [lint(13, 1)], + ); } test_unaryOperation() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { ~1; } -''', [ - lint(13, 2), - ]); +''', + [lint(13, 2)], + ); } test_unaryOperation_postfix() async { diff --git a/pkg/linter/test/rules/unnecessary_string_escapes_test.dart b/pkg/linter/test/rules/unnecessary_string_escapes_test.dart index f91fa60ee097..3a58c1a274b6 100644 --- a/pkg/linter/test/rules/unnecessary_string_escapes_test.dart +++ b/pkg/linter/test/rules/unnecessary_string_escapes_test.dart @@ -24,11 +24,12 @@ var x = '\\'; } test_escapedColon() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = '\:'; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_escapedDoubleQuotes_inDoubleQuotes() async { @@ -38,11 +39,12 @@ var x = "\""; } test_escapedDoubleQuotes_inSingleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = '\"'; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_escapedDoubleQuotes_inSingleQuotes_raw() async { @@ -58,11 +60,12 @@ var x = """text"\""text"""; } test_escapedDoubleQuotes_inThreeDoubleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = """\"text"""; -''', [ - lint(11, 1), - ]); +''', + [lint(11, 1)], + ); } test_escapedDoubleQuotes_inThreeDoubleQuotes_atEnd() async { @@ -72,19 +75,21 @@ var x = """text\""""; } test_escapedDoubleQuotes_inThreeSingleQuotes() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var x = '''\"'''; -""", [ - lint(11, 1), - ]); +""", + [lint(11, 1)], + ); } test_escapedLowerA() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = '\a'; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_escapedLowerDollar() async { @@ -112,11 +117,12 @@ var x = '\t'; } test_escapedSingleQuote_inDoubleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = "\'"; -''', [ - lint(9, 1), - ]); +''', + [lint(9, 1)], + ); } test_escapedSingleQuote_inDoubleQuotes_raw() async { @@ -138,19 +144,21 @@ var x = '''text'\''text'''; } test_escapedSingleQuote_inThreeDoubleQuotes() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = """\'"""; -''', [ - lint(11, 1), - ]); +''', + [lint(11, 1)], + ); } test_escapedSingleQuote_inThreeSingleQuotes() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var x = '''\'text'''; -""", [ - lint(11, 1), - ]); +""", + [lint(11, 1)], + ); } test_escapedSingleQuote_inThreeSingleQuotes_atEnd() async { @@ -198,13 +206,16 @@ var x = '''text\'\'\'text'''; test_unterminatedStringLiteral() async { // Note that putting `''` on the new line is important to get a token // with `'\` with no closing quote. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String unclosedQuote() => '\ ''; -''', [ - // Ensure linter does not crash. - error(ParserErrorCode.INVALID_UNICODE_ESCAPE_STARTED, 27, 1), - error(ScannerErrorCode.UNTERMINATED_STRING_LITERAL, 27, 1), - ]); +''', + [ + // Ensure linter does not crash. + error(ParserErrorCode.INVALID_UNICODE_ESCAPE_STARTED, 27, 1), + error(ScannerErrorCode.UNTERMINATED_STRING_LITERAL, 27, 1), + ], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_string_interpolations_test.dart b/pkg/linter/test/rules/unnecessary_string_interpolations_test.dart index 780b5814e6bc..7d550e540f8b 100644 --- a/pkg/linter/test/rules/unnecessary_string_interpolations_test.dart +++ b/pkg/linter/test/rules/unnecessary_string_interpolations_test.dart @@ -55,38 +55,42 @@ var b = '''x$a'''; } test_unnecessaryInterpolation_single() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = ''; var b = '$a'; -''', [ - lint(20, 4), - ]); +''', + [lint(20, 4)], + ); } test_unnecessaryInterpolation_substring() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = ''; var b = '${a.substring(1)}'; -''', [ - lint(20, 19), - ]); +''', + [lint(20, 19)], + ); } test_unnecessaryInterpolation_triple() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var a = ''; var b = '''$a'''; -""", [ - lint(20, 8), - ]); +""", + [lint(20, 8)], + ); } test_unnecessaryInterpolation_withBraces() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = ''; var b = '${a}'; -''', [ - lint(20, 6), - ]); +''', + [lint(20, 6)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_this_test.dart b/pkg/linter/test/rules/unnecessary_this_test.dart index 3abb6763c5b7..01f0c4a0d7f5 100644 --- a/pkg/linter/test/rules/unnecessary_this_test.dart +++ b/pkg/linter/test/rules/unnecessary_this_test.dart @@ -18,7 +18,8 @@ class UnnecessaryNullChecksTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_this; test_closureInMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m1(List list) { list.forEach((e) { @@ -27,26 +28,28 @@ class A { } void m2(int x) {} } -''', [ - lint(67, 4), - ]); +''', + [lint(67, 4)], + ); } test_constructorBody_assignment() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { num x = 0; A.named(num a) { this.x = a; } } -''', [ - lint(46, 4), - ]); +''', + [lint(46, 4)], + ); } test_constructorBody_methodCall() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A.named() { this.m(); @@ -54,9 +57,9 @@ class A { void m() {} } -''', [ - lint(28, 4), - ]); +''', + [lint(28, 4)], + ); } test_constructorBody_shadowedParameters() async { @@ -71,15 +74,16 @@ class A { } test_constructorInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { num x = 0; A.c1(num x) : this.x = x; } -''', [ - lint(45, 4), - ]); +''', + [lint(45, 4)], + ); } test_extension_getter() async { @@ -99,23 +103,25 @@ extension E on int? { } test_extensionType_inConstructorInitializer() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(int i) { E.e(int i) : this.i = i.hashCode; } -''', [ - lint(41, 4), - ]); +''', + [lint(41, 4)], + ); } test_extensionType_inMethod() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' extension type E(Object o) { String m()=> this.toString(); } -''', [ - lint(44, 4), - ]); +''', + [lint(44, 4)], + ); } test_initializingFormalParameter() async { @@ -143,7 +149,8 @@ class A { } test_localFunctionPresent_outOfScope() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void m1() { if (true) { @@ -154,9 +161,9 @@ class A { } void m2() {} } -''', [ - lint(101, 4), - ]); +''', + [lint(101, 4)], + ); } test_shadowInMethodBody() async { @@ -242,7 +249,8 @@ class C { } test_subclass_noShadowing() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int x = 0; } @@ -251,9 +259,9 @@ class D extends C { this.x = a; } } -''', [ - lint(67, 4), - ]); +''', + [lint(67, 4)], + ); } test_subclass_shadowedTopLevelVariable() async { diff --git a/pkg/linter/test/rules/unnecessary_to_list_in_spreads_test.dart b/pkg/linter/test/rules/unnecessary_to_list_in_spreads_test.dart index 11776f17fdb8..25f58bda4233 100644 --- a/pkg/linter/test/rules/unnecessary_to_list_in_spreads_test.dart +++ b/pkg/linter/test/rules/unnecessary_to_list_in_spreads_test.dart @@ -18,35 +18,38 @@ class UnnecessaryToListInSpreadsTest extends LintRuleTest { String get lintRule => LintNames.unnecessary_to_list_in_spreads; test_iterableToList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [ ...[1, 2].whereType().toList(), ]; -''', [ - lint(39, 6), - ]); +''', + [lint(39, 6)], + ); } test_listToList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [ ...[1, 2].toList(), ]; -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_listToList_nullAwareSpread() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List? p) { var x = [ ...?p?.toList(), ]; } -''', [ - lint(46, 6), - ]); +''', + [lint(46, 6)], + ); } test_noToList() async { @@ -58,24 +61,26 @@ var x = [ } test_setToList() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var x = [ ...{1, 2}.toList(), ]; -''', [ - lint(22, 6), - ]); +''', + [lint(22, 6)], + ); } test_setToList_nullAwareSpread() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(Set? p) { var x = [ ...?p?.toList(), ]; } -''', [ - lint(45, 6), - ]); +''', + [lint(45, 6)], + ); } } diff --git a/pkg/linter/test/rules/unnecessary_underscores_test.dart b/pkg/linter/test/rules/unnecessary_underscores_test.dart index a8910d85154d..2ea86d35e7e6 100644 --- a/pkg/linter/test/rules/unnecessary_underscores_test.dart +++ b/pkg/linter/test/rules/unnecessary_underscores_test.dart @@ -18,35 +18,42 @@ class UnnecessaryUnderscoresTest extends LintRuleTest { String get lintRule => 'unnecessary_underscores'; test_enum_field_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { __, } -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 11, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 11, 2), + ], + ); } test_field_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { int __ = 0; } -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 16, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 16, 2), + ], + ); } test_forPart_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { for (var __ = 0; ; ) {} } -''', [ - lint(22, 2), - ]); +''', + [lint(22, 2)], + ); } test_forPart_used() async { @@ -58,11 +65,12 @@ void f() { } test_function_parameter_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int _, int __) {} -''', [ - lint(18, 2), - ]); +''', + [lint(18, 2)], + ); } test_function_parameter_unused_preWildcards() async { @@ -82,13 +90,14 @@ void f(int _, int __) { } test_local_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { var __ = 0; } -''', [ - lint(17, 2), - ]); +''', + [lint(17, 2)], + ); } test_local_used() async { @@ -101,66 +110,81 @@ void f() { } test_localFunction_parameter_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(int __) {} } -''', [ - error(WarningCode.UNUSED_ELEMENT, 13, 1), - lint(19, 2), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 13, 1), lint(19, 2)], + ); } test_localFunction_parameter_used() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { g(int __) { print(__); } } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 13, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 13, 1), + ], + ); } test_localFunction_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' f() { __() {} } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 8, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 8, 2), + ], + ); } test_method_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { __() {} } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 12, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 12, 2), + ], + ); } test_topLevelFunction_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' __() {} -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 0, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 0, 2), + ], + ); } test_topLevelVariable_unused() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' int __ = 0; -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 4, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 4, 2), + ], + ); } } diff --git a/pkg/linter/test/rules/unreachable_from_main_test.dart b/pkg/linter/test/rules/unreachable_from_main_test.dart index 554698f04acc..03bfde754cdd 100644 --- a/pkg/linter/test/rules/unreachable_from_main_test.dart +++ b/pkg/linter/test/rules/unreachable_from_main_test.dart @@ -37,7 +37,8 @@ class C { } test_class_instanceField_reachable_overrides_local() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { B(); } @@ -49,9 +50,9 @@ class A { class B extends A { int? f; } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_class_instanceField_reachable_read() async { @@ -79,7 +80,8 @@ class C { } test_class_instanceField_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C(); } @@ -87,9 +89,9 @@ void main() { class C { int? f; } -''', [ - lint(41, 1), - ]); +''', + [lint(41, 1)], + ); } test_class_instanceGetter_reachable_invoked() async { @@ -105,7 +107,8 @@ class C { } test_class_instanceGetter_reachable_overrides() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { B(); } @@ -117,13 +120,14 @@ class A { class B extends A { int get foo => 0; } -''', [ - lint(44, 3), - ]); +''', + [lint(44, 3)], + ); } test_class_instanceGetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C(); } @@ -131,9 +135,9 @@ void main() { class C { int get foo => 0; } -''', [ - lint(44, 3), - ]); +''', + [lint(44, 3)], + ); } test_class_instanceMethod_reachable_invoked() async { @@ -181,7 +185,8 @@ class B extends A { } test_class_instanceMethod_reachable_overrides_local() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { B(); } @@ -193,13 +198,14 @@ class A { class B extends A { void foo() {} } -''', [ - lint(41, 3), - ]); +''', + [lint(41, 3)], + ); } test_class_instanceMethod_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C(); } @@ -207,9 +213,9 @@ void main() { class C { void foo() {} } -''', [ - lint(41, 3), - ]); +''', + [lint(41, 3)], + ); } test_class_instanceSetter_reachable_invoked() async { @@ -225,7 +231,8 @@ class C { } test_class_instanceSetter_reachable_overrides() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { B(); } @@ -237,13 +244,14 @@ class A { class B extends A { set foo(int _) {} } -''', [ - lint(40, 3), - ]); +''', + [lint(40, 3)], + ); } test_class_instanceSetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C(); } @@ -251,9 +259,9 @@ void main() { class C { set foo(int _) {} } -''', [ - lint(40, 3), - ]); +''', + [lint(40, 3)], + ); } test_class_reachable_mainInPart() async { @@ -378,7 +386,8 @@ void f([Object? p = const C()]) {} } test_class_referencedInObjectPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C {} void main() { @@ -388,23 +397,25 @@ void main() { void f([Object? c]) { if (c case C()) {} } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_class_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} class C {} -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_class_unreachable_foundInAsExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} void main() { @@ -414,13 +425,14 @@ void main() { void f([Object? o]) { o as A; } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_class_unreachable_foundInAsPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} void main() { @@ -430,13 +442,14 @@ void main() { void f([(Object, )? l]) { var (_ as A, ) = l!; } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_class_unreachable_foundInIsExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A {} void main() { @@ -446,26 +459,29 @@ void main() { void f([Object? o]) { o is A; } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_class_unreachable_hasNamedConstructors() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} class C { C(); C.named(); } -''', [ - lint(22, 1), - // TODO(srawlins): See if we can skip reporting a declaration if its - // enclosing declaration is being reported. - lint(28, 1), - lint(37, 5), - ]); +''', + [ + lint(22, 1), + // TODO(srawlins): See if we can skip reporting a declaration if its + // enclosing declaration is being reported. + lint(28, 1), + lint(37, 5), + ], + ); } test_class_unreachable_mainInPart() async { @@ -480,18 +496,14 @@ part 'part.dart'; class A {} '''); await assertDiagnosticsInUnits([ - ( - '$testPackageLibPath/lib.dart', - [ - lint(25, 1), - ] - ), + ('$testPackageLibPath/lib.dart', [lint(25, 1)]), ('$testPackageLibPath/part.dart', []), ]); } test_class_unreachable_referencedInParameter_externalMethodDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { D().f; } @@ -501,13 +513,14 @@ class C {} class D { external f(C c); } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_class_unreachable_referencedInTypeAnnotation_fieldDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { D().c; } @@ -517,13 +530,14 @@ class C {} class D { C? c; } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_class_unreachable_referencedInTypeAnnotation_parameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { f(); } @@ -531,13 +545,14 @@ void main() { void f([C? c]) {} class C {} -''', [ - lint(49, 1), - ]); +''', + [lint(49, 1)], + ); } test_class_unreachable_referencedInTypeAnnotation_topLevelVariable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { print(c); } @@ -545,25 +560,27 @@ void main() { C? c; class C {} -''', [ - lint(42, 1), - ]); +''', + [lint(42, 1)], + ); } test_class_unreachable_referencedInTypeAnnotation_variableDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C? c; } class C {} -''', [ - lint(31, 1), - ]); +''', + [lint(31, 1)], + ); } test_class_unreachable_typeArgumentBound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { f(); } @@ -571,9 +588,9 @@ void main() { class C {} void f() {} -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_classInPart_reachable() async { @@ -622,16 +639,8 @@ part of 'lib.dart'; class A {} '''); await assertDiagnosticsInUnits([ - ( - '$testPackageLibPath/lib.dart', - [], - ), - ( - '$testPackageLibPath/part.dart', - [ - lint(27, 1), - ], - ), + ('$testPackageLibPath/lib.dart', []), + ('$testPackageLibPath/part.dart', [lint(27, 1)]), ]); } @@ -647,21 +656,14 @@ class A {} void main() {} '''); await assertDiagnosticsInUnits([ - ( - '$testPackageLibPath/lib.dart', - [], - ), - ( - '$testPackageLibPath/part.dart', - [ - lint(27, 1), - ], - ), + ('$testPackageLibPath/lib.dart', []), + ('$testPackageLibPath/part.dart', [lint(27, 1)]), ]); } test_constructor_named_onEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { E.one; E.two; @@ -673,10 +675,12 @@ enum E { const E(); const E.named(); } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 84, 5), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 84, 5), + ], + ); } test_constructor_named_reachableViaDirectCall() async { @@ -747,7 +751,8 @@ class C { } test_constructor_named_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -755,13 +760,14 @@ void main() { class C { C.named(); } -''', [ - lint(36, 5), - ]); +''', + [lint(36, 5)], + ); } test_constructor_named_unreachable_inExtensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { E(7); } @@ -769,13 +775,14 @@ void main() { extension type E(int it) { E.named(this.it); } -''', [ - lint(56, 5), - ]); +''', + [lint(56, 5)], + ); } test_constructor_named_unreachable_otherHasRedirectedConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C.two(); } @@ -785,9 +792,9 @@ class C { C.one(); factory C.two() = C.one; } -''', [ - lint(42, 5), - ]); +''', + [lint(42, 5)], + ); } test_constructor_reachableViaTestReflectiveLoader() async { @@ -957,7 +964,8 @@ class C { } test_constructor_unnamed_referencedInConstantPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { const C(); } @@ -969,14 +977,14 @@ void main() { void f([C? c]) { if (c case const C()) {} } -''', [ - lint(6, 1), - lint(18, 1), - ]); +''', + [lint(6, 1), lint(18, 1)], + ); } test_constructor_unnamed_referencedInConstantPattern_generic() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class C { const C(); } @@ -988,14 +996,14 @@ void main() { void f([C? c]) { if (c case const C()) {} } -''', [ - lint(6, 1), - lint(21, 1), - ]); +''', + [lint(6, 1), lint(21, 1)], + ); } test_constructor_unnamed_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -1003,13 +1011,14 @@ void main() { class C { C(); } -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_constructor_unnamed_unreachable_otherHasRedirection() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C.two(); } @@ -1019,9 +1028,9 @@ class C { C.one(); C.two() : this.one(); } -''', [ - lint(40, 1), - ]); +''', + [lint(40, 1)], + ); } test_enum_reachableViaValue() async { @@ -1035,23 +1044,25 @@ enum E { one, two } } test_enum_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} enum E { one, two } -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_extension_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} extension IntExtension on int {} -''', [ - lint(26, 12), - ]); +''', + [lint(26, 12)], + ); } test_extensionType_reachable_referencedInTypeAnnotation_asExpression() async { @@ -1076,7 +1087,8 @@ extension type E(int it) {} } test_instanceFieldOnExtension_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { E.f; } @@ -1085,9 +1097,9 @@ extension E on int { static int f = 1; void m() {} } -''', [ - lint(72, 1), - ]); +''', + [lint(72, 1)], + ); } test_instanceMethod_reachable_toJson() async { @@ -1105,7 +1117,8 @@ class C { } test_instanceMethod_unreachable_inExtensionType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { E(7); } @@ -1113,9 +1126,9 @@ void main() { extension type E(int it) { void m() {} } -''', [ - lint(59, 1), - ]); +''', + [lint(59, 1)], + ); } test_mixin_reachable_implemented() async { @@ -1143,17 +1156,19 @@ class A with M {} } test_mixin_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} mixin M {} -''', [ - lint(22, 1), - ]); +''', + [lint(22, 1)], + ); } test_staticField_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -1161,9 +1176,9 @@ void main() { class C { static int f = 1; } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_staticFieldOnClass_reachable() async { @@ -1204,7 +1219,8 @@ extension E on int { } test_staticFieldOnExtension_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { E(1).m(); } @@ -1213,9 +1229,9 @@ extension E on int { static int f = 1; void m() {} } -''', [ - lint(63, 1), - ]); +''', + [lint(63, 1)], + ); } test_staticFieldOnMixin_reachable() async { @@ -1243,7 +1259,8 @@ class C { } test_staticGetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -1251,13 +1268,14 @@ void main() { class C { static int get g => 7; } -''', [ - lint(49, 1), - ]); +''', + [lint(49, 1)], + ); } test_staticMethod_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -1265,9 +1283,9 @@ void main() { class C { static void f() {} } -''', [ - lint(46, 1), - ]); +''', + [lint(46, 1)], + ); } test_staticMethodOnClass_reachable() async { @@ -1332,7 +1350,8 @@ class C { } test_staticSetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() { C; } @@ -1340,9 +1359,9 @@ void main() { class C { static set s(int value) {} } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_topLevelFunction_reachable() async { @@ -1370,24 +1389,26 @@ void _f() {} } test_topLevelFunction_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} void f() {} -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_topLevelFunction_unreachable_unrelatedPragma() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} @pragma('other') void f() {} -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_topLevelFunction_unreachable_visibleForTesting() async { @@ -1426,13 +1447,14 @@ int get g => 7; } test_topLevelGetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} int get g => 7; -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_topLevelSetter_reachable() async { @@ -1446,13 +1468,14 @@ set s(int value) {} } test_topLevelSetter_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} set s(int value) {} -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_topLevelVariable_reachable() async { @@ -1470,13 +1493,14 @@ int x = 1; } test_topLevelVariable_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} int x = 1; -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_typedef_reachable_referencedAsInstanceCreation_named() async { @@ -1609,12 +1633,13 @@ typedef Cb = void Function(); } test_typedef_unreachable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void main() {} typedef T = String; -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } } diff --git a/pkg/linter/test/rules/unrelated_type_equality_checks_test.dart b/pkg/linter/test/rules/unrelated_type_equality_checks_test.dart index 2ed497767a57..d78e0abe866f 100644 --- a/pkg/linter/test/rules/unrelated_type_equality_checks_test.dart +++ b/pkg/linter/test/rules/unrelated_type_equality_checks_test.dart @@ -48,15 +48,16 @@ void f(Int32 p) { } test_fixnum_int32_rightSide() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:fixnum/fixnum.dart'; void f(Int32 p) { if (0 == p) {} } -''', [ - lint(64, 2), - ]); +''', + [lint(64, 2)], + ); } test_fixnum_int64_leftSide() async { @@ -70,15 +71,16 @@ void f(Int64 p) { } test_fixnum_int64_rightSide() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:fixnum/fixnum.dart'; void f(Int64 p) { if (0 == p) {} } -''', [ - lint(64, 2), - ]); +''', + [lint(64, 2)], + ); } test_futureOfDynamic_andFutureOfVoid() async { @@ -144,15 +146,16 @@ enum E { one, two; } } test_oneEnum_andUnrelatedEnum() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(E x, F y) { if (x == y) {} } enum E { one, two; } enum F { three, four; } -''', [ - lint(27, 2), - ]); +''', + [lint(27, 2)], + ); } test_oneType_andSubtype() async { @@ -174,11 +177,12 @@ void f(A a, B b) { } test_recordAndInterfaceType_unrelated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f((int, int) a, String b) => a == b; -''', [ - lint(36, 2), - ]); +''', + [lint(36, 2)], + ); } test_records_related() async { @@ -188,11 +192,12 @@ bool f((int, int) a, (num, num) b) => a == b; } test_records_unrelated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f((int, int) a, (String, String) b) => a == b; -''', [ - lint(46, 2), - ]); +''', + [lint(46, 2)], + ); } test_recordsWithNamed_related() async { @@ -202,11 +207,12 @@ bool f(({int one, int two}) a, ({num two, num one}) b) => a == b; } test_recordsWithNamed_unrelated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f(({int one, int two}) a, ({String one, String two}) b) => a == b; -''', [ - lint(66, 2), - ]); +''', + [lint(66, 2)], + ); } test_recordsWithNamedAndPositional_related() async { @@ -216,32 +222,37 @@ bool f((int, {int two}) a, (num one, {num two}) b) => a == b; } test_recordsWithNamedAndPositional_unrelated() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool f((int, {int two}) a, (String one, {String two}) b) => a == b; -''', [ - lint(62, 2), - ]); +''', + [lint(62, 2)], + ); } test_string_andInt() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if ('foo' == 1) {} } -''', [ - lint(23, 2), - ]); +''', + [lint(23, 2)], + ); } test_string_andNull() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { if ('foo' == null) {} } -''', [ - // No lint. - error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_FALSE, 23, 7), - ]); +''', + [ + // No lint. + error(WarningCode.UNNECESSARY_NULL_COMPARISON_NEVER_NULL_FALSE, 23, 7), + ], + ); } test_string_andString() async { @@ -253,7 +264,8 @@ void f() { } test_switchExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const space = 32; String f(int char) { @@ -261,27 +273,33 @@ String f(int char) { == 'space' => 'space', }; } -''', [ - error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 49, 6), - lint(69, 10), - ]); +''', + [ + error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 49, 6), + lint(69, 10), + ], + ); } test_switchExpression_lessEq_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String f(int i) { return switch (i) { <= 1 => 'one', }; } -''', [ - // No lint. - error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 27, 6) - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 27, 6), + ], + ); } test_switchExpression_notEq() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' const space = 32; String f(int char) { @@ -289,33 +307,39 @@ String f(int char) { != 'space' => 'space', }; } -''', [ - error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 49, 6), - lint(69, 10), - ]); +''', + [ + error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 49, 6), + lint(69, 10), + ], + ); } test_switchExpression_ok() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' String f(String char) { return switch (char) { == 'space' => 'space', }; } -''', [ - // No lint. - error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 33, 6), - ]); +''', + [ + // No lint. + error(CompileTimeErrorCode.NON_EXHAUSTIVE_SWITCH_EXPRESSION, 33, 6), + ], + ); } test_twoListsOfTypeVariables_unrelatedBounds() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(List a, List b) { if (a == b) {} } -''', [ - lint(70, 2), - ]); +''', + [lint(70, 2)], + ); } test_twoListsOfUnrelatedTypeVariables() async { @@ -343,7 +367,8 @@ void f(Map a, Map b) { } test_twoSubtypesOfSharedDistantSupertype() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(D2 x, E2 y) { if (x == y) {} } @@ -352,9 +377,9 @@ class D1 extends C {} class E1 extends C {} class D2 extends D1 {} class E2 extends E1 {} -''', [ - lint(29, 2), - ]); +''', + [lint(29, 2)], + ); } test_twoSubtypesOfSharedSupertype() async { @@ -377,13 +402,14 @@ void f(A a, B b) { } test_twoTypeVariables_unrelatedBounds() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a, B b) { if (a == b) {} } -''', [ - lint(58, 2), - ]); +''', + [lint(58, 2)], + ); } test_twoUnrelatedTypeVariables() async { diff --git a/pkg/linter/test/rules/unsafe_variance_test.dart b/pkg/linter/test/rules/unsafe_variance_test.dart index 2f97b236af37..48d1aac5ca01 100644 --- a/pkg/linter/test/rules/unsafe_variance_test.dart +++ b/pkg/linter/test/rules/unsafe_variance_test.dart @@ -18,23 +18,25 @@ class UnsafeVarianceTest extends LintRuleTest { String get lintRule => 'unsafe_variance'; test_class_getter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void Function([X])? get func2 => null; } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_class_method_bound() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int Function() m2() => () => 2; } -''', [ - lint(38, 1), - ]); +''', + [lint(38, 1)], + ); } test_class_method_parameter() async { @@ -47,46 +49,50 @@ class A { } test_class_method_return() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { X Function(X) m1() => (X x) => x; } -''', [ - lint(26, 1), - ]); +''', + [lint(26, 1)], + ); } test_class_method_return_typedef() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { Func m1() => (X x) => x; } typedef Func = X Function(X); -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_class_variable() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { void Function(X) func; A(this.func); } -''', [ - lint(29, 1), - ]); +''', + [lint(29, 1)], + ); } test_enum_getter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' enum E { e; void Function([X])? get func2 => null; } -''', [ - lint(34, 1), - ]); +''', + [lint(34, 1)], + ); } test_extension_getter() async { @@ -106,13 +112,14 @@ extension type A(X x) { } test_mixin_getter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin A { void Function([X])? get func2; } -''', [ - lint(30, 1), - ]); +''', + [lint(30, 1)], + ); } test_static_class_member() async { diff --git a/pkg/linter/test/rules/use_build_context_synchronously_test.dart b/pkg/linter/test/rules/use_build_context_synchronously_test.dart index 0bbf14f295d1..2a115f50a4ca 100644 --- a/pkg/linter/test/rules/use_build_context_synchronously_test.dart +++ b/pkg/linter/test/rules/use_build_context_synchronously_test.dart @@ -42,8 +42,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_adjacentStrings_referenceInSecondString_awaitInFirstString() async { @@ -55,8 +57,10 @@ void foo(BuildContext context) async { '''); var adjacentStrings = findNode.adjacentStrings('await'); var reference = findNode.stringInterpolation('context /* ref */'); - expect(adjacentStrings.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + adjacentStrings.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_awaitExpression_referenceInExpression() async { @@ -81,8 +85,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('context /* ref */'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_cascade_referenceAfter_awaitInTarget() async { @@ -95,8 +101,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_cascade_referenceAfterTarget_awaitAfterTarget() async { @@ -108,8 +116,10 @@ void foo(BuildContext context) async { '''); var cascade = findNode.cascade('await'); var reference = findNode.methodInvocation('context /* ref */'); - expect(cascade.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + cascade.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_cascade_referenceAfterTarget_awaitInTarget() async { @@ -121,8 +131,10 @@ void foo(BuildContext context) async { '''); var cascade = findNode.cascade('await'); var reference = findNode.methodInvocation('context /* ref */'); - expect(cascade.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + cascade.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_cascade_referenceAfterTarget_awaitInTarget2() async { @@ -134,8 +146,10 @@ void foo(BuildContext context) async { '''); var cascade = findNode.cascade('await'); var reference = findNode.methodInvocation('context /* ref */'); - expect(cascade.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + cascade.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_conditional_referenceAfter_awaitInCondition() async { @@ -148,8 +162,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_conditional_referenceAfter_awaitInThen() async { @@ -162,8 +178,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('false'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_conditional_referenceInElse_mountedCheckInCondition() async { @@ -187,8 +205,10 @@ void foo(BuildContext context) async { '''); var conditional = findNode.conditionalExpression('context /* ref */'); var reference = findNode.simple('context /* ref */'); - expect(conditional.asyncStateFor(reference, contextElement), - equals(AsyncState.mountedCheck)); + expect( + conditional.asyncStateFor(reference, contextElement), + equals(AsyncState.mountedCheck), + ); } test_conditional_referenceInThen_mountedCheckInCondition() async { @@ -200,8 +220,10 @@ void foo(BuildContext context) async { '''); var conditional = findNode.conditionalExpression('context /* ref */'); var reference = findNode.simple('context /* ref */'); - expect(conditional.asyncStateFor(reference, contextElement), - equals(AsyncState.mountedCheck)); + expect( + conditional.asyncStateFor(reference, contextElement), + equals(AsyncState.mountedCheck), + ); } test_conditional_referenceInThen_notMountedCheckInCondition() async { @@ -228,8 +250,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('context /* ref */'); var reference = findNode.statement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_doWhileStatement_referenceInBody_asyncInBody2() async { @@ -244,8 +268,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('context /* ref */'); var reference = findNode.statement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_extensionOverride_referenceAfter_awaitInArgument() async { @@ -262,8 +288,10 @@ extension E on int { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithDeclaration_referenceAfter_awaitInPartCondition() async { @@ -278,8 +306,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithDeclaration_referenceAfter_awaitInPartInitialization() async { @@ -294,8 +324,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithDeclaration_referenceAfter_awaitInPartUpdaters() async { @@ -310,8 +342,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithDeclaration_referenceInExpression_mountedCheckInPartCondition() async { @@ -325,8 +359,10 @@ void foo(BuildContext context) async { '''); var forElement = findNode.forElement('for '); var reference = findNode.expression('context /* ref */'); - expect(forElement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + forElement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_forElementWithEach_referenceAfter_awaitInExpression() async { @@ -341,8 +377,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithEach_referenceAfter_awaitInPartExpression() async { @@ -357,8 +395,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithExpression_referenceAfter_awaitInPartCondition() async { @@ -373,8 +413,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithExpression_referenceAfter_awaitInPartInitialization() async { @@ -389,8 +431,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithExpression_referenceAfter_awaitInPartUpdaters() async { @@ -405,8 +449,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forElementWithExpression_referenceAfter_mountedCheckInPartCondition() async { @@ -420,8 +466,10 @@ void foo(BuildContext context, int i) async { '''); var forElement = findNode.forElement('for '); var reference = findNode.expression('context /* ref */'); - expect(forElement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + forElement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_forStatement_referenceInBody_asyncInBody() async { @@ -436,8 +484,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('context /* ref */'); var reference = findNode.statement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatement_referenceInBody_asyncInBody2() async { @@ -452,8 +502,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('context /* ref */'); var reference = findNode.statement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithDeclaration_referenceAfter_awaitInPartCondition() async { @@ -466,8 +518,10 @@ void foo(BuildContext context) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithDeclaration_referenceAfter_awaitInPartInitialization() async { @@ -480,8 +534,10 @@ void foo(BuildContext context) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithDeclaration_referenceAfter_awaitInPartUpdaters() async { @@ -494,8 +550,10 @@ void foo(BuildContext context) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithDeclaration_referenceInBody_mountedCheckInPartCondition() async { @@ -507,8 +565,10 @@ void foo(BuildContext context) async { '''); var forStatement = findNode.forStatement('for '); var reference = findNode.expressionStatement('context /* ref */'); - expect(forStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + forStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_forStatementWithEach_referenceAfter_awaitInPartExpression() async { @@ -521,8 +581,10 @@ void foo(BuildContext context) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithExpression_referenceAfter_awaitInPartCondition() async { @@ -535,8 +597,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithExpression_referenceAfter_awaitInPartInitialization() async { @@ -549,8 +613,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithExpression_referenceAfter_awaitInPartUpdaters() async { @@ -563,8 +629,10 @@ void foo(BuildContext context, int i) async { '''); var block = findNode.forStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_forStatementWithExpression_referenceAfter_mountedCheckInPartCondition() async { @@ -576,8 +644,10 @@ void foo(BuildContext context, int i) async { '''); var forStatement = findNode.forStatement('for '); var reference = findNode.expressionStatement('context /* ref */'); - expect(forStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + forStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_functionExpressionInvocation_referenceAfter_awaitInTarget() async { @@ -590,8 +660,10 @@ void foo(BuildContext context) async { '''); var block = findNode.block('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifElement_referenceAfter_asyncInCondition() async { @@ -606,8 +678,10 @@ void foo(BuildContext context) async { '''); var ifElement = findNode.listLiteral('if ('); var reference = findNode.expression('context /* ref */,'); - expect(ifElement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifElement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifElement_referenceInElse_asyncInCondition() async { @@ -621,8 +695,10 @@ void foo(BuildContext context) async { '''); var ifElement = findNode.ifElement('if ('); var reference = findNode.expression('context /* ref */'); - expect(ifElement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifElement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifElement_referenceInElse_mountedGuardInCondition() async { @@ -650,8 +726,10 @@ void foo(BuildContext context) async { '''); var ifElement = findNode.ifElement('if ('); var reference = findNode.expression('context /* ref */'); - expect(ifElement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifElement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifElement_referenceInThen_asyncInCondition() async { @@ -665,8 +743,10 @@ void foo(BuildContext context) async { '''); var ifElement = findNode.ifElement('if ('); var reference = findNode.expression('context /* ref */'); - expect(ifElement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifElement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceAfter_asyncInCondition() async { @@ -681,8 +761,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if (').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceAfter_asyncInThen_notMountedGuardInElse() async { @@ -699,8 +781,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if (1').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceAfter_asyncOrNotMountedInCondition() async { @@ -715,8 +799,10 @@ void foo(BuildContext context) async { '''); var body = findNode.ifStatement('if ').parent!; var reference = findNode.statement('context /* ref */'); - expect(body.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + body.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_awaitThenExitInElse() async { @@ -762,8 +848,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_conditionHasMountedEqEqNonConstant_exit() async { @@ -815,8 +903,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_conditionHasNotMountedEqEqFalse_exit() async { @@ -842,8 +932,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_conditionHasNotMountedNotEqTrue_exit() async { @@ -872,8 +964,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_notMountedCheckInCondition_exit() async { @@ -886,8 +980,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_notMountedGuardInCondition_exitInThen_awaitInElse() async { @@ -904,8 +1000,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if (').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceAfter_notMountedGuardsInThenAndElse() async { @@ -922,8 +1020,10 @@ void foo(BuildContext context) async { '''); var block = findNode.ifStatement('if (1').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceAfter_notStateMountedCheckInCondition_exit() async { @@ -937,8 +1037,10 @@ abstract class C extends State { '''); var block = findNode.ifStatement('if ').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_ifStatement_referenceInCaseWhen_asyncInCondition() async { @@ -954,8 +1056,10 @@ bool f(BuildContext context) => true; '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInElse_asyncInCondition() async { @@ -970,8 +1074,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInElse_mountedGuardInCondition() async { @@ -1001,8 +1107,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInElse_notMountedOrUninterestingInCondition() async { @@ -1017,8 +1125,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInElse_uninterestingAndNotMountedInCondition() async { @@ -1033,8 +1143,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInElse_uninterestingOrNotMountedInCondition() async { @@ -1049,8 +1161,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_asyncInAssignmentInCondition() async { @@ -1064,8 +1178,10 @@ void foo(BuildContext context, bool m) async { '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_asyncInCaseWhen() async { @@ -1079,8 +1195,10 @@ void foo(BuildContext context, Object value) async { '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInThen_asyncInCondition() async { @@ -1094,8 +1212,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInThen_awaitAndMountedInCondition() async { @@ -1109,8 +1229,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_awaitOrMountedInCondition() async { @@ -1124,8 +1246,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInThen_conditionAndMountedInCondition() async { @@ -1139,8 +1263,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_mountedAndAwaitInCondition() async { @@ -1154,8 +1280,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInThen_mountedGuardInCaseWhen() async { @@ -1169,8 +1297,10 @@ void foo(BuildContext context, Object value) async { '''); var ifStatement = findNode.ifStatement('if ('); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_mountedInCondition() async { @@ -1184,8 +1314,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_ifStatement_referenceInThen_mountedOrAwaitInCondition() async { @@ -1199,8 +1331,10 @@ void foo(BuildContext context) async { '''); var ifStatement = findNode.ifStatement('if '); var reference = findNode.block('context /* ref */'); - expect(ifStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + ifStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_ifStatement_referenceInThen_uninterestingOrMountedInCondition() async { @@ -1226,8 +1360,10 @@ void foo(BuildContext context, List list) async { '''); var indexExpression = findNode.assignment('['); var reference = findNode.expression('context /* ref */'); - expect(indexExpression.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + indexExpression.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_instanceCreationExpression_referenceInParameters_awaitInParameters() async { @@ -1239,8 +1375,10 @@ void foo(BuildContext context) async { '''); var instanceCreation = findNode.instanceCreation('await'); var reference = findNode.argumentList('context /* ref */'); - expect(instanceCreation.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + instanceCreation.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_isExpression_referenceAfter_awaitInExpression() async { @@ -1254,8 +1392,10 @@ Future c() async {} '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_methodInvocation_referenceAfter_asyncInTarget() async { @@ -1268,8 +1408,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_methodInvocation_referenceAfter_awaitInParameters() async { @@ -1282,8 +1424,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_methodInvocation_referenceAfter_awaitInTarget() async { @@ -1296,8 +1440,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_methodInvocation_referenceInParameters_awaitInParameters() async { @@ -1310,8 +1456,10 @@ void f(_, _) {} '''); var methodInvocation = findNode.methodInvocation('await'); var reference = findNode.argumentList('context /* ref */'); - expect(methodInvocation.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + methodInvocation.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_postfix_referenceAfter_awaitInExpression() async { @@ -1324,8 +1472,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_propertyAccess_referenceAfter_awaitInTarget() async { @@ -1338,8 +1488,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_recordLiteral_referenceAfter_awaitInField() async { @@ -1352,8 +1504,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_recordLiteral_referenceAfter_awaitInNamedField() async { @@ -1366,8 +1520,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_spread_referenceAfter_awaitInSpread() async { @@ -1380,8 +1536,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_stringInterpolation_referenceAfter_awaitInStringInterpolation() async { @@ -1394,8 +1552,10 @@ void foo(BuildContext context) async { '''); var block = findNode.stringInterpolation('await').parent!.parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchExpression_referenceAfter_awaitInCaseBody() async { @@ -1410,8 +1570,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('switch').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchExpression_referenceAfter_awaitInCondition() async { @@ -1426,8 +1588,10 @@ void foo(BuildContext context) async { '''); var block = findNode.expressionStatement('switch').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchExpression_referenceInExpression_awaitInCondition() async { @@ -1441,8 +1605,10 @@ void foo(BuildContext context) async { '''); var switchExpression = findNode.switchExpression('switch'); var reference = findNode.switchExpressionCase('context /* ref */'); - expect(switchExpression.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + switchExpression.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchExpression_referenceInExpression_awaitInWhenClause() async { @@ -1457,8 +1623,10 @@ void foo(BuildContext context) async { '''); var switchExpression = findNode.switchExpressionCase('await'); var reference = findNode.simple('context /* ref */'); - expect(switchExpression.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + switchExpression.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchExpression_referenceInExpression_mountedGuardInWhenClause() async { @@ -1473,8 +1641,10 @@ void foo(BuildContext context) async { '''); var switchExpression = findNode.switchExpressionCase('when'); var reference = findNode.simple('context /* ref */'); - expect(switchExpression.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + switchExpression.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_switchExpression_referenceInWhenClause_awaitInExpression() async { @@ -1505,8 +1675,10 @@ void foo(BuildContext context) async { '''); var block = findNode.switchStatement('switch').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceAfter_awaitInCaseWhen() async { @@ -1521,8 +1693,10 @@ void foo(BuildContext context) async { '''); var block = findNode.switchStatement('case').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceAfter_awaitInDefault() async { @@ -1538,8 +1712,10 @@ void foo(BuildContext context) async { '''); var block = findNode.switchStatement('switch').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceAfter_mountedCheckInCaseWhen() async { @@ -1569,8 +1745,10 @@ void foo(BuildContext context) async { '''); var switchStatement = findNode.switchStatement('switch'); var reference = findNode.switchPatternCase('context /* ref */'); - expect(switchStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + switchStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceInCaseBody_awaitInOtherCase() async { @@ -1602,8 +1780,10 @@ void foo(BuildContext context) async { '''); var switchStatement = findNode.switchStatement('switch'); var reference = findNode.switchPatternCase('context /* ref */'); - expect(switchStatement.asyncStateFor(reference, contextElement), - AsyncState.mountedCheck); + expect( + switchStatement.asyncStateFor(reference, contextElement), + AsyncState.mountedCheck, + ); } test_switchStatement_referenceInCaseBody_mountedCheckInCaseWhen2() async { @@ -1635,8 +1815,10 @@ void foo(BuildContext context) async { '''); var switchStatement = findNode.switchStatement('switch'); var reference = findNode.switchPatternCase('context /* ref */'); - expect(switchStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + switchStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceInCaseBody_mountedCheckInCaseWhen4() async { @@ -1684,8 +1866,10 @@ void foo(BuildContext context) async { '''); var switchStatement = findNode.switchDefault('await'); var reference = findNode.expressionStatement('context /* ref */'); - expect(switchStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + switchStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_switchStatement_referenceInDefault_mountedGuardInDefault() async { @@ -1701,8 +1885,10 @@ void foo(BuildContext context) async { '''); var switchStatement = findNode.switchDefault('context.mounted'); var reference = findNode.expressionStatement('context /* ref */'); - expect(switchStatement.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + switchStatement.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_tryStatement_referenceAfter_awaitInBody() async { @@ -1718,8 +1904,10 @@ Future c() async {} '''); var block = findNode.tryStatement('try').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_tryStatement_referenceAfter_awaitInCatch() async { @@ -1736,8 +1924,10 @@ Future c() async {} '''); var block = findNode.tryStatement('try').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_tryStatement_referenceAfter_awaitInFinally() async { @@ -1754,8 +1944,10 @@ Future c() async {} '''); var block = findNode.tryStatement('try').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_tryStatement_referenceAfter_notMountedCheckInCatch() async { @@ -1805,8 +1997,10 @@ Future c() async {} '''); var block = findNode.tryStatement('try').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.notMountedCheck); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.notMountedCheck, + ); } test_tryStatement_referenceInCatch_awaitInBody() async { @@ -1823,8 +2017,10 @@ Future c() async {} '''); var tryStatement = findNode.tryStatement('try'); var reference = findNode.catchClause('context /* ref */'); - expect(tryStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + tryStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_tryStatement_referenceInFinally_awaitInCatch() async { @@ -1842,8 +2038,10 @@ Future c() async {} '''); var tryStatement = findNode.tryStatement('try'); var reference = findNode.block('context /* ref */'); - expect(tryStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + tryStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_whileStatement_referenceAfter_asyncInBody() async { @@ -1859,8 +2057,10 @@ void foo(BuildContext context) async { '''); var block = findNode.whileStatement('while (').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_whileStatement_referenceInBody_asyncInBody() async { @@ -1875,8 +2075,10 @@ void foo(BuildContext context) async { '''); var whileStatement = findNode.whileStatement('while ('); var reference = findNode.block('context /* ref */'); - expect(whileStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + whileStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_whileStatement_referenceInBody_asyncInBody2() async { @@ -1891,8 +2093,10 @@ void foo(BuildContext context) async { '''); var whileStatement = findNode.whileStatement('while ('); var reference = findNode.block('context /* ref */'); - expect(whileStatement.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + whileStatement.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } test_yield_referenceAfter_asyncInExpression() async { @@ -1905,8 +2109,10 @@ void foo(BuildContext context) async { '''); var block = findNode.yieldStatement('await').parent!; var reference = findNode.expressionStatement('context /* ref */'); - expect(block.asyncStateFor(reference, contextElement), - AsyncState.asynchronous); + expect( + block.asyncStateFor(reference, contextElement), + AsyncState.asynchronous, + ); } } @@ -1925,7 +2131,8 @@ class UseBuildContextSynchronouslyTest extends LintRuleTest { test_assignmentExpressionContainsMountedCheck_thenReferenceToContext() async { // Assignment statement-expression with mounted check, then use of // BuildContext in if-then statement, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -1935,9 +2142,9 @@ void foo(BuildContext context) async { } Future c() async {} -''', [ - lint(134, 7), - ]); +''', + [lint(134, 7)], + ); } test_async_thenMountedCheck_thenSwitchWithReferenceToContext() async { @@ -1963,7 +2170,8 @@ Future c() async {} test_async_thenSwitchWithReferenceToContext() async { // Assignment statement-expression with mounted check, then use of // BuildContext in if-then statement, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -1976,9 +2184,9 @@ void foo(BuildContext context) async { } Future c() async {} -''', [ - lint(138, 7), - ]); +''', + [lint(138, 7)], + ); } test_await_afterReferenceToContext() async { @@ -1997,7 +2205,8 @@ Future f() async {} test_await_beforeReferenceToContext() async { // Await, then use of BuildContext, in statement block is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2006,15 +2215,16 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(107, 7), - ]); +''', + [lint(107, 7)], + ); } test_await_beforeReferenceToContext_inParens() async { // Await, then use of BuildContext in parentheses, in statement block is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2023,15 +2233,16 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(107, 9), - ]); +''', + [lint(107, 9)], + ); } test_await_beforeReferenceToContext_nullAsserted() async { // Await, then use of null-asserted BuildContext, in statement block is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext? context) async { @@ -2040,14 +2251,15 @@ void foo(BuildContext? context) async { } Future f() async {} -''', [ - lint(108, 8), - ]); +''', + [lint(108, 8)], + ); } test_await_thenMountedGuard_thenReferenceToStateBuildContext() async { // Await, then mounted guard, then reference to State.context, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class C extends State { @@ -2059,9 +2271,9 @@ abstract class C extends State { } Future f() async {} -''', [ - lint(195, 12, messageContains: "an unrelated 'mounted' check"), - ]); +''', + [lint(195, 12, messageContains: "an unrelated 'mounted' check")], + ); } test_await_thenNotMountedCheck_thenReferenceToContext() async { @@ -2085,7 +2297,8 @@ Future f() async {} test_await_thenNotMountedCheck_thenReferenceToStateContext() async { // Await, then a `BuildContext.mounted` check, then use `State.context`, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class C extends State { @@ -2097,9 +2310,9 @@ abstract class C extends State { } Future f() async {} -''', [ - lint(176, 7), - ]); +''', + [lint(176, 7)], + ); } test_await_thenNotMountedCheckInBinaryOr_thenReferenceToContext() async { @@ -2121,7 +2334,8 @@ Future f() async {} test_await_thenNotStateMountedCheck_thenReferenceToContext() async { // Await, then a `State.mounted` check, then use a local BuildContext, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class C extends State { @@ -2133,9 +2347,9 @@ abstract class C extends State { } Future f() async {} -''', [ - lint(188, 7, messageContains: "an unrelated 'mounted' check"), - ]); +''', + [lint(188, 7, messageContains: "an unrelated 'mounted' check")], + ); } test_await_thenNotStateMountedCheck_thenReferenceToStateContext() async { @@ -2159,7 +2373,8 @@ Future f() async {} test_await_thenStateMountedGuard_thenReferenceToBuildContext() async { // Await, then State.mounted guard, then reference to BuildContext, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class C extends State { @@ -2171,15 +2386,16 @@ abstract class C extends State { } Future f() async {} -''', [ - lint(192, 7, messageContains: "an unrelated 'mounted' check"), - ]); +''', + [lint(192, 7, messageContains: "an unrelated 'mounted' check")], + ); } test_awaitBeforeForBody_referenceToContext_thenMountedGuard() async { // Await, then for-each statement, and inside the for-body: use of // BuildContext, then mounted guard, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2191,14 +2407,15 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(131, 7), - ]); +''', + [lint(131, 7)], + ); } test_awaitBeforeIfStatement_withReferenceToContext() async { // Await, then use of BuildContext in an unrelated if-body, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2208,9 +2425,9 @@ void foo(BuildContext context) async { } } Future c() async => true; -''', [ - lint(128, 7), - ]); +''', + [lint(128, 7)], + ); } test_awaitBeforeReferenceToContext_inClosure() async { @@ -2235,7 +2452,8 @@ Future c() async => true; test_awaitBeforeWhileBody_referenceToContext_thenMountedGuard() async { // Await, then While-true statement, and inside the while-body: use of // BuildContext, then mounted guard, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2247,9 +2465,9 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(126, 7), - ]); +''', + [lint(126, 7)], + ); } test_awaitInIfCondition_expressionContainsReferenceToContext() async { @@ -2269,7 +2487,8 @@ void foo( test_awaitInIfThenAndExitInElse_beforeReferenceToContext() async { // Await in an if-body and await-and-exit in the associated else, then use // of BuildContext, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2282,14 +2501,15 @@ void foo(BuildContext context) async { Navigator.of(context); } Future c() async => true; -''', [ - lint(167, 7), - ]); +''', + [lint(167, 7)], + ); } /// https://github.com/dart-lang/linter/issues/3818 test_context_propertyAccess() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; class W { @@ -2303,14 +2523,15 @@ class W { Future g(BuildContext context) async {} } -''', [ - lint(159, 12), - ]); +''', + [lint(159, 12)], + ); } /// https://github.com/dart-lang/linter/issues/3676 test_contextPassedAsNamedParam() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Future foo(BuildContext context) async { @@ -2319,14 +2540,15 @@ Future foo(BuildContext context) async { } Future bar({required BuildContext context}) async {} -''', [ - lint(121, 16), - ]); +''', + [lint(121, 16)], + ); } test_future_catchError_referenceToContextInNamedArgument() async { // `Future.catchError` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context, Future f) async { f.catchError((_) {}, test: (_) { @@ -2334,66 +2556,72 @@ void foo(BuildContext context, Future f) async { return false; }); } -''', [ - lint(146, 7), - ]); +''', + [lint(146, 7)], + ); } test_future_catchError_referenceToContextInPositionalArgument() async { // `Future.catchError` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context, Future f) async { f.catchError((_) { Navigator.of(context); }); } -''', [ - lint(132, 7), - ]); +''', + [lint(132, 7)], + ); } test_future_catchError_referenceToContextInPositionalArgument_precedingNamedArgument() async { // `Future.catchError` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context, Future f) async { f.catchError(test: (_) => false, (_) { Navigator.of(context); }); } -''', [ - lint(152, 7), - ]); +''', + [lint(152, 7)], + ); } test_future_delayed_referenceToContextInWrongArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { Future.delayed((_) { Navigator.of(context); }); } -''', [ - // Just don't crash when one argument references BuildContext, and not all - // positional arguments are given. - error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 95, 36), - ]); +''', + [ + // Just don't crash when one argument references BuildContext, and not all + // positional arguments are given. + error(CompileTimeErrorCode.ARGUMENT_TYPE_NOT_ASSIGNABLE, 95, 36), + ], + ); } test_future_new_referenceToContextInArgument() async { // `Future.new()` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { Future.new(() { Navigator.of(context); }); } -''', [ - lint(113, 7), - ]); +''', + [lint(113, 7)], + ); } test_future_then_noReferenceToContext() async { @@ -2408,28 +2636,30 @@ void foo(BuildContext context, Future f) async { test_future_then_referenceToContextInCallback() async { // `Future.then` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context, Future f) async { f.then((_) { Navigator.of(context); }); } -''', [ - lint(126, 7), - ]); +''', + [lint(126, 7)], + ); } test_future_then_referenceToContextInCallback_expressionBody() async { // `Future.then` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context, Future f) async { f.then((_) => Navigator.of(context)); } -''', [ - lint(123, 7), - ]); +''', + [lint(123, 7)], + ); } test_future_then_referenceToContextInCallback_mountedGuard() async { @@ -2447,30 +2677,32 @@ void foo(BuildContext context, Future f) async { test_future_unnamed_referenceToContextInArgument() async { // `Future()` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { Future(() { Navigator.of(context); }); } -''', [ - lint(109, 7), - ]); +''', + [lint(109, 7)], + ); } test_future_wait_referenceToContextInArgument() async { // `Future.wait` call, with use of BuildContext inside, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { Future.wait([], cleanUp: (_) { Navigator.of(context); }); } -''', [ - lint(128, 7), - ]); +''', + [lint(128, 7)], + ); } test_ifConditionContainsMountedAndReferenceToContext() async { @@ -2494,7 +2726,8 @@ Future c() async {} test_ifConditionContainsMountedCheckInAssignmentLhs_thenReferenceToContext() async { // If-condition contains assignment with mounted check on LHS, then use of // BuildContext in if-then statement, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2510,15 +2743,16 @@ class A { } Future c() async {} -''', [ - lint(147, 7), - ]); +''', + [lint(147, 7)], + ); } test_ifConditionContainsMountedOrReferenceToContext() async { // Binary expression contains mounted check OR use of BuildContext, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo( @@ -2530,15 +2764,16 @@ void foo( } Future c() async {} -''', [ - lint(171, 7), - ]); +''', + [lint(171, 7)], + ); } test_ifConditionContainsNotMountedAndReferenceToContext() async { // Binary expression contains not-mounted check AND use of BuildContext, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo( @@ -2550,9 +2785,9 @@ void foo( } Future c() async {} -''', [ - lint(172, 7), - ]); +''', + [lint(172, 7)], + ); } test_noAwaitBefore_ifEmptyThen_methodInvocation() async { @@ -2572,7 +2807,8 @@ extension on BuildContext { /// https://github.com/dart-lang/linter/issues/3700 test_propertyAccess_getter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; extension on BuildContext { @@ -2583,13 +2819,14 @@ Future f(BuildContext context) async { await Future.value(); context.foo; } -''', [ - lint(174, 7), - ]); +''', + [lint(174, 7)], + ); } test_propertyAccess_setter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; extension on BuildContext { @@ -2600,9 +2837,9 @@ Future f(BuildContext context) async { await Future.value(); context.foo = 1; } -''', [ - lint(162, 7), - ]); +''', + [lint(162, 7)], + ); } test_referenceToContextInAwait() async { @@ -2621,7 +2858,8 @@ void foo(BuildContext context) async { test_referenceToContextInDoWhileBody_thenAwait() async { // Do-while statement, and inside the do-while-body: use of BuildContext, // then await, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2632,15 +2870,16 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(103, 7), - ]); +''', + [lint(103, 7)], + ); } test_referenceToContextInForBody_thenAwait() async { // For-each statement, and inside the for-body: use of BuildContext, then // await, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2651,14 +2890,15 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(118, 7), - ]); +''', + [lint(118, 7)], + ); } test_referenceToContextInFunctionExpression() async { // Inside a function expression, await then use of BuildContext is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2669,15 +2909,16 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(124, 7), - ]); +''', + [lint(124, 7)], + ); } test_referenceToContextInWhileBody_thenAwait() async { // While statement, and inside the while-body: use of BuildContext, then // await, is REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; void foo(BuildContext context) async { @@ -2688,15 +2929,16 @@ void foo(BuildContext context) async { } Future f() async {} -''', [ - lint(113, 7), - ]); +''', + [lint(113, 7)], + ); } test_streamSubscription_onData_referenceToContextInCallback() async { // `StreamSubscription.onData` call, with use of BuildContext inside, is // REPORTED. - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; import 'dart:async'; void foo(BuildContext context, StreamSubscription s) async { @@ -2704,9 +2946,9 @@ void foo(BuildContext context, StreamSubscription s) async { Navigator.of(context); }); } -''', [ - lint(161, 7), - ]); +''', + [lint(161, 7)], + ); } } diff --git a/pkg/linter/test/rules/use_colored_box_test.dart b/pkg/linter/test/rules/use_colored_box_test.dart index 8696aa5f0476..5d5172c49863 100644 --- a/pkg/linter/test/rules/use_colored_box_test.dart +++ b/pkg/linter/test/rules/use_colored_box_test.dart @@ -45,7 +45,8 @@ Widget f() { } test_colorArgument_andChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget containerWithColorAndChild() { @@ -54,9 +55,9 @@ Widget containerWithColorAndChild() { child: SizedBox(), ); } -''', [ - lint(87, 9), - ]); +''', + [lint(87, 9)], + ); } test_colorArgument_named_moreArguments() async { diff --git a/pkg/linter/test/rules/use_decorated_box_test.dart b/pkg/linter/test/rules/use_decorated_box_test.dart index 9c7526887794..85276cb7d427 100644 --- a/pkg/linter/test/rules/use_decorated_box_test.dart +++ b/pkg/linter/test/rules/use_decorated_box_test.dart @@ -48,7 +48,8 @@ Widget f() { } test_containerWithDecorationAndChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { return Container( @@ -56,9 +57,9 @@ Widget f() { child: SizedBox(), ); } -''', [ - lint(61, 9), - ]); +''', + [lint(61, 9)], + ); } test_containerWithDecorationAndChildAndOtherArgument() async { @@ -120,7 +121,8 @@ Widget f() { } test_containerWithKeyAndDecorationAndChild() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; Widget f() { return Container( @@ -129,9 +131,9 @@ Widget f() { child: SizedBox(), ); } -''', [ - lint(61, 9), - ]); +''', + [lint(61, 9)], + ); } test_containerWithoutArguments() async { diff --git a/pkg/linter/test/rules/use_enums_test.dart b/pkg/linter/test/rules/use_enums_test.dart index ffdad21f85dd..d354780f6450 100644 --- a/pkg/linter/test/rules/use_enums_test.dart +++ b/pkg/linter/test/rules/use_enums_test.dart @@ -43,39 +43,42 @@ augment class C { } test_constructor_private() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static const A a = A._(1); static const A b = A._(2); final int value; const A._(this.value); } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_extendsObject() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A extends Object { static const A a = A._(); static const A b = A._(); const A._(); } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_multiDeclaration() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static const A a = A._(), b = A._(); const A._(); } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_no_lint_abstract() async { @@ -126,27 +129,31 @@ class A { } test_no_lint_constructorUsedInConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static const _E a = _E(); static const _E b = _E(); const _E({_E e = const _E()}); } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 29, 1), - error(WarningCode.UNUSED_FIELD, 57, 1), - error(CompileTimeErrorCode.RECURSIVE_CONSTANT_CONSTRUCTOR, 76, 2), - // We are reversing the deprecation: This code will remain a `HintCode`. - // ignore: deprecated_member_use - error(WarningCode.UNUSED_ELEMENT_PARAMETER, 83, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 29, 1), + error(WarningCode.UNUSED_FIELD, 57, 1), + error(CompileTimeErrorCode.RECURSIVE_CONSTANT_CONSTRUCTOR, 76, 2), + // We are reversing the deprecation: This code will remain a `HintCode`. + // ignore: deprecated_member_use + error(WarningCode.UNUSED_ELEMENT_PARAMETER, 83, 1), + ], + ); } test_no_lint_constructorUsedOutsideClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static const _E a = _E(); static const _E b = _E(); @@ -155,11 +162,13 @@ class _E { } _E get e => _E(); -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 29, 1), - error(WarningCode.UNUSED_FIELD, 57, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 29, 1), + error(WarningCode.UNUSED_FIELD, 57, 1), + ], + ); } test_no_lint_extended() async { @@ -189,22 +198,26 @@ class A extends O { } test_no_lint_factoryAll() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static _E c = _E(); static _E d = _E(); factory _E() => c; } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 45, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 45, 1), + ], + ); } test_no_lint_factorySome() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static _E c0 = _E._(); static _E c1 = _E(); @@ -212,15 +225,18 @@ class _E { factory _E() => c0; const _E._(); } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 48, 2), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 48, 2), + ], + ); } test_no_lint_implemented() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class _E { static const _E c = _E(); static const _E d = _E(); @@ -228,11 +244,13 @@ class _E { const _E(); } class F implements _E {} -''', [ - // No lint. - error(WarningCode.UNUSED_FIELD, 29, 1), - error(WarningCode.UNUSED_FIELD, 57, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_FIELD, 29, 1), + error(WarningCode.UNUSED_FIELD, 57, 1), + ], + ); } test_no_lint_implements_index_field() async { @@ -280,36 +298,42 @@ class A { } test_no_lint_nonConstConstructor() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class _E { static final _E a = _E(); static final _E b = _E(); _E(); } -''', [ - // No lint. - // TODO(pq): consider relaxing the lint to flag cases w/o a const - // but all final fields. - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 29, 1), - error(WarningCode.UNUSED_FIELD, 57, 1), - ]); +''', + [ + // No lint. + // TODO(pq): consider relaxing the lint to flag cases w/o a const + // but all final fields. + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 29, 1), + error(WarningCode.UNUSED_FIELD, 57, 1), + ], + ); } test_no_lint_nonInstanceCreationInitialization() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static const _E a = _E(); static const _E b = a; const _E(); } -''', [ - // No lint. - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 57, 1), - ]); +''', + [ + // No lint. + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 57, 1), + ], + ); } test_no_lint_overrides_equals() async { @@ -337,7 +361,8 @@ class A { } test_referencedFactoryConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _E { static const _E c = _E(); static const _E d = _E(); @@ -348,65 +373,70 @@ class _E { } _E e = _E.withValue(0); -''', [ - lint(6, 2), - error(WarningCode.UNUSED_FIELD, 57, 1), - ]); +''', + [lint(6, 2), error(WarningCode.UNUSED_FIELD, 57, 1)], + ); } test_simple_hasPart() async { newFile('$testPackageLibPath/a.dart', ''' part of 'test.dart'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part 'a.dart'; class A { static const A a = A._(); static const A b = A._(); const A._(); } -''', [ - lint(21, 1), - ]); +''', + [lint(21, 1)], + ); } test_simple_private() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class _A { static const _A a = _A(); static const _A b = _A(); const _A(); } -''', [ - error(WarningCode.UNUSED_ELEMENT, 6, 2), - error(WarningCode.UNUSED_FIELD, 29, 1), - error(WarningCode.UNUSED_FIELD, 57, 1), - lint(6, 2), - ]); +''', + [ + error(WarningCode.UNUSED_ELEMENT, 6, 2), + error(WarningCode.UNUSED_FIELD, 29, 1), + error(WarningCode.UNUSED_FIELD, 57, 1), + lint(6, 2), + ], + ); } test_simple_public() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { static const A a = A._(); static const A b = A._(); const A._(); } -''', [ - lint(6, 1), - ]); +''', + [lint(6, 1)], + ); } test_withMixin() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' mixin class M { } class A with M { static const A a = A._(); static const A b = A._(); const A._(); } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } } diff --git a/pkg/linter/test/rules/use_full_hex_values_for_flutter_colors_test.dart b/pkg/linter/test/rules/use_full_hex_values_for_flutter_colors_test.dart index e82ada02017b..5ea2fc6c4b56 100644 --- a/pkg/linter/test/rules/use_full_hex_values_for_flutter_colors_test.dart +++ b/pkg/linter/test/rules/use_full_hex_values_for_flutter_colors_test.dart @@ -18,7 +18,8 @@ class UseFullHexValuesForFlutterColorsTest extends LintRuleTest { String get lintRule => LintNames.use_full_hex_values_for_flutter_colors; test_decimal() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library dart.ui; var c = Color(1); @@ -26,9 +27,9 @@ var c = Color(1); class Color { Color(int v); } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_dynamicArgument() async { @@ -69,7 +70,8 @@ class Color { } test_sixDigitHex_lower() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library dart.ui; var c = Color(0x000000); @@ -77,13 +79,14 @@ var c = Color(0x000000); class Color { Color(int v); } -''', [ - lint(32, 8), - ]); +''', + [lint(32, 8)], + ); } test_sixDigitHex_upper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library dart.ui; var c = Color(0X000000); @@ -91,13 +94,14 @@ var c = Color(0X000000); class Color { Color(int v); } -''', [ - lint(32, 8), - ]); +''', + [lint(32, 8)], + ); } test_sixDigitHex_withSeparators() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' library dart.ui; var c = Color(0x00_00_00); @@ -105,8 +109,8 @@ var c = Color(0x00_00_00); class Color { Color(int v); } -''', [ - lint(32, 10), - ]); +''', + [lint(32, 10)], + ); } } diff --git a/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart b/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart index 92e18c7a996a..442c19fc4963 100644 --- a/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart +++ b/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart @@ -18,11 +18,12 @@ class UseFunctionTypeSyntaxForParametersTest extends LintRuleTest { String get lintRule => LintNames.use_function_type_syntax_for_parameters; test_classicSyntax() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f1(bool f(int e)) {} -''', [ - lint(8, 13), - ]); +''', + [lint(8, 13)], + ); } test_functionTypeSyntax() async { diff --git a/pkg/linter/test/rules/use_if_null_to_convert_nulls_to_bools_test.dart b/pkg/linter/test/rules/use_if_null_to_convert_nulls_to_bools_test.dart index f26d357cde7f..e8638f73b9a9 100644 --- a/pkg/linter/test/rules/use_if_null_to_convert_nulls_to_bools_test.dart +++ b/pkg/linter/test/rules/use_if_null_to_convert_nulls_to_bools_test.dart @@ -25,21 +25,23 @@ bool r = e == false; } test_equalEqual_true() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool? e; bool r = e == true; -''', [ - lint(18, 9), - ]); +''', + [lint(18, 9)], + ); } test_notEqual_false() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' bool? e; bool r = e != false; -''', [ - lint(18, 10), - ]); +''', + [lint(18, 10)], + ); } test_notEqual_true() async { diff --git a/pkg/linter/test/rules/use_is_even_rather_than_modulo_test.dart b/pkg/linter/test/rules/use_is_even_rather_than_modulo_test.dart index bf4fa15cc098..fca2101b4b46 100644 --- a/pkg/linter/test/rules/use_is_even_rather_than_modulo_test.dart +++ b/pkg/linter/test/rules/use_is_even_rather_than_modulo_test.dart @@ -52,20 +52,22 @@ const b = a % 2 == 0; } test_moduloTwoEqualEqualOne_intTypedExpression() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = 3; var b = a % 2 == 0; -''', [ - lint(19, 10), - ]); +''', + [lint(19, 10)], + ); } test_moduloTwoEqualEqualOne_literalInt() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = 13 % 2 == 1; -''', [ - lint(8, 11), - ]); +''', + [lint(8, 11)], + ); } test_moduloTwoEqualEqualThree() async { @@ -75,11 +77,12 @@ var a = 1 % 2 == 3 - 3; } test_moduloTwoEqualEqualZero_literalInt() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var a = 1 % 2 == 0; -''', [ - lint(8, 10), - ]); +''', + [lint(8, 10)], + ); } test_moduloTwoGreaterOrEqualZero_literalInt() async { @@ -103,12 +106,15 @@ var b = a + 2 == 0; } test_undefinedClass() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' Class tmp; bool a = tmp % 2 == 0; -''', [ - // No lint - error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 5), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.UNDEFINED_CLASS, 0, 5), + ], + ); } } diff --git a/pkg/linter/test/rules/use_key_in_widget_constructors_test.dart b/pkg/linter/test/rules/use_key_in_widget_constructors_test.dart index 712162f8e3e9..9bf56d09f52a 100644 --- a/pkg/linter/test/rules/use_key_in_widget_constructors_test.dart +++ b/pkg/linter/test/rules/use_key_in_widget_constructors_test.dart @@ -43,15 +43,16 @@ augment class W { } test_constNamedConstructor_missingKey() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class MyWidget extends StatelessWidget { const MyWidget.named(); } -''', [ - lint(107, 5), - ]); +''', + [lint(107, 5)], + ); } test_constructorInAugmentedClass() async { @@ -65,7 +66,8 @@ class W extends StatelessWidget { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; import 'package:flutter/widgets.dart'; @@ -75,9 +77,9 @@ augment class W { } augment class W { const W({Key? key}); } -''', [ - lint(106, 1), - ]); +''', + [lint(106, 1)], + ); } test_constructorInAugmentedClass_noKeyParam() async { @@ -91,27 +93,29 @@ class W extends StatelessWidget { } '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of 'a.dart'; augment class W { const W(); } -''', [ - lint(45, 1), - ]); +''', + [lint(45, 1)], + ); } test_constUnnamedConstructor_missingKey() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class MyWidget extends StatelessWidget { const MyWidget(); } -''', [ - lint(98, 8), - ]); +''', + [lint(98, 8)], + ); } test_factoryConstructor() async { @@ -169,25 +173,27 @@ class W extends StatelessWidget { } test_missingConstructor() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class NoConstructorWidget extends StatefulWidget {} -''', [ - lint(55, 19), - ]); +''', + [lint(55, 19)], + ); } test_missingKey() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class MyWidget extends StatelessWidget { MyWidget(); } -''', [ - lint(92, 8), - ]); +''', + [lint(92, 8)], + ); } test_missingKey_keyPassedToSuper() async { @@ -231,15 +237,16 @@ abstract class MyWidget extends StatelessWidget { } test_simpleFormalParameter_notPassedToSuper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:flutter/widgets.dart'; abstract class MyWidget extends StatelessWidget { MyWidget.withKey({Key? key}); } -''', [ - lint(101, 7), - ]); +''', + [lint(101, 7)], + ); } test_simpleFormalParameter_passedToSuper() async { diff --git a/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart b/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart index fe585bb01180..b0f7850022c3 100644 --- a/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart +++ b/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart @@ -17,59 +17,69 @@ main() { class UseLateForPrivateFieldsAndVariablesTest extends LintRuleTest { @override List get ignoredErrorCodes => [ - WarningCode.UNUSED_ELEMENT, - WarningCode.UNUSED_FIELD, - WarningCode.UNUSED_LOCAL_VARIABLE, - ]; + WarningCode.UNUSED_ELEMENT, + WarningCode.UNUSED_FIELD, + WarningCode.UNUSED_LOCAL_VARIABLE, + ]; @override String get lintRule => LintNames.use_late_for_private_fields_and_variables; test_extensionType_instanceField() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' extension type E(int i) { int? _i; } -''', [ - // No lint. - error(CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, 33, 2), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.EXTENSION_TYPE_DECLARES_INSTANCE_FIELD, + 33, + 2, + ), + ], + ); } test_extensionType_staticField() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' extension type E(int i) { static int? _i; } -''', [ - lint(40, 2), - ]); +''', + [lint(40, 2)], + ); } test_instanceField_private() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class C { int? _i; } -''', [ - lint(17, 2), - ]); +''', + [lint(17, 2)], + ); } test_instanceField_private_declaredInPart() async { newFile('$testPackageLibPath/lib.dart', r''' part 'test.dart'; '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' part of 'lib.dart'; class C { final String? _s; C(this._s); } -''', [ - lint(47, 2), - ]); +''', + [lint(47, 2)], + ); } /// https://github.com/dart-lang/linter/issues/3823 @@ -106,7 +116,8 @@ class C { /// https://github.com/dart-lang/linter/issues/4180 test_patternAssignment_field() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class C { int? _i; void m() { @@ -114,46 +125,61 @@ class C { (_i, ) = (null, ); } } -''', [ - // No lint. - error(CompileTimeErrorCode.PATTERN_ASSIGNMENT_NOT_LOCAL_VARIABLE, 54, 2), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.PATTERN_ASSIGNMENT_NOT_LOCAL_VARIABLE, + 54, + 2, + ), + ], + ); } /// https://github.com/dart-lang/linter/issues/4180 test_patternAssignment_topLevel() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' int? _i; m() { _i?.abs(); (_i, ) = (null, ); } -''', [ - // No lint. - error(CompileTimeErrorCode.PATTERN_ASSIGNMENT_NOT_LOCAL_VARIABLE, 31, 2), - ]); +''', + [ + // No lint. + error( + CompileTimeErrorCode.PATTERN_ASSIGNMENT_NOT_LOCAL_VARIABLE, + 31, + 2, + ), + ], + ); } test_staticField_private_onExtension() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' extension E on int { static int? _i; } -''', [ - lint(35, 2), - ]); +''', + [lint(35, 2)], + ); } // TODO(srawlins): Add test_staticField_private_onClass. test_staticField_public_onPrivateExtension() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' extension _E on int { static int? i; } -''', [ - lint(36, 1), - ]); +''', + [lint(36, 1)], + ); } test_staticField_public_onPublicExtension() async { @@ -165,24 +191,26 @@ extension E on int { } test_staticField_public_onUnnamedExtension() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' extension on int { static int? i; } -''', [ - lint(33, 1), - ]); +''', + [lint(33, 1)], + ); } test_topLevel_assigned() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' int? _i; void f() { _i = 1; } -''', [ - lint(5, 2), - ]); +''', + [lint(5, 2)], + ); } test_topLevel_declaredInPart() async { @@ -193,21 +221,23 @@ void f() { _i = 1; } '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' part of 'lib.dart'; int? _i; -''', [ - lint(26, 2), - ]); +''', + [lint(26, 2)], + ); } test_topLevel_neverUsed() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' int? _i; -''', [ - lint(5, 2), - ]); +''', + [lint(5, 2)], + ); } test_topLevel_onlyAssignedNull() async { @@ -238,25 +268,27 @@ f() { } test_topLevel_onlyNullChecked() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' int? _i; f() { _i!.abs(); } -''', [ - lint(5, 2), - ]); +''', + [lint(5, 2)], + ); } test_topLevel_onlyNullChecked_beforePassedAsArgument() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' int? _i; f(int i) { f(_i!); } -''', [ - lint(5, 2), - ]); +''', + [lint(5, 2)], + ); } test_topLevel_onlyNullTest() async { @@ -294,12 +326,13 @@ void f() { _i = 1; } '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' part 'part.dart'; int? _i; -''', [ - lint(24, 2), - ]); +''', + [lint(24, 2)], + ); } } diff --git a/pkg/linter/test/rules/use_named_constants_test.dart b/pkg/linter/test/rules/use_named_constants_test.dart index 7fe69c64530d..3f6fa3f733b0 100644 --- a/pkg/linter/test/rules/use_named_constants_test.dart +++ b/pkg/linter/test/rules/use_named_constants_test.dart @@ -19,7 +19,8 @@ class UseNamedConstantsTest extends LintRuleTest { /// https://github.com/dart-lang/linter/issues/4201 test_constantPattern_ifCase() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(this.value); final int value; @@ -30,14 +31,15 @@ class A { void f(A a) { if (a case const A(0)) {} } -''', [ - lint(117, 4), - ]); +''', + [lint(117, 4)], + ); } /// https://github.com/dart-lang/linter/issues/4201 test_constantPattern_switch() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A(this.value); final int value; @@ -51,9 +53,9 @@ void f(A a) { case const A(1): } } -''', [ - lint(155, 4), - ]); +''', + [lint(155, 4)], + ); } test_duplicate_inDefinition() async { @@ -67,7 +69,8 @@ class A { } test_reconstructed_sameAsPrivateName() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { const A(1); } @@ -76,13 +79,14 @@ class A { // ignore: unused_field static const _zero = A(0); } -''', [ - lint(13, 10), - ]); +''', + [lint(13, 10)], + ); } test_reconstructed_sameAsPublicName_explicitConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { const A(0); } @@ -90,13 +94,14 @@ class A { const A(int value); static const zero = A(0); } -''', [ - lint(13, 10), - ]); +''', + [lint(13, 10)], + ); } test_reconstructed_sameAsPublicName_implicitConst() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { const a = A(0); } @@ -104,9 +109,9 @@ class A { const A(int value); static const zero = A(0); } -''', [ - lint(23, 4), - ]); +''', + [lint(23, 4)], + ); } test_usesNamed() async { diff --git a/pkg/linter/test/rules/use_raw_strings_test.dart b/pkg/linter/test/rules/use_raw_strings_test.dart index 1433d91985e8..456baef896db 100644 --- a/pkg/linter/test/rules/use_raw_strings_test.dart +++ b/pkg/linter/test/rules/use_raw_strings_test.dart @@ -18,27 +18,30 @@ class UseRawStringsTest extends LintRuleTest { String get lintRule => LintNames.use_raw_strings; test_escapedBackslash() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = '\\'; -''', [ - lint(8, 4), - ]); +''', + [lint(8, 4)], + ); } test_escapedDollar() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = '\$'; -''', [ - lint(8, 4), - ]); +''', + [lint(8, 4)], + ); } test_escapedMultiple() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var f = '\$ and \\'; -''', [ - lint(8, 11), - ]); +''', + [lint(8, 11)], + ); } test_escapedMultiple_withInterpolation() async { @@ -86,27 +89,30 @@ var f = r'\$ and \\ and \n'; } test_triple_escapedBackslash() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var f = '''\\'''; -""", [ - lint(8, 8), - ]); +""", + [lint(8, 8)], + ); } test_triple_escapedDollar() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var f = '''\$'''; -""", [ - lint(8, 8), - ]); +""", + [lint(8, 8)], + ); } test_triple_escapedMultiple() async { - await assertDiagnostics(r""" + await assertDiagnostics( + r""" var f = '''\$ and \\'''; -""", [ - lint(8, 15), - ]); +""", + [lint(8, 15)], + ); } test_triple_escapedMultiple_andInterpolation() async { diff --git a/pkg/linter/test/rules/use_rethrow_when_possible_test.dart b/pkg/linter/test/rules/use_rethrow_when_possible_test.dart index 508ecaef2c47..0459d058ec60 100644 --- a/pkg/linter/test/rules/use_rethrow_when_possible_test.dart +++ b/pkg/linter/test/rules/use_rethrow_when_possible_test.dart @@ -18,28 +18,30 @@ class UseRethrowWhenPossibleTest extends LintRuleTest { String get lintRule => LintNames.use_rethrow_when_possible; test_catchError_throwSameError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e) { throw e; } } -''', [ - lint(36, 7), - ]); +''', + [lint(36, 7)], + ); } test_catchErrorAndStackTrace_throwSameError() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { try {} catch (e, stackTrace) { print(stackTrace); throw e; } } -''', [ - lint(71, 7), - ]); +''', + [lint(71, 7)], + ); } test_rethrow() async { diff --git a/pkg/linter/test/rules/use_setters_to_change_properties_test.dart b/pkg/linter/test/rules/use_setters_to_change_properties_test.dart index 0eaecf2f8871..80236adc65cb 100644 --- a/pkg/linter/test/rules/use_setters_to_change_properties_test.dart +++ b/pkg/linter/test/rules/use_setters_to_change_properties_test.dart @@ -37,7 +37,8 @@ abstract class A { } test_extension() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { int x = 0; } @@ -47,9 +48,9 @@ extension E on A { this.x = x; } } -''', [ - lint(52, 4), - ]); +''', + [lint(52, 4)], + ); } test_inheritedFromSuperclass() async { @@ -85,26 +86,28 @@ class B implements A { } test_setterLike_blockBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { int x = 0; void setX(int x) { this.x = x; } } -''', [ - lint(39, 4), - ]); +''', + [lint(39, 4)], + ); } test_setterLike_expressionBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' abstract class A { int x = 0; void setX(int x) => this.x = x; } -''', [ - lint(39, 4), - ]); +''', + [lint(39, 4)], + ); } } diff --git a/pkg/linter/test/rules/use_string_buffers_test.dart b/pkg/linter/test/rules/use_string_buffers_test.dart index 90cd4e3a1ab0..096d097daa36 100644 --- a/pkg/linter/test/rules/use_string_buffers_test.dart +++ b/pkg/linter/test/rules/use_string_buffers_test.dart @@ -60,7 +60,8 @@ class A { } test_field_plusEquals_nonStringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String buffer = ''; @@ -71,13 +72,14 @@ class A { } } } -''', [ - lint(100, 26), - ]); +''', + [lint(100, 26)], + ); } test_field_plusEquals_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { String buffer = ''; @@ -88,35 +90,37 @@ class A { } } } -''', [ - lint(100, 13), - ]); +''', + [lint(100, 13)], + ); } test_localVariable_assignment_interpolatedStringLiteralAsPrefix() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (int i = 0; i < 10; i++) { buffer = '${buffer}a'; } } -''', [ - lint(69, 6), - ]); +''', + [lint(69, 6)], + ); } test_localVariable_assignment_interpolatedStringLiteralAsPrefixWithPlus() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (int i = 0; i < 10; i++) { buffer = '${buffer + 'a'}a'; } } -''', [ - lint(69, 6), - ]); +''', + [lint(69, 6)], + ); } test_localVariable_assignment_interpolatedStringLiteralNotAsPrefix() async { @@ -131,81 +135,87 @@ void foo() { } test_localVariable_doLoop_plusEquals_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; do { buffer += 'a'; } while (buffer.length < 10); } -''', [ - lint(43, 13), - ]); +''', + [lint(43, 13)], + ); } test_localVariable_plus_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (int i = 0; i < 10; i++) { buffer = buffer + 'a'; } } -''', [ - lint(69, 6), - ]); +''', + [lint(69, 6)], + ); } test_localVariable_plusEquals_nonStringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (final s in ['a']) { buffer += s; } } -''', [ - lint(63, 11), - ]); +''', + [lint(63, 11)], + ); } test_localVariable_plusEquals_nonStringLiteral_parenthesized() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (final s in ['a']) { (buffer += s); } } -''', [ - lint(64, 11), - ]); +''', + [lint(64, 11)], + ); } test_localVariable_plusEquals_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; for (int i = 0; i < 10; i++) { buffer += 'a'; } } -''', [ - lint(69, 13), - ]); +''', + [lint(69, 13)], + ); } test_localVariable_whileLoop_plusEquals_stringLiteral() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void foo() { var buffer = ''; while (buffer.length < 10) { buffer += 'a'; } } -''', [ - lint(67, 13), - ]); +''', + [lint(67, 13)], + ); } test_loopVariable_plusEquals_nonStringLiteral() async { diff --git a/pkg/linter/test/rules/use_string_in_part_of_directives_test.dart b/pkg/linter/test/rules/use_string_in_part_of_directives_test.dart index 7526c2fafd55..929620f5faf5 100644 --- a/pkg/linter/test/rules/use_string_in_part_of_directives_test.dart +++ b/pkg/linter/test/rules/use_string_in_part_of_directives_test.dart @@ -25,11 +25,12 @@ class UseStringInPartOfDirectivesTest extends LintRuleTest { library lib; part '$testFileName'; '''); - await assertDiagnostics(r''' + await assertDiagnostics( + r''' part of lib; -''', [ - error(ParserErrorCode.PART_OF_NAME, 8, 3), - ]); +''', + [error(ParserErrorCode.PART_OF_NAME, 8, 3)], + ); } test_part_of_with_library_name_preEnhancedParts() async { @@ -47,9 +48,7 @@ part '$testFileName'; part of lib; ''', - [ - lint(40, 12), - ], + [lint(40, 12)], ); } diff --git a/pkg/linter/test/rules/use_super_parameters_test.dart b/pkg/linter/test/rules/use_super_parameters_test.dart index e25ca98bc749..42655cd40485 100644 --- a/pkg/linter/test/rules/use_super_parameters_test.dart +++ b/pkg/linter/test/rules/use_super_parameters_test.dart @@ -18,46 +18,50 @@ class UseSuperParametersTest extends LintRuleTest { String get lintRule => LintNames.use_super_parameters; test_functionTypedFormalParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int f(int i)); } class B extends A { B(int f(int i)) : super(f); } -''', [ - lint(53, 1), - ]); +''', + [lint(53, 1)], + ); } test_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { const A({int? x, int? y}); } class B extends A { const B({int? x, int? y}) : super(x: x, y: y); } -''', [ - lint(69, 1), - ]); +''', + [lint(69, 1)], + ); } Future test_named_oneWithNameChange() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class A { A({int? x, int? y}); } class B extends A { B({int? x, int? z}) : super(x: x, y: z); } -''', [ - lint(57, 1), - ]); +''', + [lint(57, 1)], + ); } test_named_someReferencedInBody() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A({int? x, int? y}); } @@ -66,13 +70,20 @@ class B extends A { print(x); } } -''', [ - lint(57, 1, messageContains: "Parameter 'y' could be a super parameter."), - ]); +''', + [ + lint( + 57, + 1, + messageContains: "Parameter 'y' could be a super parameter.", + ), + ], + ); } test_named_thisParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A({int? x, int? y}); } @@ -80,9 +91,15 @@ class B extends A { int? x; B({this.x, int? y}) : super(x:x, y:y); } -''', [ - lint(67, 1, messageContains: "Parameter 'y' could be a super parameter."), - ]); +''', + [ + lint( + 67, + 1, + messageContains: "Parameter 'y' could be a super parameter.", + ), + ], + ); } test_no_lint_forwardedOutOfOrder() async { @@ -324,42 +341,45 @@ class B extends A { } test_nonForwardingNamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int x, {int? foo}); } class B extends A { B(int x, {int? foo}) : super(x, foo: 0); } -''', [ - lint(58, 1), - ]); +''', + [lint(58, 1)], + ); } test_optionalPositional_inSuper() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int x, [int? y]); } class B extends A { B(int x) : super(x); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_optionalPositional_singleSuperParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int x); } class B extends A { B([int x = 0]) : super(x); } -''', [ - lint(46, 1), - ]); +''', + [lint(46, 1)], + ); } /// https://github.com/dart-lang/linter/issues/3569 @@ -379,7 +399,8 @@ class Square extends Rect { } test_requiredPositional_allConvertible() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { final int foo; final int bar; @@ -388,26 +409,28 @@ class B { class C extends B { C(int foo, int bar) : super(foo, bar); } -''', [ - lint(93, 1), - ]); +''', + [lint(93, 1)], + ); } test_requiredPositional_mixedSuperParameters() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int x, {int? y}); } class B extends A { B(int x, int y) : super(x, y: y); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } test_requiredPositional_someConvertible() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { final int foo; final int bar; @@ -416,21 +439,22 @@ class B { class C extends B { C(int baz, int foo, int bar) : super(foo, bar); } -''', [ - lint(93, 1), - ]); +''', + [lint(93, 1)], + ); } test_requiredPositional_withNamed() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class A { A(int x, {int? y}); } class B extends A { B(int x, {int? y}) : super(x, y: y); } -''', [ - lint(56, 1), - ]); +''', + [lint(56, 1)], + ); } } diff --git a/pkg/linter/test/rules/use_test_throws_matchers_test.dart b/pkg/linter/test/rules/use_test_throws_matchers_test.dart index 761efb95c30e..84ed914baccb 100644 --- a/pkg/linter/test/rules/use_test_throws_matchers_test.dart +++ b/pkg/linter/test/rules/use_test_throws_matchers_test.dart @@ -22,10 +22,7 @@ class UseTestThrowsMatchersTest extends LintRuleTest { super.setUp(); var testApiPath = '$workspaceRootPath/test_api'; var packageConfigBuilder = PackageConfigFileBuilder(); - packageConfigBuilder.add( - name: 'test_api', - rootPath: testApiPath, - ); + packageConfigBuilder.add(name: 'test_api', rootPath: testApiPath); writeTestPackageConfig(packageConfigBuilder); newFile('$testApiPath/lib/src/frontend/expect.dart', r''' void expect(dynamic actual, dynamic matcher) {} @@ -38,7 +35,8 @@ export 'src/frontend/expect.dart'; } test_failInTry() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'package:test_api/test_api.dart'; void f() { @@ -47,9 +45,9 @@ void f() { fail('fail'); } catch (e) {} } -''', [ - lint(74, 13), - ]); +''', + [lint(74, 13)], + ); } test_failWithExpectInCatch() async { diff --git a/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart b/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart index 95c36b1ae857..062791bb30dd 100644 --- a/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart +++ b/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart @@ -46,7 +46,8 @@ class A { } test_asx_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { A asa() { return A.from(this); @@ -56,9 +57,9 @@ class B { class A { A.from(B _); } -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } test_asX_private_argumentIsThis() async { @@ -77,7 +78,8 @@ class A { } test_asx_private_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { // ignore: unused_element A _asa() { @@ -88,9 +90,9 @@ class B { class A { A.from(B _); } -''', [ - lint(42, 4), - ]); +''', + [lint(42, 4)], + ); } test_getX_argumentIsOther_extends() async { @@ -142,7 +144,8 @@ class B {} } test_namedOtherwise_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { A foo() { return A.from(this); @@ -152,13 +155,14 @@ class B { class A { A.from(B _); } -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } test_namedOtherwise_private_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { // ignore: unused_element A _foo() { @@ -169,9 +173,9 @@ class B { class A { A.from(B _); } -''', [ - lint(42, 4), - ]); +''', + [lint(42, 4)], + ); } test_namedOtherwise_private_hasParameters_argumentIsThis() async { @@ -218,7 +222,8 @@ class A { } test_tox_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { A toa() { return A.from(this); @@ -228,9 +233,9 @@ class B { class A { A.from(B _); } -''', [ - lint(14, 3), - ]); +''', + [lint(14, 3)], + ); } test_toX_private_argumentIsThis() async { @@ -249,7 +254,8 @@ class A { } test_tox_private_argumentIsThis() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' class B { // ignore: unused_element A _toa() { @@ -260,8 +266,8 @@ class B { class A { A.from(B _); } -''', [ - lint(42, 4), - ]); +''', + [lint(42, 4)], + ); } } diff --git a/pkg/linter/test/rules/use_truncating_division_test.dart b/pkg/linter/test/rules/use_truncating_division_test.dart index b2ddbd8004af..ecd6340ec94b 100644 --- a/pkg/linter/test/rules/use_truncating_division_test.dart +++ b/pkg/linter/test/rules/use_truncating_division_test.dart @@ -26,33 +26,36 @@ void f(double x, double y) { } test_int_divide_truncate() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x, int y) { (x / y).toInt(); } -''', [ - lint(25, 15), - ]); +''', + [lint(25, 15)], + ); } test_int_divide_truncate_moreParensAroundDivision() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x, int y) { (((x / y))).toInt(); } -''', [ - lint(25, 19), - ]); +''', + [lint(25, 19)], + ); } test_int_divide_truncate_moreParensAroundOperands() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(int x, int y) { ((x + 1) / (y - 1)).toInt(); } -''', [ - lint(25, 27), - ]); +''', + [lint(25, 27)], + ); } test_intExtensionType_divide_truncate() async { diff --git a/pkg/linter/test/rules/valid_regexps_test.dart b/pkg/linter/test/rules/valid_regexps_test.dart index f36926754844..1cf6e5f229a4 100644 --- a/pkg/linter/test/rules/valid_regexps_test.dart +++ b/pkg/linter/test/rules/valid_regexps_test.dart @@ -34,11 +34,12 @@ var s = RegExp('( $r'); } test_invalid() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' var s = RegExp('('); -''', [ - lint(15, 3), - ]); +''', + [lint(15, 3)], + ); } test_valid() async { diff --git a/pkg/linter/test/rules/void_checks_test.dart b/pkg/linter/test/rules/void_checks_test.dart index 5485e8c58f1b..a52813033e85 100644 --- a/pkg/linter/test/rules/void_checks_test.dart +++ b/pkg/linter/test/rules/void_checks_test.dart @@ -28,7 +28,8 @@ void f() { } test_constructorArgument_genericParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { A.c(p); } @@ -36,9 +37,9 @@ class A { T value; A.c(this.value); } -''', [ - lint(32, 1), - ]); +''', + [lint(32, 1)], + ); } test_emptyFunctionExpressionReturningFutureOrVoid() async { @@ -52,15 +53,18 @@ void emptyFunctionExpressionReturningFutureOrVoid(FutureOr Function() f) { } test_extraPositionalArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' missing_parameter_for_argument() { void foo() {} foo(0); } -''', [ - // No lint - error(CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS, 57, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS, 57, 1), + ], + ); } test_functionArgument_FutureOrVoidParameter_dynamicArgument() async { @@ -104,36 +108,39 @@ void m(FutureOr arg) {} } test_functionArgument_voidParameter_dynamicArgument() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { m(p); } void m(void arg) {} -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_functionArgument_voidParameter_named() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { m(p: p); } void m({required void p}) {} -''', [ - lint(27, 1), - ]); +''', + [lint(27, 1)], + ); } test_functionArgument_voidParameter_optional() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { m(p); } void m([void v]) {} -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_functionExpression_blockBody_returnStatement_genericContext() async { @@ -240,7 +247,8 @@ class A { } test_futureOrVoidField_assignInt() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; void f(A a) { a.x = 1; @@ -249,9 +257,9 @@ class A { FutureOr x; A(this.x); } -''', [ - lint(37, 7), - ]); +''', + [lint(37, 7)], + ); } test_futureOrVoidField_assignNull() async { @@ -277,36 +285,39 @@ FutureOr f() { } test_futureOrVoidFunction_blockBody_returnStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' import 'dart:async'; FutureOr f() { return 1; } -''', [ - lint(44, 9), - ]); +''', + [lint(44, 9)], + ); } test_listPattern_local() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f() { void p; [p] = [7]; return p; } -''', [ - lint(24, 1), - ]); +''', + [lint(24, 1)], + ); } test_listPattern_param() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(void p) { [p] = [7]; } -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_localFunction_emptyBlockBody_matchingFutureOrVoidSignature() async { @@ -342,24 +353,28 @@ void f(void Function() p) { } test_recordPattern() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(void p) { (p, ) = (7, ); } -''', [ - lint(20, 1), - ]); +''', + [lint(20, 1)], + ); } test_returnOfInvalidType() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void bug2813() { return 1; } -''', [ - // No lint - error(CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_FUNCTION, 26, 1), - ]); +''', + [ + // No lint + error(CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_FUNCTION, 26, 1), + ], + ); } // https://github.com/dart-lang/linter/issues/2685 @@ -386,26 +401,28 @@ void f(Future p) { } test_setterArgument_genericParameter() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(A a, dynamic p) { a.f = p; } class A { set f(T value) {} } -''', [ - lint(33, 7), - ]); +''', + [lint(33, 7)], + ); } test_voidFunction_blockBody_returnStatement() async { - await assertDiagnostics(r''' + await assertDiagnostics( + r''' void f(dynamic p) { return p; } -''', [ - lint(22, 9), - ]); +''', + [lint(22, 9)], + ); } test_voidFunction_blockBody_returnStatement_empty() async { diff --git a/pkg/linter/test/scope_util_test.dart b/pkg/linter/test/scope_util_test.dart index 7a0fb2c65621..9bc84f299922 100644 --- a/pkg/linter/test/scope_util_test.dart +++ b/pkg/linter/test/scope_util_test.dart @@ -58,7 +58,8 @@ class B extends A { newFile('$testPackageLibPath/a.dart', r''' set foo(int _) {} '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'a.dart'; class A { @@ -70,9 +71,9 @@ class B extends A { this.foo; } } -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 8), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 8)], + ); var import = findElement.importFind('package:test/a.dart'); _checkGetterDifferent(import.topSet('foo')); } @@ -89,9 +90,7 @@ class B extends A { } } '''); - _checkGetterRequested( - findElement.parameter('foo'), - ); + _checkGetterRequested(findElement.parameter('foo')); } test_class_getter_fromExtends_expressionBody() async { @@ -104,9 +103,7 @@ class B extends A { void bar(int foo) => this.foo; } '''); - _checkGetterRequested( - findElement.parameter('foo'), - ); + _checkGetterRequested(findElement.parameter('foo')); } test_class_getter_none_fromExtends() async { @@ -128,7 +125,8 @@ class B extends A { newFile('$testPackageLibPath/a.dart', r''' int get foo => 0; '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'a.dart'; class A { @@ -140,9 +138,9 @@ class B extends A { this.foo; } } -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 8), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 8)], + ); var import = findElement.importFind('package:test/a.dart'); _checkGetterRequested(import.topGet('foo')); } @@ -288,7 +286,8 @@ var foo = 0; newFile('$testPackageLibPath/a.dart', r''' void foo() {} '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'a.dart'; class A { @@ -300,9 +299,9 @@ class B extends A { this.foo(); } } -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 8), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 8)], + ); var import = findElement.importFind('package:test/a.dart'); _checkMethodRequested(import.topFunction('foo')); } @@ -595,7 +594,8 @@ var foo = 0; newFile('$testPackageLibPath/a.dart', r''' set foo(int _) {} '''); - await assertDiagnostics(''' + await assertDiagnostics( + ''' import 'a.dart'; class A { @@ -607,9 +607,9 @@ class B extends A { this.foo = 0; } } -''', [ - error(WarningCode.UNUSED_IMPORT, 7, 8), - ]); +''', + [error(WarningCode.UNUSED_IMPORT, 7, 8)], + ); var import = findElement.importFind('package:test/a.dart'); _checkSetterRequested(import.topSet('foo')); } @@ -683,7 +683,8 @@ class A { } test_extension_method_none_fromExtended() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class A { void foo() {} } @@ -693,14 +694,15 @@ extension on A { this.foo(); } } -''', [ - error(WarningCode.UNUSED_ELEMENT, 53, 3), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 53, 3)], + ); _checkMethodNone(); } test_extension_method_requested_formalParameter_method() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class A {} extension on A { @@ -710,14 +712,15 @@ extension on A { this.foo(); } } -''', [ - error(WarningCode.UNUSED_ELEMENT, 53, 3), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 53, 3)], + ); _checkMethodRequested(findElement.parameter('foo')); } test_extension_method_requested_fromExtended_topLevelVariable() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class A { void foo() {} } @@ -729,14 +732,15 @@ extension on A { } var foo = 0; -''', [ - error(WarningCode.UNUSED_ELEMENT, 53, 3), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 53, 3)], + ); _checkMethodRequested(findElement.topGet('foo')); } test_extension_method_requested_fromThisExtension() async { - await assertDiagnostics(''' + await assertDiagnostics( + ''' class A {} extension on A { @@ -746,9 +750,9 @@ extension on A { this.foo(); } } -''', [ - error(WarningCode.UNUSED_ELEMENT, 53, 3), - ]); +''', + [error(WarningCode.UNUSED_ELEMENT, 53, 3)], + ); _checkMethodRequested(findElement.method('foo')); } @@ -883,7 +887,11 @@ mixin A { } void _resultDifferent( - AstNode node, String id, bool setter, Element2 element) { + AstNode node, + String id, + bool setter, + Element2 element, + ) { var result = resolveNameInScope(id, node, shouldResolveSetter: setter); if (!result.isDifferentName || result.element != element) { fail('Expected different $element, actual: $result'); @@ -898,7 +906,11 @@ mixin A { } void _resultRequested( - AstNode node, String id, bool setter, Element2 element) { + AstNode node, + String id, + bool setter, + Element2 element, + ) { var result = resolveNameInScope(id, node, shouldResolveSetter: setter); if (!result.isRequestedName || result.element != element) { fail('Expected requested $element, actual: $result'); diff --git a/pkg/linter/test/utils_test.dart b/pkg/linter/test/utils_test.dart index a93aa33a68ed..37509cf5bad5 100644 --- a/pkg/linter/test/utils_test.dart +++ b/pkg/linter/test/utils_test.dart @@ -10,31 +10,34 @@ import 'util/test_utils.dart'; void main() { group('isDartFileName', () { testEach(['foo.dart'], isDartFileName, isTrue); - testEach([ - 'foo.d', 'foo', - // Analysis server cares about case. - 'baz.DART', - ], isDartFileName, isFalse); + testEach( + [ + 'foo.d', 'foo', + // Analysis server cares about case. + 'baz.DART', + ], + isDartFileName, + isFalse, + ); }); group('isValidPackageName', () { - testEach([ - 'foo', - '_foo', - '__foo', - 'async', - ], isValidPackageName, isTrue); - testEach([ - 'break', // reserved word - 'fOO', - 'foo_', - 'foo_Bar', - 'fooBar', - 'Foo', - '_', - '__', - '1', - ], isValidPackageName, isFalse); + testEach(['foo', '_foo', '__foo', 'async'], isValidPackageName, isTrue); + testEach( + [ + 'break', // reserved word + 'fOO', + 'foo_', + 'foo_Bar', + 'fooBar', + 'Foo', + '_', + '__', + '1', + ], + isValidPackageName, + isFalse, + ); }); group('pubspec', () { @@ -56,7 +59,7 @@ void main() { '\$Foo', 'Bar\$', 'Foo\$Generated', - 'Foo\$Generated\$Bar' + 'Foo\$Generated\$Bar', ]; testEach(good, isCamelCase, isTrue); var bad = ['fooBar', 'foo', 'f', '_f', 'F_B']; @@ -65,8 +68,10 @@ void main() { group('CamelCaseString', () { test('invalid creation', () { - expect(() => CamelCaseString('invalid'), - throwsA(TypeMatcher())); + expect( + () => CamelCaseString('invalid'), + throwsA(TypeMatcher()), + ); }); test('toString', () { expect(CamelCaseString('CamelCase').toString(), 'CamelCase'); @@ -162,16 +167,7 @@ void main() { ]; testEach(good, isLowerCaseUnderScoreWithDots, isTrue); - var bad = [ - 'Foo', - 'fooBar.', - '.foo_Bar', - '_.', - '.', - 'F_B', - 'JS', - 'JSON', - ]; + var bad = ['Foo', 'fooBar.', '.foo_Bar', '_.', '.', 'F_B', 'JS', 'JSON']; testEach(bad, isLowerCaseUnderScoreWithDots, isFalse); }); diff --git a/pkg/linter/test/validate_incompatible_rules_test.dart b/pkg/linter/test/validate_incompatible_rules_test.dart index 68e4acf45b0e..074a71c7aba4 100644 --- a/pkg/linter/test/validate_incompatible_rules_test.dart +++ b/pkg/linter/test/validate_incompatible_rules_test.dart @@ -12,14 +12,20 @@ void main() { for (var rule in Registry.ruleRegistry) { for (var incompatibleRule in rule.incompatibleRules) { test(rule.name, () async { - var referencedRule = Registry.ruleRegistry - .firstWhere((r) => r.name == incompatibleRule); - expect(referencedRule, isNotNull, - reason: - 'No rule found for id: $incompatibleRule (check for typo?)'); - expect(referencedRule.incompatibleRules, contains(rule.name), - reason: - '$referencedRule should define ${rule.name} in `incompatibleRules` but does not.'); + var referencedRule = Registry.ruleRegistry.firstWhere( + (r) => r.name == incompatibleRule, + ); + expect( + referencedRule, + isNotNull, + reason: 'No rule found for id: $incompatibleRule (check for typo?)', + ); + expect( + referencedRule.incompatibleRules, + contains(rule.name), + reason: + '$referencedRule should define ${rule.name} in `incompatibleRules` but does not.', + ); }); } } diff --git a/pkg/linter/test/validate_no_rule_description_references_test.dart b/pkg/linter/test/validate_no_rule_description_references_test.dart index 33595755eb6b..83b5e218ca31 100644 --- a/pkg/linter/test/validate_no_rule_description_references_test.dart +++ b/pkg/linter/test/validate_no_rule_description_references_test.dart @@ -9,18 +9,27 @@ import 'package:linter/src/rules.dart'; import 'package:test/test.dart'; void main() { - group('check for rule message descriptions in tests:', - // We just need to validate rule message descriptions in one CI bot. - onPlatform: {'windows': Skip('Windows host may not have "grep" tool')}, - () { - registerLintRules(); - for (var rule in Registry.ruleRegistry) { - test(rule.name, () async { - var result = Process.runSync('grep', ['-R', rule.description, 'test']); - expect(result.stdout, isEmpty, + group( + 'check for rule message descriptions in tests:', + // We just need to validate rule message descriptions in one CI bot. + onPlatform: {'windows': Skip('Windows host may not have "grep" tool')}, + () { + registerLintRules(); + for (var rule in Registry.ruleRegistry) { + test(rule.name, () async { + var result = Process.runSync('grep', [ + '-R', + rule.description, + 'test', + ]); + expect( + result.stdout, + isEmpty, reason: - 'Tests that hardcode descriptions make lint messages hard to evolve.'); - }); - } - }); + 'Tests that hardcode descriptions make lint messages hard to evolve.', + ); + }); + } + }, + ); } diff --git a/pkg/linter/test/validate_rule_description_format_test.dart b/pkg/linter/test/validate_rule_description_format_test.dart index bf2f89c059ce..41ba20a2136b 100644 --- a/pkg/linter/test/validate_rule_description_format_test.dart +++ b/pkg/linter/test/validate_rule_description_format_test.dart @@ -13,17 +13,22 @@ void main() { var rules = Registry.ruleRegistry.rules; test('(setup)', () { - expect(rules, isNotEmpty, - reason: - 'Ensure `registerLintRules()` is called before running this suite.'); + expect( + rules, + isNotEmpty, + reason: + 'Ensure `registerLintRules()` is called before running this suite.', + ); }); group('description - trailing periods', () { for (var rule in rules) { test('`${rule.name}` description', () { - expect(rule.description.endsWith('.'), isTrue, - reason: - "Rule description for ${rule.name} should end with a '.'"); + expect( + rule.description.endsWith('.'), + isTrue, + reason: "Rule description for ${rule.name} should end with a '.'", + ); }); } }); diff --git a/pkg/linter/test/verify_generated_files_test.dart b/pkg/linter/test/verify_generated_files_test.dart index bee73a446d3a..1ff8b3e5c19c 100644 --- a/pkg/linter/test/verify_generated_files_test.dart +++ b/pkg/linter/test/verify_generated_files_test.dart @@ -13,7 +13,8 @@ void main() { expect( await generatedNamesFile.check(linterPackageRoot), isTrue, - reason: "The generated lint codes at 'lib/src/lint_names.dart' need to " + reason: + "The generated lint codes at 'lib/src/lint_names.dart' need to " 'be regenerated. ' "Run 'dart run pkg/linter/tool/generate_lints.dart' to update.", ); @@ -23,7 +24,8 @@ void main() { expect( await generatedCodesFile.check(linterPackageRoot), isTrue, - reason: "The generated lint codes at 'lib/src/lint_codes.g.dart' need " + reason: + "The generated lint codes at 'lib/src/lint_codes.g.dart' need " 'to be regenerated. ' "Run 'dart run pkg/linter/tool/generate_lints.dart' to update.", ); diff --git a/pkg/linter/test/verify_reflective_test_suites_test.dart b/pkg/linter/test/verify_reflective_test_suites_test.dart index 30906f1710ee..c745bd635041 100644 --- a/pkg/linter/test/verify_reflective_test_suites_test.dart +++ b/pkg/linter/test/verify_reflective_test_suites_test.dart @@ -16,8 +16,9 @@ import 'test_constants.dart'; void main() { group('check reflective test suites', () { group('rules', () { - var testDirPath = - PhysicalResourceProvider.INSTANCE.pathContext.absolute(ruleTestDir); + var testDirPath = PhysicalResourceProvider.INSTANCE.pathContext.absolute( + ruleTestDir, + ); _VerifyTests(testDirPath).build(); }); }); @@ -36,23 +37,32 @@ class _VerifyTests { void build() { var provider = PhysicalResourceProvider.INSTANCE; var collection = AnalysisContextCollection( - resourceProvider: provider, includedPaths: [testDirPath]); + resourceProvider: provider, + includedPaths: [testDirPath], + ); var contexts = collection.contexts; if (contexts.length != 1) { fail('The test directory contains multiple analysis contexts.'); } - _buildTestsIn(contexts.first.currentSession, testDirPath, - provider.getFolder(testDirPath)); + _buildTestsIn( + contexts.first.currentSession, + testDirPath, + provider.getFolder(testDirPath), + ); } void _buildTestsIn( - AnalysisSession session, String testDirPath, Folder directory) { + AnalysisSession session, + String testDirPath, + Folder directory, + ) { var testFileNames = []; File? testAllFile; var children = directory.getChildren(); - children - .sort((first, second) => first.shortName.compareTo(second.shortName)); + children.sort( + (first, second) => first.shortName.compareTo(second.shortName), + ); for (var child in children) { if (child is Folder) { if (child.getChildAssumingFile(testAllFileName).exists) { @@ -95,7 +105,8 @@ class _VerifyTests { } if (missingFiles.isNotEmpty) { fail( - 'Tests missing from "$testDirPath/$testAllFileName": ${missingFiles.join(', ')}'); + 'Tests missing from "$testDirPath/$testAllFileName": ${missingFiles.join(', ')}', + ); } var extraImports = []; for (var importedFile in importedFiles) { @@ -105,7 +116,8 @@ class _VerifyTests { } if (extraImports.isNotEmpty) { fail( - 'Extra tests in "$testDirPath/$testAllFileName": ${extraImports.join(', ')}'); + 'Extra tests in "$testDirPath/$testAllFileName": ${extraImports.join(', ')}', + ); } }); } diff --git a/pkg/linter/tool/benchmark.dart b/pkg/linter/tool/benchmark.dart index 233181ad5a09..0945d03fe376 100644 --- a/pkg/linter/tool/benchmark.dart +++ b/pkg/linter/tool/benchmark.dart @@ -45,8 +45,10 @@ Iterable collectFiles(String entityPtah) { } else { var directory = Directory(entityPtah); if (directory.existsSync()) { - for (var entry - in directory.listSync(recursive: true, followLinks: false)) { + for (var entry in directory.listSync( + recursive: true, + followLinks: false, + )) { var relative = path.relative(entry.path, from: directory.path); if (entry is File && entry.path.isLintable && !relative.isInHiddenDir) { @@ -89,13 +91,20 @@ Future runLinter(List args) async { var parser = ArgParser(); parser - ..addFlag('help', - abbr: 'h', negatable: false, help: 'Show usage information.') + ..addFlag( + 'help', + abbr: 'h', + negatable: false, + help: 'Show usage information.', + ) ..addOption('config', abbr: 'c', help: 'Use configuration from this file.') ..addOption('dart-sdk', help: 'Custom path to a Dart SDK.') - ..addMultiOption('rules', - help: 'A list of lint rules to run. For example: ' - 'annotate_overrides, avoid_catching_errors'); + ..addMultiOption( + 'rules', + help: + 'A list of lint rules to run. For example: ' + 'annotate_overrides, avoid_catching_errors', + ); ArgResults options; try { @@ -113,8 +122,11 @@ Future runLinter(List args) async { var paths = options.rest; if (paths.isEmpty) { - printUsage(parser, errorSink, - 'Please provide at least one file or directory to lint.'); + printUsage( + parser, + errorSink, + 'Please provide at least one file or directory to lint.', + ); exitCode = unableToProcessExitCode; return; } @@ -127,8 +139,9 @@ Future runLinter(List args) async { var optionsContent = readFile(configFile); var options = loadYamlNode(optionsContent) as YamlMap; var ruleConfigs = parseLinterSection(options)!.values; - var enabledRules = Registry.ruleRegistry - .where((rule) => !ruleConfigs.any((rc) => rc.disables(rule.name))); + var enabledRules = Registry.ruleRegistry.where( + (rule) => !ruleConfigs.any((rc) => rc.disables(rule.name)), + ); linterOptions = LinterOptions(enabledRules: enabledRules); } else if (ruleNames is Iterable && ruleNames.isNotEmpty) { @@ -155,20 +168,19 @@ Future runLinter(List args) async { var filesToLint = [ for (var path in paths) - ...collectFiles(path) - .map((file) => file.path.toAbsoluteNormalizedPath()) - .map(File.new), + ...collectFiles( + path, + ).map((file) => file.path.toAbsoluteNormalizedPath()).map(File.new), ]; - await writeBenchmarks( - outSink, - filesToLint, - linterOptions, - ); + await writeBenchmarks(outSink, filesToLint, linterOptions); } Future writeBenchmarks( - StringSink out, List filesToLint, LinterOptions linterOptions) async { + StringSink out, + List filesToLint, + LinterOptions linterOptions, +) async { var timings = {}; for (var i = 0; i < benchmarkRuns; ++i) { await lintFiles(TestLinter(linterOptions), filesToLint); @@ -183,28 +195,31 @@ Future writeBenchmarks( var recommendedRuleset = await dartRecommendedLints; var flutterRuleset = await flutterUserLints; - var stats = timings.keys.map((t) { - var sets = []; - if (coreRuleset.contains(t)) { - sets.add('core'); - } - if (recommendedRuleset.contains(t)) { - sets.add('recommended'); - } - if (flutterRuleset.contains(t)) { - sets.add('flutter'); - } + var stats = + timings.keys.map((t) { + var sets = []; + if (coreRuleset.contains(t)) { + sets.add('core'); + } + if (recommendedRuleset.contains(t)) { + sets.add('recommended'); + } + if (flutterRuleset.contains(t)) { + sets.add('flutter'); + } - var details = sets.isEmpty ? '' : " [${sets.join(', ')}]"; - return Stat('$t$details', timings[t] ?? 0); - }).toList(); + var details = sets.isEmpty ? '' : " [${sets.join(', ')}]"; + return Stat('$t$details', timings[t] ?? 0); + }).toList(); out.writeTimings(stats, 0); } int _maxSeverity(List infos) { var filteredErrors = infos.expand((i) => i.errors); return filteredErrors.fold( - 0, (value, e) => math.max(value, e.errorCode.errorSeverity.ordinal)); + 0, + (value, e) => math.max(value, e.errorCode.errorSeverity.ordinal), + ); } class Stat implements Comparable { @@ -258,8 +273,10 @@ extension on StringSink { void writeTimings(List timings, int summaryLength) { var names = timings.map((s) => s.name).toList(); - var longestName = - names.fold(0, (prev, element) => math.max(prev, element.length)); + var longestName = names.fold( + 0, + (prev, element) => math.max(prev, element.length), + ); var longestTime = 8; var tableWidth = math.max(summaryLength, longestName + longestTime); var pad = tableWidth - longestName; @@ -275,12 +292,14 @@ extension on StringSink { for (var stat in timings) { totalTime += stat.elapsed; writeln( - '${stat.name.padRight(longestName)}${stat.elapsed.toString().padLeft(pad)}'); + '${stat.name.padRight(longestName)}${stat.elapsed.toString().padLeft(pad)}', + ); } writeln(line); writeln( - '${'Total'.padRight(longestName)}${totalTime.toString().padLeft(pad)}'); + '${'Total'.padRight(longestName)}${totalTime.toString().padLeft(pad)}', + ); writeln(line); } } diff --git a/pkg/linter/tool/checks/check_all_yaml.dart b/pkg/linter/tool/checks/check_all_yaml.dart index 5bce88161386..d9594a018cdd 100644 --- a/pkg/linter/tool/checks/check_all_yaml.dart +++ b/pkg/linter/tool/checks/check_all_yaml.dart @@ -53,8 +53,10 @@ String? checkAllYaml() { registerLintRules(); var registeredRules = Registry.ruleRegistry - .where((r) => - !r.state.isDeprecated && !r.state.isInternal && !r.state.isRemoved) + .where( + (r) => + !r.state.isDeprecated && !r.state.isInternal && !r.state.isRemoved, + ) .map((r) => r.name); var extraRules = []; @@ -102,7 +104,8 @@ Map _getOptionsFromString(String optionsSource) { } if (doc is! YamlMap) { throw Exception( - 'Bad options file format (expected map, got ${doc.runtimeType})'); + 'Bad options file format (expected map, got ${doc.runtimeType})', + ); } doc.nodes.forEach((k, YamlNode v) { if (k is! YamlScalar) { diff --git a/pkg/linter/tool/checks/check_messages_yaml.dart b/pkg/linter/tool/checks/check_messages_yaml.dart index 94202d6ee306..02155970b8c2 100644 --- a/pkg/linter/tool/checks/check_messages_yaml.dart +++ b/pkg/linter/tool/checks/check_messages_yaml.dart @@ -14,7 +14,9 @@ void main() { void checkMessagesYaml() { var parsedLintRuleDocs = messagesRuleInfo; if (parsedLintRuleDocs.isEmpty) { - throw StateError("The 'pkg/linter/messages.yaml' file was parsed " - 'as including no lint rule entries.'); + throw StateError( + "The 'pkg/linter/messages.yaml' file was parsed " + 'as including no lint rule entries.', + ); } } diff --git a/pkg/linter/tool/checks/driver.dart b/pkg/linter/tool/checks/driver.dart index 929232bdc3a2..7e2185fbb4c5 100644 --- a/pkg/linter/tool/checks/driver.dart +++ b/pkg/linter/tool/checks/driver.dart @@ -30,15 +30,12 @@ Future main() async { } } -var customChecks = [ - VisitRegisteredNodes(), - NoSoloTests(), - NoTrailingSpaces(), -]; +var customChecks = [VisitRegisteredNodes(), NoSoloTests(), NoTrailingSpaces()]; Future> runChecks() async { - var rules = - path.normalize(io.File(path.join('lib', 'src', 'rules')).absolute.path); + var rules = path.normalize( + io.File(path.join('lib', 'src', 'rules')).absolute.path, + ); var tests = path.normalize(io.File(path.join('test')).absolute.path); var results = await Driver(customChecks).analyze([rules, tests]); return results; @@ -64,7 +61,9 @@ class Driver { } Future> _analyzeFiles( - ResourceProvider resourceProvider, List analysisRoots) async { + ResourceProvider resourceProvider, + List analysisRoots, + ) async { _print('Analyzing...'); // Register our checks. diff --git a/pkg/linter/tool/checks/rules/no_solo_tests.dart b/pkg/linter/tool/checks/rules/no_solo_tests.dart index a15353606e14..c85631a3c4dd 100644 --- a/pkg/linter/tool/checks/rules/no_solo_tests.dart +++ b/pkg/linter/tool/checks/rules/no_solo_tests.dart @@ -10,23 +10,24 @@ import 'package:linter/src/analyzer.dart'; const _desc = r"Don't commit soloed tests."; class NoSoloTests extends LintRule { - static const LintCode code = LintCode('no_solo_tests', _desc, - correctionMessage: - "Try removing the 'soloTest' annotation or 'solo_' prefix.", - hasPublishedDocs: true); + static const LintCode code = LintCode( + 'no_solo_tests', + _desc, + correctionMessage: + "Try removing the 'soloTest' annotation or 'solo_' prefix.", + hasPublishedDocs: true, + ); - NoSoloTests() - : super( - name: 'no_solo_tests', - description: _desc, - ); + NoSoloTests() : super(name: 'no_solo_tests', description: _desc); @override LintCode get lintCode => code; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (context.definingUnit.unit.inTestDir) { var visitor = _Visitor(this); registry.addMethodDeclaration(this, visitor); diff --git a/pkg/linter/tool/checks/rules/no_trailing_spaces.dart b/pkg/linter/tool/checks/rules/no_trailing_spaces.dart index 42a566139403..42dbbece83da 100644 --- a/pkg/linter/tool/checks/rules/no_trailing_spaces.dart +++ b/pkg/linter/tool/checks/rules/no_trailing_spaces.dart @@ -9,22 +9,23 @@ import 'package:linter/src/analyzer.dart'; const _desc = r"Don't create string literals with trailing spaces in tests."; class NoTrailingSpaces extends LintRule { - static const LintCode code = LintCode('no_trailing_spaces', _desc, - correctionMessage: 'Try removing the trailing spaces.', - hasPublishedDocs: true); + static const LintCode code = LintCode( + 'no_trailing_spaces', + _desc, + correctionMessage: 'Try removing the trailing spaces.', + hasPublishedDocs: true, + ); - NoTrailingSpaces() - : super( - name: 'no_trailing_spaces', - description: _desc, - ); + NoTrailingSpaces() : super(name: 'no_trailing_spaces', description: _desc); @override LintCode get lintCode => code; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { if (context.definingUnit.unit.inTestDir) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); diff --git a/pkg/linter/tool/checks/rules/visit_registered_nodes.dart b/pkg/linter/tool/checks/rules/visit_registered_nodes.dart index 33726ad30316..82d3a97b3b97 100644 --- a/pkg/linter/tool/checks/rules/visit_registered_nodes.dart +++ b/pkg/linter/tool/checks/rules/visit_registered_nodes.dart @@ -11,23 +11,25 @@ import 'package:linter/src/analyzer.dart'; const _desc = r"Declare 'visit' methods for all registered node types."; class VisitRegisteredNodes extends LintRule { - static const LintCode code = LintCode('visit_registered_nodes', _desc, - correctionMessage: - "Try declaring a 'visit' method for all registered node types.", - hasPublishedDocs: true); + static const LintCode code = LintCode( + 'visit_registered_nodes', + _desc, + correctionMessage: + "Try declaring a 'visit' method for all registered node types.", + hasPublishedDocs: true, + ); VisitRegisteredNodes() - : super( - name: 'visit_registered_nodes', - description: _desc, - ); + : super(name: 'visit_registered_nodes', description: _desc); @override LintCode get lintCode => code; @override void registerNodeProcessors( - NodeLintRegistry registry, LinterContext context) { + NodeLintRegistry registry, + LinterContext context, + ) { var visitor = _Visitor(this, context.inheritanceManager); registry.addMethodDeclaration(this, visitor); } @@ -39,8 +41,11 @@ class _BodyVisitor extends RecursiveAstVisitor { _BodyVisitor(this.rule, this.inheritanceManager); bool implements(ClassElement2 visitor, String methodName) { - var member = inheritanceManager.getMember4(visitor, Name(null, methodName), - concrete: true); + var member = inheritanceManager.getMember4( + visitor, + Name(null, methodName), + concrete: true, + ); // In general lint visitors should only inherit from SimpleAstVisitors // (and the method implementations inherited from there are only stubs). // (We might consider enforcing this since it's harder to ensure that diff --git a/pkg/linter/tool/generate_lints.dart b/pkg/linter/tool/generate_lints.dart index 687b3bbcc878..d1ef7b3105bd 100644 --- a/pkg/linter/tool/generate_lints.dart +++ b/pkg/linter/tool/generate_lints.dart @@ -55,11 +55,13 @@ class LinterLintCode extends LintCode { out.writeln(' @Deprecated("$deprecatedMessage")'); } out.writeln(' static const LintCode $errorName ='); - out.writeln(codeInfo.toAnalyzerCode( - 'LinterLintCode', - errorName, - sharedNameReference: 'LintNames.$lintName', - )); + out.writeln( + codeInfo.toAnalyzerCode( + 'LinterLintCode', + errorName, + sharedNameReference: 'LintNames.$lintName', + ), + ); out.writeln(); } diff --git a/pkg/linter/tool/lint_sets.dart b/pkg/linter/tool/lint_sets.dart index b016aa12ab1e..abfdc1e1d654 100644 --- a/pkg/linter/tool/lint_sets.dart +++ b/pkg/linter/tool/lint_sets.dart @@ -19,7 +19,8 @@ Future> get flutterRepoLints => _fetchRulesFromGitHub('/flutter/flutter/main/analysis_options.yaml'); Future> get flutterUserLints => _fetchRulesFromGitHub( - '/flutter/packages/main/packages/flutter_lints/lib/flutter.yaml'); + '/flutter/packages/main/packages/flutter_lints/lib/flutter.yaml', +); Future> _fetchRulesFromGitHub(String optionsPath) async { var optionsUrl = Uri.https('raw.githubusercontent.com', optionsPath); diff --git a/pkg/linter/tool/machine.dart b/pkg/linter/tool/machine.dart index 950b9b4faff8..574d438fa959 100644 --- a/pkg/linter/tool/machine.dart +++ b/pkg/linter/tool/machine.dart @@ -24,8 +24,9 @@ import 'util/path_utils.dart'; /// **Deprecated:** This tool and the resulting generated file in /// `tool/machine/rules.json` are deprecated and should not be relied on. void main(List args) async { - var parser = ArgParser() - ..addFlag('write', abbr: 'w', help: 'Write `rules.json` file.'); + var parser = + ArgParser() + ..addFlag('write', abbr: 'w', help: 'Write `rules.json` file.'); var options = parser.parse(args); var json = await generateRulesJson(); @@ -42,21 +43,25 @@ void main(List args) async { Future generateRulesJson() async { registerLintRules(); var fixStatusMap = readFixStatusMap(); - return await getMachineListing(Registry.ruleRegistry, - fixStatusMap: fixStatusMap); + return await getMachineListing( + Registry.ruleRegistry, + fixStatusMap: fixStatusMap, + ); } Future getMachineListing( Iterable ruleRegistry, { Map fixStatusMap = const {}, }) async { - var rulesToDocument = List.of(ruleRegistry, growable: false) - .where((rule) => !rule.state.isInternal) - .sortedBy((rule) => rule.name); + var rulesToDocument = List.of( + ruleRegistry, + growable: false, + ).where((rule) => !rule.state.isInternal).sortedBy((rule) => rule.name); var json = JsonEncoder.withIndent(' ').convert([ - for (var (rule, info) - in rulesToDocument.map((rule) => (rule, messagesRuleInfo[rule.name]!))) + for (var (rule, info) in rulesToDocument.map( + (rule) => (rule, messagesRuleInfo[rule.name]!), + )) { 'name': rule.name, 'description': rule.description, @@ -68,7 +73,7 @@ Future getMachineListing( fixStatusMap[rule.lintCodes.first.uniqueName] ?? 'unregistered', 'details': info.deprecatedDetails, 'sinceDartSdk': _versionToString(info.states.first.since), - } + }, ]); return json; } @@ -85,7 +90,7 @@ Map readFixStatusMap() { 'src', 'services', 'correction', - 'error_fix_status.yaml' + 'error_fix_status.yaml', ]); var contents = File(statusFilePath).readAsStringSync(); diff --git a/pkg/linter/tool/messages_info.dart b/pkg/linter/tool/messages_info.dart index f370b8189e85..080e1daef174 100644 --- a/pkg/linter/tool/messages_info.dart +++ b/pkg/linter/tool/messages_info.dart @@ -46,7 +46,8 @@ final Map messagesRuleInfo = () { var lintCodes = messagesYaml['LintCode'] as YamlMap?; if (lintCodes == null) { throw StateError( - "The '_messagesFileName' file does not have a 'LintCode' section."); + "The '_messagesFileName' file does not have a 'LintCode' section.", + ); } { @@ -54,8 +55,10 @@ final Map messagesRuleInfo = () { var lintCodeKeysSorted = lintCodeKeys.sorted(); for (var i = 0; i < lintCodeKeys.length; i++) { if (lintCodeKeys[i] != lintCodeKeysSorted[i]) { - throw StateError("The LintCode entries in '_messagesFileName' " - "are not sorted alphabetically, starting at '${lintCodeKeys[i]}'."); + throw StateError( + "The LintCode entries in '_messagesFileName' " + "are not sorted alphabetically, starting at '${lintCodeKeys[i]}'.", + ); } } } @@ -83,8 +86,11 @@ class CodeInfo { final String problemMessage; final String? correctionMessage; - CodeInfo(this.uniqueName, - {required this.problemMessage, this.correctionMessage}); + CodeInfo( + this.uniqueName, { + required this.problemMessage, + this.correctionMessage, + }); } class RuleInfo { @@ -114,16 +120,10 @@ class RuleInfo { class _RuleBuilder { final String sharedName; final List< - ({ - String uniqueName, - String? problemMessage, - String? correctionMessage - })> _codes = []; - List< - ({ - String name, - Version version, - })>? _stateEntries; + ({String uniqueName, String? problemMessage, String? correctionMessage}) + > + _codes = []; + List<({String name, Version version})>? _stateEntries; Set? _categories; bool? _hasPublishedDocs; String? _documentation; @@ -145,22 +145,28 @@ class _RuleBuilder { } RuleInfo build() => RuleInfo( - name: sharedName, - codes: _validateCodes(), - states: _validateStates(), - categories: _requireSpecified('categories', _categories, - ifNotRemovedFallback: const {}), - hasPublishedDocs: _hasPublishedDocs ?? false, - documentation: _documentation, - deprecatedDetails: - _requireSpecified('deprecatedDetails', _deprecatedDetails), - removed: _wasRemoved, - ); + name: sharedName, + codes: _validateCodes(), + states: _validateStates(), + categories: _requireSpecified( + 'categories', + _categories, + ifNotRemovedFallback: const {}, + ), + hasPublishedDocs: _hasPublishedDocs ?? false, + documentation: _documentation, + deprecatedDetails: _requireSpecified( + 'deprecatedDetails', + _deprecatedDetails, + ), + removed: _wasRemoved, + ); void _addCode(String name, Map data) { if (_codes.map((code) => code.uniqueName).any((n) => n == name)) { _throwLintError( - "Has more than one LintCode with '$name' as its 'uniqueName'."); + "Has more than one LintCode with '$name' as its 'uniqueName'.", + ); } String? problemMessage; @@ -170,20 +176,23 @@ class _RuleBuilder { String? correctionMessage; if (data.containsKey('correctionMessage')) { - correctionMessage = - _requireType('correctionMessage', data['correctionMessage']); + correctionMessage = _requireType( + 'correctionMessage', + data['correctionMessage'], + ); } _codes.add(( uniqueName: name, problemMessage: problemMessage, - correctionMessage: correctionMessage + correctionMessage: correctionMessage, )); } Never _alreadySpecified(String propertyName) { _throwLintError( - "More than one LintCode specified the '$propertyName' property."); + "More than one LintCode specified the '$propertyName' property.", + ); } void _requireNotEmpty(String propertyName, String value) { @@ -192,8 +201,11 @@ class _RuleBuilder { } } - T _requireSpecified(String propertyName, T? value, - {T? ifNotRemovedFallback}) { + T _requireSpecified( + String propertyName, + T? value, { + T? ifNotRemovedFallback, + }) { if (value == null) { if (_wasRemoved && ifNotRemovedFallback != null) { return ifNotRemovedFallback; @@ -213,11 +225,15 @@ class _RuleBuilder { } Iterable _requireTypeForItems( - String propertyName, Iterable items) { + String propertyName, + Iterable items, + ) { for (var item in items) { if (item is! T) { - _throwLintError("The items in the '$propertyName' collection must " - "each be of type '$T'."); + _throwLintError( + "The items in the '$propertyName' collection must " + "each be of type '$T'.", + ); } } @@ -232,8 +248,10 @@ class _RuleBuilder { if (_categories != null) _alreadySpecified(propertyName); var categoryValues = _requireType>(propertyName, value); - var categoryStrings = - _requireTypeForItems(propertyName, categoryValues); + var categoryStrings = _requireTypeForItems( + propertyName, + categoryValues, + ); var countWithDuplicates = categoryStrings.length; var categoriesSet = categoryStrings.toSet(); @@ -292,25 +310,28 @@ class _RuleBuilder { var stateValue = _requireType>(propertyName, value); - _stateEntries = stateValue.entries.map((state) { - var stateName = state.key; - var version = state.value; - if (stateName is! String || version is! String) { - _throwLintError('Each state key and value must be a string.'); - } - - if (!_stateNames.contains(stateName)) { - _throwLintError('$stateName is not a valid state name.'); - } - - try { - var parsedVersion = Version.parse('$version.0'); - return (name: stateName, version: parsedVersion); - } on Exception { - _throwLintError('The state versions must be in ' - "'major.minor' format, but found '$version'."); - } - }).toList(); + _stateEntries = + stateValue.entries.map((state) { + var stateName = state.key; + var version = state.value; + if (stateName is! String || version is! String) { + _throwLintError('Each state key and value must be a string.'); + } + + if (!_stateNames.contains(stateName)) { + _throwLintError('$stateName is not a valid state name.'); + } + + try { + var parsedVersion = Version.parse('$version.0'); + return (name: stateName, version: parsedVersion); + } on Exception { + _throwLintError( + 'The state versions must be in ' + "'major.minor' format, but found '$version'.", + ); + } + }).toList(); } Never _throwLintError(String message) { @@ -329,7 +350,8 @@ class _RuleBuilder { var problemMessage = code.problemMessage; if (problemMessage == null) { _throwLintError( - "'LintCode.${code.uniqueName}' is missing a 'problemMessage'."); + "'LintCode.${code.uniqueName}' is missing a 'problemMessage'.", + ); } // TODO(parlough): Eventually require that codes have a correction message. @@ -338,9 +360,13 @@ class _RuleBuilder { // _throwLintError("'LintCode.${code.uniqueName}' is missing a 'correctionMessage'."); // } - codeInfos.add(CodeInfo(code.uniqueName, + codeInfos.add( + CodeInfo( + code.uniqueName, problemMessage: problemMessage, - correctionMessage: code.correctionMessage)); + correctionMessage: code.correctionMessage, + ), + ); } return codeInfos; @@ -353,14 +379,16 @@ class _RuleBuilder { } var sortedStates = states - .map((state) => switch (state.name) { - 'experimental' => State.experimental(since: state.version), - 'stable' => State.stable(since: state.version), - 'internal' => State.internal(since: state.version), - 'deprecated' => State.deprecated(since: state.version), - 'removed' => State.removed(since: state.version), - _ => _throwLintError('Unexpected state name: ${state.name}.'), - }) + .map( + (state) => switch (state.name) { + 'experimental' => State.experimental(since: state.version), + 'stable' => State.stable(since: state.version), + 'internal' => State.internal(since: state.version), + 'deprecated' => State.deprecated(since: state.version), + 'removed' => State.removed(since: state.version), + _ => _throwLintError('Unexpected state name: ${state.name}.'), + }, + ) .sortedBy((state) => state.since ?? Version.none); return sortedStates; diff --git a/pkg/linter/tool/migrate.dart b/pkg/linter/tool/migrate.dart index aad9b8f6d24b..44feb8fefbff 100644 --- a/pkg/linter/tool/migrate.dart +++ b/pkg/linter/tool/migrate.dart @@ -16,33 +16,40 @@ import 'checks/driver.dart'; /// Lists files yet to be migrated to the new element model. void main(List args) async { - var parser = ArgParser() - ..addFlag('write', - abbr: 'w', help: 'Write updated `analyzer_use_new_elements.txt` file.'); + var parser = + ArgParser()..addFlag( + 'write', + abbr: 'w', + help: 'Write updated `analyzer_use_new_elements.txt` file.', + ); - var errors = - await getOldElementModelAccesses(directoryToMigrate.absolute.path); + var errors = await getOldElementModelAccesses( + directoryToMigrate.absolute.path, + ); var errorFiles = {}; for (var error in errors) { errorFiles.add(error.source.fullName); } - var migratedFilesSet = filesToMigrate - .where((file) => !errorFiles.any((f) => f.endsWith(file))) - .toSet(); + var migratedFilesSet = + filesToMigrate + .where((file) => !errorFiles.any((f) => f.endsWith(file))) + .toSet(); var migratedFilesSorted = migratedFilesSet.map(asRelativePosix).sorted(); - var unmigratedFilesSorted = filesToMigrate - .where((file) => !migratedFilesSet.contains(file)) - .map(asRelativePosix) - .sorted(); + var unmigratedFilesSorted = + filesToMigrate + .where((file) => !migratedFilesSet.contains(file)) + .map(asRelativePosix) + .sorted(); var options = parser.parse(args); if (options['write'] == true) { print("Writing to 'analyzer_use_new_elements.txt'..."); print('-' * 20); - File('analyzer_use_new_elements.txt') - .writeAsStringSync('${unmigratedFilesSorted.join('\n')}\n'); + File( + 'analyzer_use_new_elements.txt', + ).writeAsStringSync('${unmigratedFilesSorted.join('\n')}\n'); } else { print('Migrated files:\n'); print(migratedFilesSorted.join('\n')); @@ -57,17 +64,20 @@ void main(List args) async { final Directory directoryToMigrate = Directory.current; -final List filesToMigrate = directoryToMigrate - .listSync(recursive: true) - .where((f) => f.path.endsWith('.dart')) - .map((r) => r.path) - .toList(); +final List filesToMigrate = + directoryToMigrate + .listSync(recursive: true) + .where((f) => f.path.endsWith('.dart')) + .map((r) => r.path) + .toList(); String asRelativePosix(String fullPath) => path.posix.joinAll( - path.split(path.relative(fullPath, from: directoryToMigrate.path))); + path.split(path.relative(fullPath, from: directoryToMigrate.path)), +); Future> getOldElementModelAccesses(String directory) async { - var results = await Driver([AnalyzerUseNewElements(useOptInFile: false)]) - .analyze([directory]); + var results = await Driver([ + AnalyzerUseNewElements(useOptInFile: false), + ]).analyze([directory]); return results; } diff --git a/pkg/linter/tool/rule.dart b/pkg/linter/tool/rule.dart index cf4681d4e855..eaf712448b7b 100644 --- a/pkg/linter/tool/rule.dart +++ b/pkg/linter/tool/rule.dart @@ -18,14 +18,15 @@ import 'messages_info.dart'; /// Generates rule and rule test stub files (into `src/rules` and `test/rules` /// respectively), as well as the rule index (`rules.dart`). void main(List args) { - var parser = ArgParser() - ..addOption('out', abbr: 'o', help: 'Specifies project root.') - ..addOption( - 'name', - abbr: 'n', - help: 'Specifies lower_underscore rule name.', - mandatory: true, - ); + var parser = + ArgParser() + ..addOption('out', abbr: 'o', help: 'Specifies project root.') + ..addOption( + 'name', + abbr: 'n', + help: 'Specifies lower_underscore rule name.', + mandatory: true, + ); ArgResults options; try { @@ -57,8 +58,14 @@ String get _thisYear => DateTime.now().year.toString(); String capitalize(String s) => s.substring(0, 1).toUpperCase() + s.substring(1); -void generateFile(String ruleName, String stubPath, Generator generator, - {String? outDir, bool overwrite = false, bool format = false}) { +void generateFile( + String ruleName, + String stubPath, + Generator generator, { + String? outDir, + bool overwrite = false, + bool format = false, +}) { var (:file, :contents) = generator(ruleName, toClassName(ruleName)); if (outDir != null) { var outPath = path.join(outDir, stubPath, file); @@ -79,26 +86,46 @@ void generateFile(String ruleName, String stubPath, Generator generator, void generateRule(String ruleName, {String? outDir}) { // Generate rule stub. - generateFile(ruleName, path.join('lib', 'src', 'rules'), _generateClass, - outDir: outDir); + generateFile( + ruleName, + path.join('lib', 'src', 'rules'), + _generateClass, + outDir: outDir, + ); // Generate unit test stub. generateFile(ruleName, ruleTestDir, _generateTest, outDir: outDir); // Generate test `all.dart` helper. - generateFile(ruleName, ruleTestDir, _generateAllTestsFile, - outDir: outDir, overwrite: true, format: true); + generateFile( + ruleName, + ruleTestDir, + _generateAllTestsFile, + outDir: outDir, + overwrite: true, + format: true, + ); // Generate an example `all.yaml` - generateFile(ruleName, 'example', _generateAllYaml, - outDir: outDir, overwrite: true); + generateFile( + ruleName, + 'example', + _generateAllYaml, + outDir: outDir, + overwrite: true, + ); printToConsole('Updating ${Changelog.fileName}'); Changelog().addEntry(RuleStateChange.added, ruleName); // Update rule registry. - generateFile(ruleName, path.join('lib', 'src'), _generateRulesFile, - outDir: outDir, overwrite: true); + generateFile( + ruleName, + path.join('lib', 'src'), + _generateRulesFile, + outDir: outDir, + overwrite: true, + ); printToConsole('A unit test has been stubbed out in:'); printToConsole(' $ruleTestDir/${ruleName}_test.dart'); @@ -129,8 +156,8 @@ GeneratedFile _generateAllTestsFile(String libName, String className) { sb.writeln('// ignore_for_file: library_prefixes'); sb.writeln(); - var paths = Directory(ruleTestDir).listSync().map((f) => f.path).toList() - ..sort(); + var paths = + Directory(ruleTestDir).listSync().map((f) => f.path).toList()..sort(); var testNames = []; for (var file in paths) { @@ -162,11 +189,16 @@ linter: rules: '''); - var names = Registry.ruleRegistry.rules - .where((r) => - !r.state.isDeprecated && !r.state.isInternal && !r.state.isRemoved) - .map((r) => r.name) - .toList(); + var names = + Registry.ruleRegistry.rules + .where( + (r) => + !r.state.isDeprecated && + !r.state.isInternal && + !r.state.isRemoved, + ) + .map((r) => r.name) + .toList(); names.add(libName); names.sort(); @@ -177,8 +209,8 @@ linter: } GeneratedFile _generateClass(String ruleName, String className) => ( - file: '$ruleName.dart', - contents: """ + file: '$ruleName.dart', + contents: """ // Copyright (c) $_thisYear, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @@ -221,8 +253,8 @@ class _Visitor extends SimpleAstVisitor { // TODO: implement } } -""" - ); +""", +); GeneratedFile _generateRulesFile(String libName, String className) { registerLintRules(); @@ -268,8 +300,8 @@ void registerLintRules() { } GeneratedFile _generateTest(String libName, String className) => ( - file: '${libName}_test.dart', - contents: ''' + file: '${libName}_test.dart', + contents: ''' // Copyright (c) $_thisYear, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @@ -297,8 +329,8 @@ class ${className}Test extends LintRuleTest { ]); } } -''' - ); +''', +); typedef GeneratedFile = ({String file, String contents}); diff --git a/pkg/linter/tool/scorecard.dart b/pkg/linter/tool/scorecard.dart index d83d4b28ce67..48e4c9e5f378 100644 --- a/pkg/linter/tool/scorecard.dart +++ b/pkg/linter/tool/scorecard.dart @@ -45,8 +45,9 @@ Iterable get registeredLintNames => registeredLints!.map((r) => r.name); Iterable? get registeredLints { if (_registeredLints == null) { registerLintRules(); - _registeredLints = Registry.ruleRegistry.toList() - ..sort((l1, l2) => l1.name.compareTo(l2.name)); + _registeredLints = + Registry.ruleRegistry.toList() + ..sort((l1, l2) => l1.name.compareTo(l2.name)); } return _registeredLints; } @@ -148,7 +149,8 @@ class LintScore { sb.write('${ruleSets.contains('flutter') ? " $checkMark" : ""} |'); case Detail.flutterRepo: sb.write( - '${ruleSets.contains('flutter_repo') ? " $checkMark" : ""} |'); + '${ruleSets.contains('flutter_repo') ? " $checkMark" : ""} |', + ); case Detail.status: sb.write('${!state.isStable ? ' **${state.label}** ' : ""} |'); } @@ -206,13 +208,16 @@ class ScoreCard { ruleSets.add('flutter_repo'); } - scorecard.add(LintScore( - name: lint.name, - hasFix: lintsWithFixes.contains(lint.name) || - lintsWithAssists.contains(lint.name), - state: lint.state, - ruleSets: ruleSets, - )); + scorecard.add( + LintScore( + name: lint.name, + hasFix: + lintsWithFixes.contains(lint.name) || + lintsWithAssists.contains(lint.name), + state: lint.state, + ruleSets: ruleSets, + ), + ); } return scorecard; @@ -225,14 +230,15 @@ class ScoreCard { 'src', 'services', 'correction', - 'assist.dart' + 'assist.dart', ]); var contents = File(assistFilePath).readAsStringSync(); var parser = CompilationUnitParser(); var cu = parser.parse(contents: contents, name: 'assist.dart'); var assistKindClass = cu.declarations.firstWhere( - (m) => m is ClassDeclaration && m.name.lexeme == 'DartAssistKind'); + (m) => m is ClassDeclaration && m.name.lexeme == 'DartAssistKind', + ); var collector = _AssistCollector(); assistKindClass.accept(collector); @@ -245,7 +251,8 @@ class ScoreCard { var parser = CompilationUnitParser(); var cu = parser.parse(contents: contents, name: 'lint_names.dart'); var lintNamesClass = cu.declarations.firstWhere( - (m) => m is ClassDeclaration && m.name.lexeme == 'LintNames'); + (m) => m is ClassDeclaration && m.name.lexeme == 'LintNames', + ); var collector = _FixCollector(); lintNamesClass.accept(collector); @@ -261,8 +268,10 @@ class _AssistCollector extends GeneralizingAstVisitor { if (node.name.toString() == 'associatedErrorCodes:') { var list = node.expression as ListLiteral; for (var element in list.elements) { - var name = - element.toString().substring(1, element.toString().length - 1); + var name = element.toString().substring( + 1, + element.toString().length - 1, + ); lintNames.add(name); if (!registeredLintNames.contains(name)) { printToConsole('WARNING: unrecognized lint in assists: $name'); diff --git a/pkg/linter/tool/util/formatter.dart b/pkg/linter/tool/util/formatter.dart index a4a286476ece..f9a6fc9ad466 100644 --- a/pkg/linter/tool/util/formatter.dart +++ b/pkg/linter/tool/util/formatter.dart @@ -41,14 +41,17 @@ class ReportFormatter { /// Override to influence error sorting. int compare(AnalysisError error1, AnalysisError error2) { // Severity. - var compare = error2.errorCode.errorSeverity - .compareTo(error1.errorCode.errorSeverity); + var compare = error2.errorCode.errorSeverity.compareTo( + error1.errorCode.errorSeverity, + ); if (compare != 0) { return compare; } // Path. - compare = Comparable.compare(error1.source.fullName.toLowerCase(), - error2.source.fullName.toLowerCase()); + compare = Comparable.compare( + error1.source.fullName.toLowerCase(), + error2.source.fullName.toLowerCase(), + ); if (compare != 0) { return compare; } diff --git a/pkg/linter/tool/util/lint_driver.dart b/pkg/linter/tool/util/lint_driver.dart index 17c87fc193c0..2225f65045b1 100644 --- a/pkg/linter/tool/util/lint_driver.dart +++ b/pkg/linter/tool/util/lint_driver.dart @@ -44,8 +44,9 @@ class LintDriver { }) { analysisOptions.lint = true; analysisOptions.warning = false; - analysisOptions.lintRules = - _options.enabledRules.toList(growable: false); + analysisOptions.lintRules = _options.enabledRules.toList( + growable: false, + ); }, enableLintRuleTiming: _options.enableTiming, ); diff --git a/pkg/linter/tool/util/path_utils.dart b/pkg/linter/tool/util/path_utils.dart index 572cb43e9c81..9438fce44273 100644 --- a/pkg/linter/tool/util/path_utils.dart +++ b/pkg/linter/tool/util/path_utils.dart @@ -13,8 +13,10 @@ List get _packageRoot { while (parts.last != 'linter') { parts.removeLast(); if (parts.isEmpty) { - throw StateError("Script is not located inside a 'linter' directory? " - "'${Platform.script.path}'"); + throw StateError( + "Script is not located inside a 'linter' directory? " + "'${Platform.script.path}'", + ); } } return parts; From 0836d36dc7d074cdbfbd5a8795a6ba940c14156b Mon Sep 17 00:00:00 2001 From: Alexander Aprelev Date: Mon, 13 Jan 2025 13:04:42 -0800 Subject: [PATCH 15/76] [infra] Adjust build windows-arm64 split to avoid timeouts. Fixes https://ci.chromium.org/ui/p/dart/builders/ci.sandbox/pkg-win-release-arm64/3781. With new split the steps are distributed roughly like this: ``` $ RBE=0 tools/build.py -mrelease -ax64 gen_snapshot [982/982] LINK ./gen_snapshot The build took 39.285 seconds $ RBE=0 tools/build.py -mrelease -ax64 runtime/bin:dart runtime/bin:run_vm_tests [1392/1392] LINK ./run_vm_tests The build took 97.936 seconds $ RBE=0 tools/build.py -mrelease -ax64 runtime [1223/1223] ACTION //utils/kernel-service:frontend_server_aot_product(//build/toolchain/linux:clang_x64) The build took 97.168 seconds $ RBE=0 tools/build.py -mrelease -ax64 create_sdk ddc_stable_test [402/402] COPY gen/dart2js_aot_product.dart.snapshot dart-sdk/bin/snapshots/dart2js_aot.dart.snapshot The build took 100.373 seconds ``` Also add Ryan to the OWNERS_INFRA. Change-Id: Ibbf1a13ccd33d7bcb366ac864b05e960e5d73b8b Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404201 Commit-Queue: Alexander Aprelev Reviewed-by: Alexander Thomas --- tools/OWNERS_INFRA | 1 + tools/bots/test_matrix.json | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tools/OWNERS_INFRA b/tools/OWNERS_INFRA index dedb68b9ce9b..e82f681eaad4 100644 --- a/tools/OWNERS_INFRA +++ b/tools/OWNERS_INFRA @@ -1 +1,2 @@ athom@google.com +rmacnak@google.com diff --git a/tools/bots/test_matrix.json b/tools/bots/test_matrix.json index 851040962b63..5664b978800b 100644 --- a/tools/bots/test_matrix.json +++ b/tools/bots/test_matrix.json @@ -3203,14 +3203,29 @@ ] }, { - "name": "build dart - step 1 - divided to avoid timeout", + "name": "build dart - step 1 - gen-snapshot - divided to avoid timeout", + "script": "tools/build.py", + "arguments": [ + "gen_snapshot" + ] + }, + { + "name": "build dart - step 2 - runtime/bin:dart - divided to avoid timeout", + "script": "tools/build.py", + "arguments": [ + "runtime/bin:dart", + "runtime/bin:run_vm_tests" + ] + }, + { + "name": "build dart - step 3 - runtime - divided to avoid timeout", "script": "tools/build.py", "arguments": [ "runtime" ] }, { - "name": "build dart - step 2 - divided to avoid timeout", + "name": "build dart - step 4 - sdk, ddc_stable_test - divided to avoid timeout", "script": "tools/build.py", "arguments": [ "create_sdk", From ad481ff4b567dac66c6ae8c0d2967d46c58e1a2a Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 13:54:20 -0800 Subject: [PATCH 16/76] Elements. Add Element2.fragments Change-Id: I85fb19c87b833abca99cb86c4e285d9120f96ac2 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403948 Commit-Queue: Konstantin Shcheglov Reviewed-by: Brian Wilkerson --- .../domains/analysis/implemented_dart.dart | 1 - .../src/lsp/handlers/handler_references.dart | 1 - pkg/analyzer/lib/dart/element/element2.dart | 112 +++++ .../lib/src/dart/element/element.dart | 426 ++++++++++++++---- pkg/analyzer/lib/src/dart/element/member.dart | 70 +++ .../lib/src/utilities/extensions/element.dart | 20 - 6 files changed, 531 insertions(+), 99 deletions(-) diff --git a/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart b/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart index 4a991a717fce..063415104101 100644 --- a/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart +++ b/pkg/analysis_server/lib/src/domains/analysis/implemented_dart.dart @@ -5,7 +5,6 @@ import 'package:analysis_server/src/protocol_server.dart' as protocol; import 'package:analysis_server/src/services/search/search_engine.dart'; import 'package:analyzer/dart/element/element2.dart'; -import 'package:analyzer/src/utilities/extensions/element.dart'; class ImplementedComputer { final SearchEngine searchEngine; diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_references.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_references.dart index db25375189f4..740f61fa66e2 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/handler_references.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_references.dart @@ -15,7 +15,6 @@ import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/src/dart/ast/utilities.dart'; import 'package:analyzer/src/util/performance/operation_performance.dart'; -import 'package:analyzer/src/utilities/extensions/element.dart'; typedef StaticOptions = Either2; diff --git a/pkg/analyzer/lib/dart/element/element2.dart b/pkg/analyzer/lib/dart/element/element2.dart index 7c4c221889f6..3f36d780a1bf 100644 --- a/pkg/analyzer/lib/dart/element/element2.dart +++ b/pkg/analyzer/lib/dart/element/element2.dart @@ -111,6 +111,9 @@ abstract class Annotatable { abstract class BindPatternVariableElement2 implements PatternVariableElement2 { @override BindPatternVariableFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [BindPatternVariableElement2] contributed by a single @@ -138,6 +141,9 @@ abstract class ClassElement2 implements InterfaceElement2 { @override ClassFragment get firstFragment; + @override + List get fragments; + /// Whether the class or its superclass declares a non-final instance field. bool get hasNonFinalField; @@ -267,6 +273,9 @@ abstract class ConstructorElement2 @override ConstructorFragment get firstFragment; + @override + List get fragments; + /// Whether the constructor is a const constructor. bool get isConst; @@ -406,6 +415,9 @@ abstract class Element2 { /// invocations of [Fragment.nextFragment]. Fragment get firstFragment; + /// The fragments this element consists of. + List get fragments; + /// The unique integer identifier of this element. int get id; @@ -608,6 +620,9 @@ abstract class EnumElement2 implements InterfaceElement2 { @override EnumFragment get firstFragment; + + @override + List get fragments; } /// The portion of an [EnumElement2] contributed by a single declaration. @@ -638,6 +653,9 @@ abstract class ExecutableElement2 implements FunctionTypedElement2 { @override ExecutableFragment get firstFragment; + @override + List get fragments; + /// Whether the executable element did not have an explicit return type /// specified for it in the original source. bool get hasImplicitReturnType; @@ -712,6 +730,9 @@ abstract class ExtensionElement2 implements InstanceElement2 { @override ExtensionFragment get firstFragment; + + @override + List get fragments; } /// The portion of an [ExtensionElement2] contributed by a single @@ -736,6 +757,9 @@ abstract class ExtensionTypeElement2 implements InterfaceElement2 { @override ExtensionTypeFragment get firstFragment; + @override + List get fragments; + /// The primary constructor of this extension. ConstructorElement2 get primaryConstructor2; @@ -781,6 +805,9 @@ abstract class FieldElement2 implements PropertyInducingElement2 { @override FieldFragment get firstFragment; + @override + List get fragments; + /// Whether the field is abstract. /// /// Executable fields are abstract if they are declared with the `abstract` @@ -811,6 +838,9 @@ abstract class FieldFormalParameterElement2 implements FormalParameterElement { @override FieldFormalParameterFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [FieldFormalParameterElement2] contributed by a single @@ -868,6 +898,9 @@ abstract class FormalParameterElement /// formal parameter. List get formalParameters; + @override + List get fragments; + /// Whether the parameter has a default value. bool get hasDefaultValue; @@ -1051,6 +1084,9 @@ abstract class FunctionTypedElement2 implements TypeParameterizedElement2 { /// The formal parameters defined by this element. List get formalParameters; + @override + List get fragments; + /// The return type defined by this element. DartType get returnType; @@ -1081,6 +1117,9 @@ abstract class FunctionTypedFragment implements TypeParameterizedFragment { abstract class GenericFunctionTypeElement2 implements FunctionTypedElement2 { @override GenericFunctionTypeFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [GenericFunctionTypeElement2] coming from a single @@ -1117,6 +1156,9 @@ abstract class GetterElement implements PropertyAccessorElement2 { @override GetterFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [GetterElement] contributed by a single declaration. @@ -1183,6 +1225,9 @@ abstract class InstanceElement2 @override InstanceFragment get firstFragment; + @override + List get fragments; + /// The getters declared in this element. List get getters2; @@ -1297,6 +1342,9 @@ abstract class InterfaceElement2 implements InstanceElement2 { @override InterfaceFragment get firstFragment; + @override + List get fragments; + /// The interfaces that are implemented by this class. /// /// Note: Because the element model represents the state of the code, @@ -1437,6 +1485,9 @@ abstract class JoinPatternVariableElement2 implements PatternVariableElement2 { @override JoinPatternVariableFragment get firstFragment; + @override + List get fragments; + /// Whether the [variables2] are consistent. /// /// The variables are consistent if they are present in all branches, and have @@ -1482,6 +1533,9 @@ abstract class LabelElement2 implements Element2 { @override LabelFragment get firstFragment; + @override + List get fragments; + @override LibraryElement2 get library2; } @@ -1562,6 +1616,7 @@ abstract class LibraryElement2 /// /// This includes the defining fragment, and fragments included using the /// `part` directive. + @override List get fragments; /// The getters defined in this library. @@ -1826,6 +1881,9 @@ abstract class LocalFunctionElement implements ExecutableElement2, LocalElement2 { @override LocalFunctionFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [LocalFunctionElement] contributed by a single @@ -1864,6 +1922,9 @@ abstract class LocalVariableElement2 @override LocalVariableFragment get firstFragment; + @override + List get fragments; + /// Whether the variable has an initializer at declaration. bool get hasInitializer; } @@ -2012,6 +2073,9 @@ abstract class MethodElement2 @override MethodFragment get firstFragment; + @override + List get fragments; + /// Whether the method defines an operator. /// /// The test might be based on the name of the executable element, in which @@ -2043,6 +2107,9 @@ abstract class MixinElement2 implements InterfaceElement2 { @override MixinFragment get firstFragment; + @override + List get fragments; + /// Whether the mixin is a base mixin. /// /// A mixin is a base mixin if it has an explicit `base` modifier. @@ -2105,6 +2172,9 @@ abstract class MultiplyDefinedElement2 implements Element2 { @override MultiplyDefinedFragment get firstFragment; + + @override + List get fragments; } /// The fragment for a [MultiplyDefinedElement2]. @@ -2139,6 +2209,9 @@ abstract class PatternVariableElement2 implements LocalVariableElement2 { @override PatternVariableFragment get firstFragment; + @override + List get fragments; + /// The variable in which this variable joins with other pattern variables /// with the same name, in a logical-or pattern, or shared case scope. JoinPatternVariableElement2? get join2; @@ -2175,6 +2248,9 @@ abstract class PrefixElement2 implements Element2 { @override PrefixFragment get firstFragment; + @override + List get fragments; + /// The imports that share this prefix. List get imports; @@ -2216,6 +2292,9 @@ abstract class PrefixFragment implements Fragment { abstract class PromotableElement2 implements VariableElement2 { @override PromotableFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [PromotableElement2] contributed by a single declaration. @@ -2246,6 +2325,9 @@ abstract class PropertyAccessorElement2 implements ExecutableElement2 { @override PropertyAccessorFragment get firstFragment; + @override + List get fragments; + /// The field or top-level variable associated with this getter. /// /// If this getter was explicitly defined (is not synthetic) then the variable @@ -2295,6 +2377,9 @@ abstract class PropertyInducingElement2 @override PropertyInducingFragment get firstFragment; + @override + List get fragments; + /// The getter associated with this variable. /// /// If this variable was explicitly defined (is not synthetic) then the @@ -2389,6 +2474,9 @@ abstract class SetterElement implements PropertyAccessorElement2 { @override SetterFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [SetterElement] contributed by a single declaration. @@ -2426,6 +2514,9 @@ abstract class SuperFormalParameterElement2 implements FormalParameterElement { @override SuperFormalParameterFragment get firstFragment; + @override + List get fragments; + /// The associated super-constructor parameter, from the super-constructor /// that is referenced by the implicit or explicit super-constructor /// invocation. @@ -2461,6 +2552,9 @@ abstract class TopLevelFunctionElement @override TopLevelFunctionFragment get firstFragment; + @override + List get fragments; + /// Whether the function represents `identical` from the `dart:core` library. bool get isDartCoreIdentical; @@ -2504,6 +2598,9 @@ abstract class TopLevelVariableElement2 implements PropertyInducingElement2 { @override TopLevelVariableFragment get firstFragment; + @override + List get fragments; + /// Whether the field was explicitly marked as being external. bool get isExternal; } @@ -2550,6 +2647,9 @@ abstract class TypeAliasElement2 @override TypeAliasFragment get firstFragment; + @override + List get fragments; + /// Returns the type resulting from instantiating this typedef with the given /// [typeArguments] and [nullabilitySuffix]. /// @@ -2593,6 +2693,9 @@ abstract class TypeDefiningElement2 implements Element2, Annotatable { @override TypeDefiningFragment get firstFragment; + + @override + List get fragments; } /// The portion of a [TypeDefiningElement2] contributed by a single declaration. @@ -2626,6 +2729,9 @@ abstract class TypeParameterElement2 implements TypeDefiningElement2 { @override TypeParameterFragment get firstFragment; + @override + List get fragments; + /// Returns the [TypeParameterType] with the given [nullabilitySuffix] for /// this type parameter. TypeParameterType instantiate({ @@ -2655,6 +2761,9 @@ abstract class TypeParameterizedElement2 implements Element2, Annotatable { @override TypeParameterizedFragment get firstFragment; + @override + List get fragments; + /// If the element defines a type, indicates whether the type may safely /// appear without explicit type arguments as the bounds of a type parameter /// declaration. @@ -2702,6 +2811,9 @@ abstract class VariableElement2 implements Element2 { @override VariableFragment get firstFragment; + @override + List get fragments; + /// Whether the variable element did not have an explicit type specified /// for it. bool get hasImplicitType; diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index 2a3a50483d54..1b1a08c6818e 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -127,12 +127,12 @@ class BindPatternVariableElementImpl extends PatternVariableElementImpl super.element as BindPatternVariableElementImpl2; @override - BindPatternVariableFragment? get nextFragment => - super.nextFragment as BindPatternVariableFragment?; + BindPatternVariableElementImpl? get nextFragment => + super.nextFragment as BindPatternVariableElementImpl?; @override - BindPatternVariableFragment? get previousFragment => - super.previousFragment as BindPatternVariableFragment?; + BindPatternVariableElementImpl? get previousFragment => + super.previousFragment as BindPatternVariableElementImpl?; } class BindPatternVariableElementImpl2 extends PatternVariableElementImpl2 @@ -140,8 +140,18 @@ class BindPatternVariableElementImpl2 extends PatternVariableElementImpl2 BindPatternVariableElementImpl2(super._wrappedElement); @override - BindPatternVariableFragment get firstFragment => - super.firstFragment as BindPatternVariableFragment; + BindPatternVariableElementImpl get firstFragment => + super.firstFragment as BindPatternVariableElementImpl; + + @override + List get fragments { + return [ + for (BindPatternVariableElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } /// This flag is set to `true` if this variable clashes with another /// pattern variable with the same name within the same pattern. @@ -653,6 +663,16 @@ class ClassElementImpl2 extends InterfaceElementImpl2 firstFragment.augmentedInternal = this; } + @override + List get fragments { + return [ + for (ClassElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get hasNonFinalField => firstFragment.hasNonFinalField; @@ -1520,7 +1540,7 @@ class ConstructorElementImpl extends ExecutableElementImpl } @override - ConstructorFragment? get nextFragment => augmentation; + ConstructorElementImpl? get nextFragment => augmentation; @override Element get nonSynthetic { @@ -1625,7 +1645,7 @@ class ConstructorElementImpl2 extends ExecutableElementImpl2 ConstructorElementImpl? fragment = firstFragment; while (fragment != null) { fragment.element = this; - fragment = fragment.nextFragment as ConstructorElementImpl?; + fragment = fragment.nextFragment; } } @@ -1647,6 +1667,16 @@ class ConstructorElementImpl2 extends ExecutableElementImpl2 InterfaceElementImpl2 get enclosingElement2 => firstFragment.enclosingElement3.element; + @override + List get fragments { + return [ + for (ConstructorElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isConst => firstFragment.isConst; @@ -2067,6 +2097,16 @@ class DynamicElementImpl2 extends TypeDefiningElementImpl2 { @override DynamicElementImpl get firstFragment => DynamicElementImpl.instance; + @override + List get fragments { + return [ + for (DynamicElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isSynthetic => true; @@ -2614,6 +2654,16 @@ abstract class ElementImpl implements Element, Element2 { throw UnimplementedError('This is a fragment'); } + @override + List get fragments { + return [ + for (Fragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get hasAlwaysThrows { var metadata = this.metadata; @@ -3312,6 +3362,16 @@ abstract class ElementImpl2 implements Element2 { // TODO(augmentations): implement enclosingElement2 Element2? get enclosingElement2 => throw UnimplementedError(); + @override + List get fragments { + return [ + for (Fragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + /// Return an identifier that uniquely identifies this element among the /// children of this element's parent. String get identifier { @@ -3587,10 +3647,11 @@ class EnumElementImpl extends InterfaceElementImpl ElementKind get kind => ElementKind.ENUM; @override - EnumFragment? get nextFragment => super.nextFragment as EnumFragment?; + EnumElementImpl? get nextFragment => super.nextFragment as EnumElementImpl?; @override - EnumFragment? get previousFragment => super.previousFragment as EnumFragment?; + EnumElementImpl? get previousFragment => + super.previousFragment as EnumElementImpl?; ConstFieldElementImpl? get valuesField { for (var field in fields) { @@ -3636,6 +3697,16 @@ class EnumElementImpl2 extends InterfaceElementImpl2 List get constants2 => constants.map((e) => e.asElement2).toList(); + @override + List get fragments { + return [ + for (EnumElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override T? accept2(ElementVisitor2 visitor) { return visitor.visitEnumElement(this); @@ -3935,12 +4006,12 @@ class ExtensionElementImpl extends InstanceElementImpl } @override - ExtensionFragment? get nextFragment => - super.nextFragment as ExtensionFragment?; + ExtensionElementImpl? get nextFragment => + super.nextFragment as ExtensionElementImpl?; @override - ExtensionFragment? get previousFragment => - super.previousFragment as ExtensionFragment?; + ExtensionElementImpl? get previousFragment => + super.previousFragment as ExtensionElementImpl?; @override DartType get thisType => extendedType; @@ -4011,6 +4082,16 @@ class ExtensionElementImpl2 extends InstanceElementImpl2 firstFragment.augmentedInternal = this; } + @override + List get fragments { + return [ + for (ExtensionElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override DartType get thisType => extendedType; @@ -4057,12 +4138,12 @@ class ExtensionTypeElementImpl extends InterfaceElementImpl } @override - ExtensionTypeFragment? get nextFragment => - super.nextFragment as ExtensionTypeFragment?; + ExtensionTypeElementImpl? get nextFragment => + super.nextFragment as ExtensionTypeElementImpl?; @override - ExtensionTypeFragment? get previousFragment => - super.previousFragment as ExtensionTypeFragment?; + ExtensionTypeElementImpl? get previousFragment => + super.previousFragment as ExtensionTypeElementImpl?; @override ConstructorElementImpl get primaryConstructor { @@ -4119,6 +4200,16 @@ class ExtensionTypeElementImpl2 extends InterfaceElementImpl2 firstFragment.augmentedInternal = this; } + @override + List get fragments { + return [ + for (ExtensionTypeElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override ConstructorElement2 get primaryConstructor2 => primaryConstructor.element; @@ -4234,11 +4325,11 @@ class FieldElementImpl extends PropertyInducingElementImpl } @override - FieldFragment? get nextFragment => super.nextFragment as FieldFragment?; + FieldElementImpl? get nextFragment => super.nextFragment as FieldElementImpl?; @override - FieldFragment? get previousFragment => - super.previousFragment as FieldFragment?; + FieldElementImpl? get previousFragment => + super.previousFragment as FieldElementImpl?; @override T? accept(ElementVisitor visitor) => visitor.visitFieldElement(this); @@ -4257,7 +4348,7 @@ class FieldElementImpl2 extends PropertyInducingElementImpl2 FieldElementImpl? fragment = firstFragment; while (fragment != null) { fragment.element = this; - fragment = fragment.nextFragment as FieldElementImpl?; + fragment = fragment.nextFragment; } } @@ -4268,6 +4359,16 @@ class FieldElementImpl2 extends PropertyInducingElementImpl2 InstanceElement2 get enclosingElement2 => (firstFragment._enclosingElement3 as InstanceFragment).element; + @override + List get fragments { + return [ + for (FieldElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override GetterElement? get getter2 => firstFragment.getter?.element as GetterElement?; @@ -4359,12 +4460,12 @@ class FieldFormalParameterElementImpl extends ParameterElementImpl bool get isInitializingFormal => true; @override - FieldFormalParameterFragment? get nextFragment => - super.nextFragment as FieldFormalParameterFragment?; + FieldFormalParameterElementImpl? get nextFragment => + super.nextFragment as FieldFormalParameterElementImpl?; @override - FieldFormalParameterFragment? get previousFragment => - super.previousFragment as FieldFormalParameterFragment?; + FieldFormalParameterElementImpl? get previousFragment => + super.previousFragment as FieldFormalParameterElementImpl?; @override T? accept(ElementVisitor visitor) => @@ -4387,8 +4488,18 @@ class FieldFormalParameterElementImpl2 extends FormalParameterElementImpl }; @override - FieldFormalParameterFragment get firstFragment => - super.firstFragment as FieldFormalParameterFragment; + FieldFormalParameterElementImpl get firstFragment => + super.firstFragment as FieldFormalParameterElementImpl; + + @override + List get fragments { + return [ + for (FieldFormalParameterElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } } class FormalParameterElementImpl extends PromotableElementImpl2 @@ -4405,7 +4516,7 @@ class FormalParameterElementImpl extends PromotableElementImpl2 ParameterElementImpl? fragment = wrappedElement; while (fragment != null) { fragment.element = this; - fragment = fragment.nextFragment as ParameterElementImpl?; + fragment = fragment.nextFragment; } } @@ -4417,8 +4528,7 @@ class FormalParameterElementImpl extends PromotableElementImpl2 String? get defaultValueCode => wrappedElement.defaultValueCode; @override - FormalParameterFragment get firstFragment => - wrappedElement as FormalParameterFragment; + ParameterElementImpl get firstFragment => wrappedElement; @override // TODO(augmentations): Implement the merge of formal parameters. @@ -4426,6 +4536,16 @@ class FormalParameterElementImpl extends PromotableElementImpl2 .map((fragment) => (fragment as ParameterElementImpl).element) .toList(); + @override + List get fragments { + return [ + for (ParameterElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override // TODO(augmentations): Implement the merge of formal parameters. bool get hasDefaultValue => wrappedElement.hasDefaultValue; @@ -5100,10 +5220,10 @@ class FunctionElementImpl extends ExecutableElementImpl ElementKind get kind => ElementKind.FUNCTION; @override - ExecutableFragment? get nextFragment => augmentation; + FunctionElementImpl? get nextFragment => augmentation; @override - ExecutableFragment? get previousFragment => augmentationTarget; + FunctionElementImpl? get previousFragment => augmentationTarget; @override bool get _includeNameOffsetInIdentifier { @@ -5203,7 +5323,7 @@ class GenericFunctionTypeElementImpl extends _ExistingElementImpl int? get nameOffset2 => null; @override - GenericFunctionTypeFragment? get nextFragment => null; + GenericFunctionTypeElementImpl? get nextFragment => null; @override List get parameters { @@ -5220,7 +5340,7 @@ class GenericFunctionTypeElementImpl extends _ExistingElementImpl } @override - GenericFunctionTypeFragment? get previousFragment => null; + GenericFunctionTypeElementImpl? get previousFragment => null; @override DartType get returnType { @@ -5277,7 +5397,7 @@ class GenericFunctionTypeElementImpl2 extends FunctionTypedElementImpl2 String? get documentationComment => _wrappedElement.documentationComment; @override - GenericFunctionTypeFragment get firstFragment => _wrappedElement; + GenericFunctionTypeElementImpl get firstFragment => _wrappedElement; @override List get formalParameters => @@ -5285,6 +5405,16 @@ class GenericFunctionTypeElementImpl2 extends FunctionTypedElementImpl2 .map((fragment) => fragment.element) .toList(); + @override + List get fragments { + return [ + for (GenericFunctionTypeElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isSimplyBounded => _wrappedElement.isSimplyBounded; @@ -5337,7 +5467,7 @@ class GetterElementImpl extends PropertyAccessorElementImpl2 PropertyAccessorElementImpl? fragment = firstFragment; while (fragment != null) { fragment.element = this; - fragment = fragment.nextFragment as PropertyAccessorElementImpl?; + fragment = fragment.nextFragment; } } @@ -5348,6 +5478,16 @@ class GetterElementImpl extends PropertyAccessorElementImpl2 SetterElement? get correspondingSetter2 => firstFragment.correspondingSetter2?.element as SetterElement?; + @override + List get fragments { + return [ + for (PropertyAccessorElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override ElementKind get kind => ElementKind.GETTER; @@ -6580,12 +6720,12 @@ class JoinPatternVariableElementImpl extends PatternVariableElementImpl } @override - JoinPatternVariableFragment? get nextFragment => - super.nextFragment as JoinPatternVariableFragment?; + JoinPatternVariableElementImpl? get nextFragment => + super.nextFragment as JoinPatternVariableElementImpl?; @override - JoinPatternVariableFragment? get previousFragment => - super.previousFragment as JoinPatternVariableFragment?; + JoinPatternVariableElementImpl? get previousFragment => + super.previousFragment as JoinPatternVariableElementImpl?; /// Returns this variable, and variables that join into it. List get transitiveVariables { @@ -6614,8 +6754,18 @@ class JoinPatternVariableElementImpl2 extends PatternVariableElementImpl2 JoinPatternVariableElementImpl2(super._wrappedElement); @override - JoinPatternVariableFragment get firstFragment => - super.firstFragment as JoinPatternVariableFragment; + JoinPatternVariableElementImpl get firstFragment => + super.firstFragment as JoinPatternVariableElementImpl; + + @override + List get fragments { + return [ + for (JoinPatternVariableElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } shared.JoinedPatternVariableInconsistency get inconsistency => _wrappedElement.inconsistency; @@ -6705,10 +6855,10 @@ class LabelElementImpl extends ElementImpl int? get nameOffset2 => nameOffset; @override - LabelFragment? get nextFragment => null; + LabelElementImpl? get nextFragment => null; @override - LabelFragment? get previousFragment => null; + LabelElementImpl? get previousFragment => null; @override T? accept(ElementVisitor visitor) => visitor.visitLabelElement(this); @@ -6729,7 +6879,12 @@ class LabelElementImpl2 extends ElementImpl2 ExecutableElement2? get enclosingElement2 => null; @override - LabelFragment get firstFragment => _wrappedElement; + LabelElementImpl get firstFragment => _wrappedElement; + + @override + List get fragments { + return [firstFragment]; + } @override LibraryElement2 get library2 { @@ -7467,6 +7622,16 @@ class LocalFunctionElementImpl extends ExecutableElementImpl2 .map((fragment) => fragment.element) .toList(); + @override + List get fragments { + return [ + for (FunctionElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get hasImplicitReturnType => _wrappedElement.hasImplicitReturnType; @@ -7569,10 +7734,10 @@ class LocalVariableElementImpl extends NonParameterVariableElementImpl int? get nameOffset2 => nameOffset; @override - LocalVariableFragment? get nextFragment => null; + LocalVariableElementImpl? get nextFragment => null; @override - LocalVariableFragment? get previousFragment => null; + LocalVariableElementImpl? get previousFragment => null; @override T? accept(ElementVisitor visitor) => @@ -7594,7 +7759,12 @@ class LocalVariableElementImpl2 extends PromotableElementImpl2 String? get documentationComment => null; @override - LocalVariableFragment get firstFragment => _wrappedElement; + LocalVariableElementImpl get firstFragment => _wrappedElement; + + @override + List get fragments { + return [firstFragment]; + } @override bool get hasImplicitType => _wrappedElement.hasImplicitType; @@ -8119,7 +8289,7 @@ class MethodElementImpl extends ExecutableElementImpl } @override - MethodFragment? get nextFragment => augmentation; + MethodElementImpl? get nextFragment => augmentation; @override Element get nonSynthetic { @@ -8130,7 +8300,7 @@ class MethodElementImpl extends ExecutableElementImpl } @override - MethodFragment? get previousFragment => augmentationTarget; + MethodElementImpl? get previousFragment => augmentationTarget; @override T? accept(ElementVisitor visitor) => visitor.visitMethodElement(this); @@ -8166,6 +8336,16 @@ class MethodElementImpl2 extends ExecutableElementImpl2 Element2? get enclosingElement2 => (firstFragment._enclosingElement3 as InstanceFragment).element; + @override + List get fragments { + return [ + for (MethodElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isOperator => firstFragment.isOperator; @@ -8241,11 +8421,11 @@ class MixinElementImpl extends ClassOrMixinElementImpl } @override - MixinFragment? get nextFragment => super.nextFragment as MixinFragment?; + MixinElementImpl? get nextFragment => super.nextFragment as MixinElementImpl?; @override - MixinFragment? get previousFragment => - super.previousFragment as MixinFragment?; + MixinElementImpl? get previousFragment => + super.previousFragment as MixinElementImpl?; @override List get superclassConstraints { @@ -8300,6 +8480,16 @@ class MixinElementImpl2 extends InterfaceElementImpl2 firstFragment.augmentedInternal = this; } + @override + List get fragments { + return [ + for (MixinElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isBase => firstFragment.isBase; @@ -8714,7 +8904,8 @@ class MultiplyDefinedElementImpl2 extends ElementImpl2 final List conflictingElements2; @override - late final firstFragment = MultiplyDefinedFragmentImpl(this); + late final MultiplyDefinedFragmentImpl firstFragment = + MultiplyDefinedFragmentImpl(this); MultiplyDefinedElementImpl2( this.libraryFragment, @@ -8742,6 +8933,11 @@ class MultiplyDefinedElementImpl2 extends ElementImpl2 @override Null get enclosingElement2 => null; + @override + List get fragments { + return [firstFragment]; + } + @override bool get isPrivate => false; @@ -8945,6 +9141,11 @@ class NeverElementImpl2 extends TypeDefiningElementImpl2 { @override NeverElementImpl get firstFragment => NeverElementImpl.instance; + @override + List get fragments { + return [firstFragment]; + } + @override bool get isSynthetic => true; @@ -9136,7 +9337,7 @@ class ParameterElementImpl extends VariableElementImpl @override // TODO(augmentations): Support chaining between the fragments. - FormalParameterFragment? get nextFragment => null; + ParameterElementImpl? get nextFragment => null; @override List get parameters { @@ -9154,7 +9355,7 @@ class ParameterElementImpl extends VariableElementImpl @override // TODO(augmentations): Support chaining between the fragments. - FormalParameterFragment? get previousFragment => null; + ParameterElementImpl? get previousFragment => null; @override List get typeParameters { @@ -9365,12 +9566,12 @@ class PatternVariableElementImpl extends LocalVariableElementImpl JoinPatternVariableFragment? get join2 => join; @override - PatternVariableFragment? get nextFragment => - super.nextFragment as PatternVariableFragment?; + PatternVariableElementImpl? get nextFragment => + super.nextFragment as PatternVariableElementImpl?; @override - PatternVariableFragment? get previousFragment => - super.previousFragment as PatternVariableFragment?; + PatternVariableElementImpl? get previousFragment => + super.previousFragment as PatternVariableElementImpl?; /// Return the root [join], or self. PatternVariableElementImpl get rootVariable { @@ -9383,8 +9584,18 @@ class PatternVariableElementImpl2 extends LocalVariableElementImpl2 PatternVariableElementImpl2(super._wrappedElement); @override - PatternVariableFragment get firstFragment => - super.firstFragment as PatternVariableFragment; + PatternVariableElementImpl get firstFragment => + super.firstFragment as PatternVariableElementImpl; + + @override + List get fragments { + return [ + for (PatternVariableElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } /// This flag is set to `true` while we are visiting the [WhenClause] of /// the [GuardedPattern] that declares this variable. @@ -9500,6 +9711,7 @@ class PrefixElementImpl2 extends ElementImpl2 implements PrefixElement2 { @override Null get enclosingElement2 => null; + @override List get fragments { return [ for (PrefixFragmentImpl? fragment = firstFragment; @@ -9690,7 +9902,7 @@ class PropertyAccessorElementImpl extends ExecutableElementImpl PropertyAccessorElementImpl firstFragment = this; var previousFragment = firstFragment.previousFragment; while (previousFragment != null) { - firstFragment = previousFragment as PropertyAccessorElementImpl; + firstFragment = previousFragment; previousFragment = firstFragment.previousFragment; } // As a side-effect of creating the element, all of the fragments in the @@ -9770,10 +9982,10 @@ class PropertyAccessorElementImpl extends ExecutableElementImpl } @override - PropertyAccessorFragment? get nextFragment => augmentation; + PropertyAccessorElementImpl? get nextFragment => augmentation; @override - PropertyAccessorFragment? get previousFragment => augmentationTarget; + PropertyAccessorElementImpl? get previousFragment => augmentationTarget; @override PropertyInducingElementImpl? get variable2 { @@ -10185,7 +10397,7 @@ class SetterElementImpl extends PropertyAccessorElementImpl2 PropertyAccessorElementImpl? fragment = firstFragment; while (fragment != null) { fragment.element = this; - fragment = fragment.nextFragment as PropertyAccessorElementImpl?; + fragment = fragment.nextFragment; } } @@ -10199,6 +10411,16 @@ class SetterElementImpl extends PropertyAccessorElementImpl2 @override Element2? get enclosingElement2 => firstFragment.enclosingFragment?.element; + @override + List get fragments { + return [ + for (PropertyAccessorElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override ElementKind get kind => ElementKind.SETTER; @@ -10283,12 +10505,12 @@ class SuperFormalParameterElementImpl extends ParameterElementImpl bool get isSuperFormal => true; @override - SuperFormalParameterFragment? get nextFragment => - super.nextFragment as SuperFormalParameterFragment?; + SuperFormalParameterElementImpl? get nextFragment => + super.nextFragment as SuperFormalParameterElementImpl?; @override - SuperFormalParameterFragment? get previousFragment => - super.previousFragment as SuperFormalParameterFragment?; + SuperFormalParameterElementImpl? get previousFragment => + super.previousFragment as SuperFormalParameterElementImpl?; @override ParameterElement? get superConstructorParameter { @@ -10339,6 +10561,16 @@ class SuperFormalParameterElementImpl2 extends FormalParameterElementImpl SuperFormalParameterElementImpl get firstFragment => super.firstFragment as SuperFormalParameterElementImpl; + @override + List get fragments { + return [ + for (SuperFormalParameterElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override FormalParameterElement? get superConstructorParameter2 { return firstFragment.superConstructorParameter?.asElement2; @@ -10379,6 +10611,16 @@ class TopLevelFunctionElementImpl extends ExecutableElementImpl2 @override Element2? get enclosingElement2 => firstFragment._enclosingElement3?.library2; + @override + List get fragments { + return [ + for (FunctionElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isDartCoreIdentical => firstFragment.isDartCoreIdentical; @@ -10444,12 +10686,12 @@ class TopLevelVariableElementImpl extends PropertyInducingElementImpl } @override - TopLevelVariableFragment? get nextFragment => - super.nextFragment as TopLevelVariableFragment?; + TopLevelVariableElementImpl? get nextFragment => + super.nextFragment as TopLevelVariableElementImpl?; @override - TopLevelVariableFragment? get previousFragment => - super.previousFragment as TopLevelVariableFragment?; + TopLevelVariableElementImpl? get previousFragment => + super.previousFragment as TopLevelVariableElementImpl?; @override T? accept(ElementVisitor visitor) => @@ -10480,6 +10722,16 @@ class TopLevelVariableElementImpl2 extends PropertyInducingElementImpl2 LibraryElement2 get enclosingElement2 => firstFragment.library as LibraryElement2; + @override + List get fragments { + return [ + for (TopLevelVariableElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override GetterElement? get getter2 => firstFragment.getter2?.element as GetterElement?; @@ -10662,11 +10914,11 @@ class TypeAliasElementImpl extends _ExistingElementImpl @override // TODO(augmentations): Support the fragment chain. - TypeAliasFragment? get nextFragment => null; + TypeAliasElementImpl? get nextFragment => null; @override // TODO(augmentations): Support the fragment chain. - TypeAliasFragment? get previousFragment => null; + TypeAliasElementImpl? get previousFragment => null; /// Instantiates this type alias with its type parameters as arguments. DartType get rawType { @@ -10816,6 +11068,16 @@ class TypeAliasElementImpl2 extends TypeDefiningElementImpl2 LibraryElement2 get enclosingElement2 => firstFragment.library as LibraryElement2; + @override + List get fragments { + return [ + for (TypeAliasElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isSimplyBounded => firstFragment.isSimplyBounded; @@ -11073,6 +11335,16 @@ class TypeParameterElementImpl2 extends TypeDefiningElementImpl2 @override DartType? get boundShared => bound; + @override + List get fragments { + return [ + for (TypeParameterElementImpl? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + bool get isLegacyCovariant => firstFragment.isLegacyCovariant; @override diff --git a/pkg/analyzer/lib/src/dart/element/member.dart b/pkg/analyzer/lib/src/dart/element/member.dart index 36334fa90563..70163ae70812 100644 --- a/pkg/analyzer/lib/src/dart/element/member.dart +++ b/pkg/analyzer/lib/src/dart/element/member.dart @@ -61,6 +61,16 @@ class ConstructorMember extends ExecutableMember @override ConstructorFragment get firstFragment => _element2.firstFragment; + @override + List get fragments { + return [ + for (ConstructorFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get isConst => declaration.isConst; @@ -228,6 +238,16 @@ abstract class ExecutableMember extends Member List get formalParameters => parameters.map((fragment) => fragment.asElement2).toList(); + @override + List get fragments { + return [ + for (ExecutableFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get hasImplicitReturnType => declaration.hasImplicitReturnType; @@ -519,6 +539,16 @@ class FieldMember extends VariableMember @override FieldFragment get firstFragment => _element2.firstFragment; + @override + List get fragments { + return [ + for (FieldFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override PropertyAccessorElement? get getter { var baseGetter = declaration.getter; @@ -707,6 +737,16 @@ class GetterMember extends PropertyAccessorMember implements GetterElement { @override GetterFragment get firstFragment => _element2.firstFragment; + @override + List get fragments { + return [ + for (GetterFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment as GetterFragment?) + fragment, + ]; + } + @override String? get lookupName => _element2.lookupName; @@ -1014,6 +1054,16 @@ class MethodMember extends ExecutableMember @override MethodFragment get firstFragment => _element2.firstFragment; + @override + List get fragments { + return [ + for (MethodFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override LibraryElement2 get library2 => _element2.library2; @@ -1145,6 +1195,16 @@ class ParameterMember extends VariableMember List get formalParameters => _element2.formalParameters; + @override + List get fragments { + return [ + for (FormalParameterFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment) + fragment, + ]; + } + @override bool get hasDefaultValue => declaration.hasDefaultValue; @@ -1431,6 +1491,16 @@ class SetterMember extends PropertyAccessorMember implements SetterElement { @override SetterFragment get firstFragment => _element2.firstFragment; + @override + List get fragments { + return [ + for (SetterFragment? fragment = firstFragment; + fragment != null; + fragment = fragment.nextFragment as SetterFragment?) + fragment, + ]; + } + @override String? get lookupName => _element2.lookupName; diff --git a/pkg/analyzer/lib/src/utilities/extensions/element.dart b/pkg/analyzer/lib/src/utilities/extensions/element.dart index d234639f6a4a..8ffcc2bd9b42 100644 --- a/pkg/analyzer/lib/src/utilities/extensions/element.dart +++ b/pkg/analyzer/lib/src/utilities/extensions/element.dart @@ -25,17 +25,6 @@ extension ClassElementExtension on ClassElement { } } -extension ClassElementImpl2Extension on ClassElementImpl2 { - List get fragments { - return [ - for (ClassElementImpl? fragment = firstFragment; - fragment != null; - fragment = fragment.nextFragment) - fragment, - ]; - } -} - extension CompilationUnitElementExtension on CompilationUnitElement { LibraryFragment get asElement2 { return this as LibraryFragment; @@ -77,15 +66,6 @@ extension ConstructorElementExtension on ConstructorElement { } extension Element2Extension on Element2 { - List get fragments { - return [ - for (Fragment? fragment = firstFragment; - fragment != null; - fragment = fragment.nextFragment) - fragment, - ]; - } - /// Whether the element is effectively [internal]. bool get isInternal { if (this case Annotatable annotatable) { From 106d3a61b877e9291575e829cb75acd8a90c7a3a Mon Sep 17 00:00:00 2001 From: Mayank Patke Date: Mon, 13 Jan 2025 14:07:52 -0800 Subject: [PATCH 17/76] [DEPS] Restore Firefox/JSC to 133.0 to avoid breaking wasm tests Change-Id: I19f44c656023b6940cd8161ea5b367ec56fa9845 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403947 Reviewed-by: Sigmund Cherem Auto-Submit: Mayank Patke Commit-Queue: Mayank Patke --- DEPS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DEPS b/DEPS index 05af62964bf5..49296040dba5 100644 --- a/DEPS +++ b/DEPS @@ -72,7 +72,7 @@ vars = { # instructions. d8, the V8 shell, is always checked out. "checkout_javascript_engines": False, "d8_tag": "version:13.4.32", - "jsshell_tag": "version:134.0", + "jsshell_tag": "version:133.0", "jsc_tag": "version:288804", # https://chrome-infra-packages.appspot.com/p/fuchsia/third_party/clang @@ -182,7 +182,7 @@ vars = { "download_chrome": False, "chrome_tag": "132.0.6834.83", "download_firefox": False, - "firefox_tag": "134.0", + "firefox_tag": "133.0.3", # Emscripten is used in dart2wasm tests. "download_emscripten": False, From c988e32a56dfb1af85d3b7b901906f0b6ba541a6 Mon Sep 17 00:00:00 2001 From: pq Date: Mon, 13 Jan 2025 15:05:28 -0800 Subject: [PATCH 18/76] [cq] remove unnecessary ignores See: https://github.com/dart-lang/sdk/issues/35234 Change-Id: I4563df48df9d71332b3de6fabea9176e199c1ad5 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404202 Reviewed-by: Brian Wilkerson Auto-Submit: Phil Quitslund Commit-Queue: Phil Quitslund --- .../fix/data_driven/code_fragment_parser.dart | 1 - .../fix/data_driven/transform_set_parser.dart | 1 - .../test/lsp/flutter_outline_test.dart | 1 - pkg/analysis_server/test/lsp/server_abstract.dart | 1 - .../test/src/plugin_server_error_test.dart | 1 - .../src/generated/testing/test_type_provider.dart | 2 -- .../src/summary2/kernel_compilation_service.dart | 2 -- pkg/analyzer/lib/src/summary2/macro.dart | 2 -- .../change_builder/change_builder_dart_test.dart | 2 -- pkg/linter/lib/src/analyzer.dart | 2 -- .../src/rules/package_prefixed_library_names.dart | 1 - pkg/linter/lib/src/rules/prefer_is_empty.dart | 1 - pkg/linter/test/rules/use_enums_test.dart | 1 - pkg/linter/tool/checks/driver.dart | 13 +++++++------ pkg/linter/tool/util/lint_driver.dart | 3 --- 15 files changed, 7 insertions(+), 27 deletions(-) diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart index cfc452485788..a15c765da9e4 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/code_fragment_parser.dart @@ -11,7 +11,6 @@ import 'package:analyzer/error/listener.dart'; import 'package:analyzer/src/utilities/extensions/string.dart'; // Several "report" functions intentionally return a `Null`-typed value. -// ignore_for_file: prefer_void_to_null /// A parser for the textual representation of a code fragment. class CodeFragmentParser { diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart index 0b6dc567035c..536b684b3086 100644 --- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart +++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/transform_set_parser.dart @@ -27,7 +27,6 @@ import 'package:collection/collection.dart'; import 'package:yaml/yaml.dart'; // Several "report" functions intentionally return a `Null`-typed value. -// ignore_for_file: prefer_void_to_null /// Information used to report errors when translating a node. class ErrorContext { diff --git a/pkg/analysis_server/test/lsp/flutter_outline_test.dart b/pkg/analysis_server/test/lsp/flutter_outline_test.dart index 105c18ee2ad5..3e076a06ff07 100644 --- a/pkg/analysis_server/test/lsp/flutter_outline_test.dart +++ b/pkg/analysis_server/test/lsp/flutter_outline_test.dart @@ -30,7 +30,6 @@ class FlutterOutlineNonFlutterProjectTest // Wait up to 1sec to ensure no error/log notifications were sent back. var didTimeout = false; var outlineNotification = waitForFlutterOutline(mainFileUri) - // ignore: unnecessary_cast .then((outline) => outline as FlutterOutline?) .timeout( const Duration(seconds: 1), diff --git a/pkg/analysis_server/test/lsp/server_abstract.dart b/pkg/analysis_server/test/lsp/server_abstract.dart index ca6b503458a4..d0398db54a22 100644 --- a/pkg/analysis_server/test/lsp/server_abstract.dart +++ b/pkg/analysis_server/test/lsp/server_abstract.dart @@ -1574,7 +1574,6 @@ mixin LspAnalysisServerTestMixin on LspRequestHelpersMixin, LspEditHelpersMixin // This is the signature expected for LSP. // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#:~:text=Response%3A-,result%3A%20null,-error%3A%20code%20and - // ignore: prefer_void_to_null Future sendShutdown() { var request = makeRequest(Method.shutdown, null); return expectSuccessfulResponseTo(request, (result) => result as Null); diff --git a/pkg/analysis_server_plugin/test/src/plugin_server_error_test.dart b/pkg/analysis_server_plugin/test/src/plugin_server_error_test.dart index bb165b081d5f..d3d9d8831575 100644 --- a/pkg/analysis_server_plugin/test/src/plugin_server_error_test.dart +++ b/pkg/analysis_server_plugin/test/src/plugin_server_error_test.dart @@ -232,7 +232,6 @@ class _ThrowsAsyncErrorVisitor extends SimpleAstVisitor { void visitBooleanLiteral(BooleanLiteral node) { // Raise an async error that can only be caught by an error zone's `onError` // handler. - // ignore: unawaited_futures Future.error(StateError('A message.')); } } diff --git a/pkg/analyzer/lib/src/generated/testing/test_type_provider.dart b/pkg/analyzer/lib/src/generated/testing/test_type_provider.dart index 8811e727b543..bba7d1fc4d3a 100644 --- a/pkg/analyzer/lib/src/generated/testing/test_type_provider.dart +++ b/pkg/analyzer/lib/src/generated/testing/test_type_provider.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/source/source.dart'; import 'package:analyzer/src/dart/analysis/session.dart'; import 'package:analyzer/src/dart/element/class_hierarchy.dart'; diff --git a/pkg/analyzer/lib/src/summary2/kernel_compilation_service.dart b/pkg/analyzer/lib/src/summary2/kernel_compilation_service.dart index dfd4b3bf5465..d36a38d6c30d 100644 --- a/pkg/analyzer/lib/src/summary2/kernel_compilation_service.dart +++ b/pkg/analyzer/lib/src/summary2/kernel_compilation_service.dart @@ -138,11 +138,9 @@ class KernelCompilationService { if (instance != null) { _currentInstance = null; // We don't expect any answer, the process will stop. - // ignore: unawaited_futures instance.requestChannel.sendRequest('exit', {}); instance.socket.destroy(); // This socket is bound to a fresh port, we don't need it. - // ignore: unawaited_futures instance.serverSocket.close(); instance.process.kill(); } diff --git a/pkg/analyzer/lib/src/summary2/macro.dart b/pkg/analyzer/lib/src/summary2/macro.dart index 2ee109e16863..cb4621c4273f 100644 --- a/pkg/analyzer/lib/src/summary2/macro.dart +++ b/pkg/analyzer/lib/src/summary2/macro.dart @@ -133,7 +133,6 @@ class KernelBundleMacroExecutor extends BundleMacroExecutor { Uri get _kernelUri { return _kernelUriCached ??= - // ignore: avoid_dynamic_calls (Isolate.current as dynamic).createUriForKernelBlob(kernelBytes) as Uri; } @@ -142,7 +141,6 @@ class KernelBundleMacroExecutor extends BundleMacroExecutor { support.executor.unregisterExecutorFactory(_executorFactoryToken); var kernelUriCached = _kernelUriCached; if (kernelUriCached != null) { - // ignore: avoid_dynamic_calls (Isolate.current as dynamic).unregisterKernelBlobUri(kernelUriCached); _kernelUriCached = null; } diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart index 146f47406cac..7c873d68b3b9 100644 --- a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart +++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: camel_case_types - import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element2.dart'; diff --git a/pkg/linter/lib/src/analyzer.dart b/pkg/linter/lib/src/analyzer.dart index 151168d5bd58..03daae3e7283 100644 --- a/pkg/linter/lib/src/analyzer.dart +++ b/pkg/linter/lib/src/analyzer.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: implementation_imports - export 'package:analyzer/dart/element/type_system.dart'; export 'package:analyzer/source/line_info.dart'; export 'package:analyzer/src/dart/ast/token.dart'; diff --git a/pkg/linter/lib/src/rules/package_prefixed_library_names.dart b/pkg/linter/lib/src/rules/package_prefixed_library_names.dart index a9d8023a5821..9e9ab7c81a5d 100644 --- a/pkg/linter/lib/src/rules/package_prefixed_library_names.dart +++ b/pkg/linter/lib/src/rules/package_prefixed_library_names.dart @@ -38,7 +38,6 @@ class _Visitor extends SimpleAstVisitor { _Visitor(this.rule); @override - // ignore: prefer_expression_function_bodies void visitLibraryDirective(LibraryDirective node) { // Project info is not being set. //See: https://github.com/dart-lang/linter/issues/3395 diff --git a/pkg/linter/lib/src/rules/prefer_is_empty.dart b/pkg/linter/lib/src/rules/prefer_is_empty.dart index c889d20f39d7..f66cfbb98f4a 100644 --- a/pkg/linter/lib/src/rules/prefer_is_empty.dart +++ b/pkg/linter/lib/src/rules/prefer_is_empty.dart @@ -186,7 +186,6 @@ class _Visitor extends SimpleAstVisitor { required bool ignoreAs, }) { var search = expression; - // ignore: literal_only_boolean_expressions while (true) { if (ignoreParens && search is ParenthesizedExpression) { search = search.expression; diff --git a/pkg/linter/test/rules/use_enums_test.dart b/pkg/linter/test/rules/use_enums_test.dart index d354780f6450..731093460f1c 100644 --- a/pkg/linter/test/rules/use_enums_test.dart +++ b/pkg/linter/test/rules/use_enums_test.dart @@ -145,7 +145,6 @@ class _E { error(WarningCode.UNUSED_FIELD, 57, 1), error(CompileTimeErrorCode.RECURSIVE_CONSTANT_CONSTRUCTOR, 76, 2), // We are reversing the deprecation: This code will remain a `HintCode`. - // ignore: deprecated_member_use error(WarningCode.UNUSED_ELEMENT_PARAMETER, 83, 1), ], ); diff --git a/pkg/linter/tool/checks/driver.dart b/pkg/linter/tool/checks/driver.dart index 7e2185fbb4c5..ad6487d491b2 100644 --- a/pkg/linter/tool/checks/driver.dart +++ b/pkg/linter/tool/checks/driver.dart @@ -9,9 +9,9 @@ import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/file_system/physical_file_system.dart'; -import 'package:analyzer/src/dart/analysis/analysis_options.dart'; // ignore: implementation_imports -import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart'; // ignore: implementation_imports -import 'package:analyzer/src/lint/registry.dart'; // ignore: implementation_imports +import 'package:analyzer/src/dart/analysis/analysis_options.dart'; +import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart'; +import 'package:analyzer/src/lint/registry.dart'; import 'package:cli_util/cli_logging.dart'; import 'package:linter/src/analyzer.dart'; import 'package:linter/src/test_utilities/analysis_error_info.dart'; @@ -96,9 +96,10 @@ class Driver { try { var result = await context.currentSession.getErrors(filePath); if (result is ErrorsResult) { - var filtered = result.errors - .where((e) => e.errorCode.name != 'TODO') - .toList(); + var filtered = + result.errors + .where((e) => e.errorCode.name != 'TODO') + .toList(); if (filtered.isNotEmpty) { errors.add(AnalysisErrorInfo(filtered, result.lineInfo)); } diff --git a/pkg/linter/tool/util/lint_driver.dart b/pkg/linter/tool/util/lint_driver.dart index 2225f65045b1..1813fbdcc194 100644 --- a/pkg/linter/tool/util/lint_driver.dart +++ b/pkg/linter/tool/util/lint_driver.dart @@ -7,11 +7,8 @@ import 'dart:io' as io; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/instrumentation/instrumentation.dart'; -// ignore: implementation_imports import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart'; -// ignore: implementation_imports import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine; -// ignore: implementation_imports import 'package:analyzer/src/lint/io.dart'; import 'package:linter/src/test_utilities/analysis_error_info.dart'; import 'package:linter/src/test_utilities/linter_options.dart'; From 161b8e9cc13a1aa3b50f1b387c564bc27f84e451 Mon Sep 17 00:00:00 2001 From: Devon Carew Date: Mon, 13 Jan 2025 16:34:30 -0800 Subject: [PATCH 19/76] Bump shelf to bf799519cda2898a7c5af06dcfdd5fe6443afd79 Changes: ``` > git log --format="%C(auto) %h %s" 2b5b683..bf79951 https://dart.googlesource.com/shelf.git/+/bf79951 Publish shelf_router_generator 1.1.1 (467) https://dart.googlesource.com/shelf.git/+/8ea524b Bump actions/cache from 4.1.2 to 4.2.0 in the github-actions group (465) https://dart.googlesource.com/shelf.git/+/6b8b338 shelf_router_generator: bump dependencies (464) https://dart.googlesource.com/shelf.git/+/e3975a8 add more type information to the 'webSocketHandler' method (463) ``` Diff: https://dart.googlesource.com/shelf.git/+/2b5b683e78f5cc84e479a43297fd7b5489d7db02..bf799519cda2898a7c5af06dcfdd5fe6443afd79/ Change-Id: I6ac9ef9bf1f5533ecabcf920c6deaf7c9216dd3a Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403964 Reviewed-by: Nate Bosch Commit-Queue: Devon Carew --- DEPS | 2 +- pkg/dds/CHANGELOG.md | 4 ++++ pkg/dds/pubspec.yaml | 6 +++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/DEPS b/DEPS index 49296040dba5..329afb33ad0a 100644 --- a/DEPS +++ b/DEPS @@ -147,7 +147,7 @@ vars = { "protobuf_rev": "b7dd58cdbd879beee4c3fbf8ee80fce8e97bad26", "pub_rev": "58de642dc1d07601f6eb2b4ecd94555c0210106b", # disable tools/rev_sdk_deps.dart "pub_semver_rev": "960f91309e325ae037e5f1434acb77b83a12d91e", - "shelf_rev": "2b5b683e78f5cc84e479a43297fd7b5489d7db02", + "shelf_rev": "bf799519cda2898a7c5af06dcfdd5fe6443afd79", "source_maps_rev": "e5e9d343302acf7df2145316ae4e56026c550989", "source_span_rev": "e6a34591b7f7880c7ca0fcb95b858ccf7f8be304", "sse_rev": "b573a1e9a61f5f3e2198becfa3f4f2e8decd1e90", diff --git a/pkg/dds/CHANGELOG.md b/pkg/dds/CHANGELOG.md index 341aad00d2a5..89c1eac711de 100644 --- a/pkg/dds/CHANGELOG.md +++ b/pkg/dds/CHANGELOG.md @@ -1,3 +1,7 @@ +# 5.0.1-wip + +- Widen the dependency on `package:shelf_web_socket`. + # 5.0.0 - [DAP] The debug adapter no longer spawns its own in-process copy of DDS, instead relying on one started by the Dart VM (or `Flutter`). This means the `enableDds` and `enableAuthCodes` arguments to the `DartDebugAdapter` base class have been deprecated and have any effect. Suppressing DDS (or auth codes) should be done in launch configuration (for example using `vmAdditionalArgs` or `toolArgs` depending on the target tool). - Updated the `devtools_shared` dependency to version `^11.0.0`. diff --git a/pkg/dds/pubspec.yaml b/pkg/dds/pubspec.yaml index 6562dfd06e2a..93b01ebf38a2 100644 --- a/pkg/dds/pubspec.yaml +++ b/pkg/dds/pubspec.yaml @@ -1,5 +1,5 @@ name: dds -version: 5.0.0 +version: 5.0.1-wip description: >- A library used to spawn the Dart Developer Service, used to communicate with a Dart VM Service instance. @@ -24,7 +24,7 @@ dependencies: path: ^1.8.0 shelf_proxy: ^1.0.0 shelf_static: ^1.0.0 - shelf_web_socket: '>=1.0.0 <3.0.0' + shelf_web_socket: '>=1.0.0 <4.0.0' shelf: ^1.0.0 sse: ^4.0.0 stream_channel: ^2.0.0 @@ -38,4 +38,4 @@ dependencies: dev_dependencies: lints: any test: any - webdriver: any \ No newline at end of file + webdriver: any From d3c75903393a6178651199f25b9653c20d23cac7 Mon Sep 17 00:00:00 2001 From: Devon Carew Date: Mon, 13 Jan 2025 17:28:36 -0800 Subject: [PATCH 20/76] [DEPS] remove no longer referenced deps Change-Id: I391c548a6ce22d2a71578735d1c18ebcebc42b1b Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403934 Commit-Queue: Devon Carew Reviewed-by: Kevin Moore --- DEPS | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/DEPS b/DEPS index 329afb33ad0a..1c9ad4451a88 100644 --- a/DEPS +++ b/DEPS @@ -142,15 +142,9 @@ vars = { "material_color_utilities_rev": "799b6ba2f3f1c28c67cc7e0b4f18e0c7d7f3c03e", # dart-native-interop-team@ is rolling breaking changes manually while the assets features are in experimental. "native_rev": "14368a80bae9e3f381a2e59c91405338d82451ee", # disable tools/rev_sdk_deps.dart - "package_config_rev": "07097d7ae60d40b34ce8daabdce318ecc168b7d1", - "pool_rev": "bf27900420ba382b6e5c0484ab3c79daad703dcd", "protobuf_rev": "b7dd58cdbd879beee4c3fbf8ee80fce8e97bad26", "pub_rev": "58de642dc1d07601f6eb2b4ecd94555c0210106b", # disable tools/rev_sdk_deps.dart - "pub_semver_rev": "960f91309e325ae037e5f1434acb77b83a12d91e", "shelf_rev": "bf799519cda2898a7c5af06dcfdd5fe6443afd79", - "source_maps_rev": "e5e9d343302acf7df2145316ae4e56026c550989", - "source_span_rev": "e6a34591b7f7880c7ca0fcb95b858ccf7f8be304", - "sse_rev": "b573a1e9a61f5f3e2198becfa3f4f2e8decd1e90", "stack_trace_rev": "5fe4cfea7f0d8e67b7d5738d2e1c64a18b5ba450", "stream_channel_rev": "31a3aba8a78a78b266fbf7474f19cd4ba9ca562e", "string_scanner_rev": "69212690d491603a511904a7a84cd502f34bf7a9", @@ -158,8 +152,6 @@ vars = { "tar_rev": "5a1ea943e70cdf3fa5e1102cdbb9418bd9b4b81a", "term_glyph_rev": "52677db71a2c6b6d0018ebbe5ed7552dbae1248f", "test_rev": "f364fc8291d668d85c702a5b9f9a4f2e5c1ade0e", - "test_descriptor_rev": "92fa0c551267b38e4b27c9f74976ae4cd96d8b1e", - "test_reflective_loader_rev": "9e35c9e00b8b6299e9295c0f29617af39276717d", "tools_rev": "b412ba4550bb634caf3c1064b7ebb671cd5e9247", "vector_math_rev": "bd4b574b2a457a3955d223694f1a979a0c0f38c9", "watcher_rev": "7f3b3a3ea49ba7e21fff240ce8ee616d62d32956", @@ -382,25 +374,12 @@ deps = { }, Var("dart_root") + "/third_party/pkg/native": Var("dart_git") + "native.git" + "@" + Var("native_rev"), - Var("dart_root") + "/third_party/pkg/package_config": - Var("dart_git") + "package_config.git" + - "@" + Var("package_config_rev"), - Var("dart_root") + "/third_party/pkg/pool": - Var("dart_git") + "pool.git" + "@" + Var("pool_rev"), Var("dart_root") + "/third_party/pkg/protobuf": Var("dart_git") + "protobuf.git" + "@" + Var("protobuf_rev"), - Var("dart_root") + "/third_party/pkg/pub_semver": - Var("dart_git") + "pub_semver.git" + "@" + Var("pub_semver_rev"), Var("dart_root") + "/third_party/pkg/pub": Var("dart_git") + "pub.git" + "@" + Var("pub_rev"), Var("dart_root") + "/third_party/pkg/shelf": Var("dart_git") + "shelf.git" + "@" + Var("shelf_rev"), - Var("dart_root") + "/third_party/pkg/source_maps": - Var("dart_git") + "source_maps.git" + "@" + Var("source_maps_rev"), - Var("dart_root") + "/third_party/pkg/source_span": - Var("dart_git") + "source_span.git" + "@" + Var("source_span_rev"), - Var("dart_root") + "/third_party/pkg/sse": - Var("dart_git") + "sse.git" + "@" + Var("sse_rev"), Var("dart_root") + "/third_party/pkg/stack_trace": Var("dart_git") + "stack_trace.git" + "@" + Var("stack_trace_rev"), Var("dart_root") + "/third_party/pkg/stream_channel": @@ -418,11 +397,6 @@ deps = { Var("dart_git") + "term_glyph.git" + "@" + Var("term_glyph_rev"), Var("dart_root") + "/third_party/pkg/test": Var("dart_git") + "test.git" + "@" + Var("test_rev"), - Var("dart_root") + "/third_party/pkg/test_descriptor": - Var("dart_git") + "test_descriptor.git" + "@" + Var("test_descriptor_rev"), - Var("dart_root") + "/third_party/pkg/test_reflective_loader": - Var("dart_git") + "test_reflective_loader.git" + - "@" + Var("test_reflective_loader_rev"), Var("dart_root") + "/third_party/pkg/tools": Var("dart_git") + "tools.git" + "@" + Var("tools_rev"), Var("dart_root") + "/third_party/pkg/vector_math": From 50527dafa269f4d20a56d0292ca37b93872da782 Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Mon, 13 Jan 2025 18:04:01 -0800 Subject: [PATCH 21/76] Elements. Migrate SubtypeHelper. Change-Id: Iced0a394881f82937638caba4011cd8ac09ffa98 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404280 Reviewed-by: Phil Quitslund Commit-Queue: Konstantin Shcheglov --- .../lib/src/dart/element/element.dart | 3 +- .../lib/src/dart/element/subtype.dart | 83 ++++++++++--------- pkg/analyzer/lib/src/dart/element/type.dart | 11 +-- .../lib/src/dart/element/type_system.dart | 75 +++++++++++++++++ .../lib/src/utilities/extensions/element.dart | 11 +++ .../src/rules/analyzer_use_new_elements.dart | 70 ++++++++++------ .../rules/analyzer_use_new_elements_test.dart | 13 +++ 7 files changed, 191 insertions(+), 75 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart index 1b1a08c6818e..245a9778f3e9 100644 --- a/pkg/analyzer/lib/src/dart/element/element.dart +++ b/pkg/analyzer/lib/src/dart/element/element.dart @@ -11367,7 +11367,8 @@ class TypeParameterElementImpl2 extends TypeDefiningElementImpl2 TypeParameterType instantiate({ required NullabilitySuffix nullabilitySuffix, }) { - return firstFragment.instantiate( + return TypeParameterTypeImpl.v2( + element: this, nullabilitySuffix: nullabilitySuffix, ); } diff --git a/pkg/analyzer/lib/src/dart/element/subtype.dart b/pkg/analyzer/lib/src/dart/element/subtype.dart index 64c91650d34c..0b9de69dd0be 100644 --- a/pkg/analyzer/lib/src/dart/element/subtype.dart +++ b/pkg/analyzer/lib/src/dart/element/subtype.dart @@ -2,11 +2,9 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer_operations.dart' show Variance; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; @@ -92,7 +90,7 @@ class SubtypeHelper { T0 is TypeParameterTypeImpl) { var S = T0.promotedBound; if (S == null) { - var B = T0.element.bound ?? _objectQuestion; + var B = T0.element3.bound ?? _objectQuestion; return isSubtypeOf(B, _objectNone); } else { return isSubtypeOf(S, _objectNone); @@ -115,7 +113,7 @@ class SubtypeHelper { return false; } // Extension types require explicit `Object` implementation. - if (T0 is InterfaceTypeImpl && T0.element is ExtensionTypeElement) { + if (T0 is InterfaceTypeImpl && T0.element3 is ExtensionTypeElement2) { for (var interface in T0.interfaces) { if (isSubtypeOf(interface, T1_)) { return true; @@ -179,7 +177,7 @@ class SubtypeHelper { if (T0 is TypeParameterTypeImpl && T1 is TypeParameterTypeImpl && T1.promotedBound == null && - T0.element == T1.element) { + T0.element3 == T1.element3) { return true; } @@ -188,8 +186,8 @@ class SubtypeHelper { if (T1 is TypeParameterTypeImpl) { var T1_promotedBound = T1.promotedBound; if (T1_promotedBound != null) { - var X1 = TypeParameterTypeImpl( - element: T1.element, + var X1 = TypeParameterTypeImpl.v2( + element: T1.element3, nullabilitySuffix: T1.nullabilitySuffix, ); return isSubtypeOf(T0, X1) && isSubtypeOf(T0, T1_promotedBound); @@ -221,7 +219,7 @@ class SubtypeHelper { if (S0 != null && isSubtypeOf(S0, T1)) { return true; } - var B0 = T0.element.bound; + var B0 = T0.element3.bound; if (B0 != null && isSubtypeOf(B0, T1)) { return true; } @@ -249,7 +247,7 @@ class SubtypeHelper { if (S0 != null && isSubtypeOf(S0, T1)) { return true; } - var B0 = T0.element.bound; + var B0 = T0.element3.bound; if (B0 != null && isSubtypeOf(B0, T1)) { return true; } @@ -275,7 +273,7 @@ class SubtypeHelper { return true; } - var B0 = T0.element.bound; + var B0 = T0.element3.bound; if (B0 != null && isSubtypeOf(B0, T1)) { return true; } @@ -305,11 +303,11 @@ class SubtypeHelper { } bool _interfaceArguments( - InterfaceElement element, + InterfaceElement2 element, InterfaceType subType, InterfaceType superType, ) { - List parameters = element.typeParameters; + List parameters = element.typeParameters2; List subArguments = subType.typeArguments; List superArguments = superType.typeArguments; @@ -317,7 +315,7 @@ class SubtypeHelper { assert(parameters.length == subArguments.length); for (int i = 0; i < subArguments.length; i++) { - var parameter = parameters[i] as TypeParameterElementImpl; + var parameter = parameters[i] as TypeParameterElementImpl2; var subArgument = subArguments[i]; var superArgument = superArguments[i]; @@ -347,7 +345,8 @@ class SubtypeHelper { /// Check that [f] is a subtype of [g]. bool _isFunctionSubtypeOf(FunctionType f, FunctionType g) { - var fresh = _typeSystem.relateTypeParameters(f.typeFormals, g.typeFormals); + var fresh = + _typeSystem.relateTypeParameters2(f.typeParameters, g.typeParameters); if (fresh == null) { return false; } @@ -359,8 +358,8 @@ class SubtypeHelper { return false; } - var fParameters = f.parameters; - var gParameters = g.parameters; + var fParameters = f.formalParameters; + var gParameters = g.formalParameters; var fIndex = 0; var gIndex = 0; @@ -391,27 +390,33 @@ class SubtypeHelper { } } else if (fParameter.isNamed) { if (gParameter.isNamed) { - var compareNames = fParameter.name.compareTo(gParameter.name); - if (compareNames == 0) { - if (fParameter.isRequiredNamed && !gParameter.isRequiredNamed) { - return false; - } else if (isSubtypeOf(gParameter.type, fParameter.type)) { - fIndex++; - gIndex++; - } else { - return false; - } - } else if (compareNames < 0) { - if (fParameter.isRequiredNamed) { - return false; - } else { - fIndex++; - } - } else { - assert(compareNames > 0); - // The subtype must accept all parameters of the supertype. + var fName = fParameter.name3; + var gName = gParameter.name3; + if (fName == null || gName == null) { return false; } + + var compareNames = fName.compareTo(gName); + switch (compareNames) { + case 0: + if (fParameter.isRequiredNamed && !gParameter.isRequiredNamed) { + return false; + } else if (isSubtypeOf(gParameter.type, fParameter.type)) { + fIndex++; + gIndex++; + } else { + return false; + } + case < 0: + if (fParameter.isRequiredNamed) { + return false; + } else { + fIndex++; + } + default: + // The subtype must accept all parameters of the supertype. + return false; + } } else { break; } @@ -448,8 +453,8 @@ class SubtypeHelper { return false; } - var subElement = subType.element; - var superElement = superType.element; + var subElement = subType.element3; + var superElement = superType.element3; if (identical(subElement, superElement)) { return _interfaceArguments(superElement, subType, superType); } @@ -460,7 +465,7 @@ class SubtypeHelper { } for (var interface in subElement.allSupertypes) { - if (identical(interface.element, superElement)) { + if (identical(interface.element3, superElement)) { var substitution = Substitution.fromInterfaceType(subType); var substitutedInterface = substitution.substituteType(interface) as InterfaceType; diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart index fe88fce9d4aa..37ba01ef616a 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart @@ -207,14 +207,9 @@ class FunctionTypeImpl extends TypeImpl Null get element3 => null; @override - List get formalParameters => parameters - .map((parameter) => switch (parameter) { - FormalParameterFragment(:var element) => element, - ParameterMember(:var element) => element, - _ => throw UnsupportedError( - 'Unsupported type ${parameter.runtimeType}'), - }) - .toList(); + List get formalParameters { + return parameters.map((p) => p.asElement2).toList(growable: false); + } @Deprecated('Check element, or use getDisplayString()') @override diff --git a/pkg/analyzer/lib/src/dart/element/type_system.dart b/pkg/analyzer/lib/src/dart/element/type_system.dart index 721385a8ae26..3b6e7683bfe0 100644 --- a/pkg/analyzer/lib/src/dart/element/type_system.dart +++ b/pkg/analyzer/lib/src/dart/element/type_system.dart @@ -39,6 +39,7 @@ import 'package:analyzer/src/dart/element/well_bounded.dart'; import 'package:analyzer/src/dart/resolver/flow_analysis_visitor.dart'; import 'package:analyzer/src/generated/inference_log.dart'; import 'package:analyzer/src/utilities/extensions/collection.dart'; +import 'package:analyzer/src/utilities/extensions/element.dart'; import 'package:meta/meta.dart'; class ExtensionTypeErasure extends ReplacementVisitor { @@ -78,6 +79,19 @@ class RelatedTypeParameters { ); } +/// Fresh type parameters created to unify two lists of type parameters. +class RelatedTypeParameters2 { + static final _empty = RelatedTypeParameters2._(const [], const []); + + final List typeParameters; + final List typeParameterTypes; + + RelatedTypeParameters2._( + this.typeParameters, + this.typeParameterTypes, + ); +} + /// The [TypeSystem] implementation. class TypeSystemImpl implements TypeSystem { /// The provider of types for the system. @@ -1622,6 +1636,67 @@ class TypeSystemImpl implements TypeSystem { ); } + /// Given two lists of type parameters, check that they have the same + /// number of elements, and their bounds are equal. + /// + /// The return value will be a new list of fresh type parameters, that can + /// be used to instantiate both function types, allowing further comparison. + RelatedTypeParameters2? relateTypeParameters2( + List typeParameters1, + List typeParameters2, + ) { + if (typeParameters1.length != typeParameters2.length) { + return null; + } + if (typeParameters1.isEmpty) { + return RelatedTypeParameters2._empty; + } + + var length = typeParameters1.length; + var freshTypeParameters = List.generate(length, (index) { + return typeParameters1[index].freshCopy(); + }, growable: false); + + var freshTypeParameterTypes = List.generate(length, (index) { + return freshTypeParameters[index].instantiate( + nullabilitySuffix: NullabilitySuffix.none, + ); + }, growable: false); + + var substitution1 = Substitution.fromPairs2( + typeParameters1, + freshTypeParameterTypes, + ); + var substitution2 = Substitution.fromPairs2( + typeParameters2, + freshTypeParameterTypes, + ); + + for (var i = 0; i < typeParameters1.length; i++) { + var bound1 = typeParameters1[i].bound; + var bound2 = typeParameters2[i].bound; + if (bound1 == null && bound2 == null) { + continue; + } + bound1 ??= DynamicTypeImpl.instance; + bound2 ??= DynamicTypeImpl.instance; + bound1 = substitution1.substituteType(bound1); + bound2 = substitution2.substituteType(bound2); + if (!isEqualTo(bound1, bound2)) { + return null; + } + + if (bound1 is! DynamicType) { + freshTypeParameters[i].bound = bound1; + } + } + + return RelatedTypeParameters2._( + freshTypeParameters, + freshTypeParameterTypes, + ); + } + /// Replaces all covariant occurrences of `dynamic`, `void`, and `Object` or /// `Object?` with `Null` or `Never` and all contravariant occurrences of /// `Null` or `Never` with `Object` or `Object?`. diff --git a/pkg/analyzer/lib/src/utilities/extensions/element.dart b/pkg/analyzer/lib/src/utilities/extensions/element.dart index 8ffcc2bd9b42..f79211b10d64 100644 --- a/pkg/analyzer/lib/src/utilities/extensions/element.dart +++ b/pkg/analyzer/lib/src/utilities/extensions/element.dart @@ -550,6 +550,17 @@ extension TypeParameterElement2Extension on TypeParameterElement2 { TypeParameterElement get asElement { return firstFragment as TypeParameterElement; } + + TypeParameterElementImpl2 freshCopy() { + return TypeParameterElementImpl2( + firstFragment: TypeParameterElementImpl( + name3 ?? '', + -1, + ), + name3: name3, + bound: bound, + ); + } } extension TypeParameterElementExtension on TypeParameterElement { diff --git a/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart b/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart index 6fd5ba280436..23cc67b3f6c5 100644 --- a/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart +++ b/pkg/linter/lib/src/rules/analyzer_use_new_elements.dart @@ -26,34 +26,41 @@ bool _isOldModelElement(Element2? element) { var uriStr = libraryFragment.source.uri.toString(); - if (element is InstanceElement2) { - if (uriStr == 'package:analyzer/dart/element/element.dart') { - // Skip classes that don't required migration. - if (const { - 'DirectiveUri', - 'DirectiveUriWithLibrary', - 'DirectiveUriWithRelativeUri', - 'DirectiveUriWithRelativeUriString', - 'DirectiveUriWithSource', - 'DirectiveUriWithUnit', - 'ElementAnnotation', - 'ElementKind', - 'ElementLocation', - 'HideElementCombinator', - 'LibraryLanguageVersion', - 'NamespaceCombinator', - 'ShowElementCombinator', - }.contains(firstFragment.name2)) { - return false; + switch (element) { + case InstanceElement2(): + if (uriStr == 'package:analyzer/dart/element/element.dart') { + // Skip classes that don't required migration. + if (const { + 'DirectiveUri', + 'DirectiveUriWithLibrary', + 'DirectiveUriWithRelativeUri', + 'DirectiveUriWithRelativeUriString', + 'DirectiveUriWithSource', + 'DirectiveUriWithUnit', + 'ElementAnnotation', + 'ElementKind', + 'ElementLocation', + 'HideElementCombinator', + 'LibraryLanguageVersion', + 'NamespaceCombinator', + 'ShowElementCombinator', + }.contains(firstFragment.name2)) { + return false; + } + return true; + } + case GetterElement(): + switch (uriStr) { + case 'package:analyzer/src/dart/ast/ast.dart': + return element.name3 == 'declaredElement'; + case 'package:analyzer/src/dart/element/type.dart': + var enclosingElement = element.enclosingElement2; + if (enclosingElement is InterfaceElement2) { + if (enclosingElement.thisType.implementsDartType) { + return element.name3 == 'element'; + } + } } - return true; - } - } - - if (element is GetterElement) { - if (uriStr == 'package:analyzer/src/dart/ast/ast.dart') { - return element.name3 == 'declaredElement'; - } } return false; } @@ -149,3 +156,12 @@ class _Visitor extends SimpleAstVisitor { } } } + +extension on InterfaceType { + bool get implementsDartType => allSupertypes.any((t) => t.isDartType); + + bool get isDartType => + element3.library2.uri.toString() == + 'package:analyzer/dart/element/type.dart' && + element3.name3 == 'DartType'; +} diff --git a/pkg/linter/test/rules/analyzer_use_new_elements_test.dart b/pkg/linter/test/rules/analyzer_use_new_elements_test.dart index 894ffde5ab83..177e3873ae64 100644 --- a/pkg/linter/test/rules/analyzer_use_new_elements_test.dart +++ b/pkg/linter/test/rules/analyzer_use_new_elements_test.dart @@ -52,6 +52,19 @@ ClassElement f() { ''', []); } + test_interfaceTypeImpl_element() async { + await assertDiagnostics( + r''' +import 'package:analyzer/src/dart/element/type.dart'; + +void f(InterfaceTypeImpl type) { + type.element; +} +''', + [lint(95, 7)], + ); + } + test_methodInvocation_hasFormalParameter() async { newFile('$testPackageLibPath/a.dart', r''' import 'package:analyzer/dart/element/element.dart'; From 1f5b9042b6a92591d162716d29bb14f1d7d80015 Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jan 2025 21:32:57 -0800 Subject: [PATCH 22/76] Elements. Migrate test/src/dart/analysis/session_test.dart Change-Id: I0e35b0a56119adc42708a0e44321c600db33f8f8 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404220 Reviewed-by: Phil Quitslund Commit-Queue: Keerti Parthasarathy Reviewed-by: Brian Wilkerson --- .../test/src/dart/analysis/session_test.dart | 96 +++++++++---------- 1 file changed, 47 insertions(+), 49 deletions(-) diff --git a/pkg/analyzer/test/src/dart/analysis/session_test.dart b/pkg/analyzer/test/src/dart/analysis/session_test.dart index 917e9d64a6b2..75530f770334 100644 --- a/pkg/analyzer/test/src/dart/analysis/session_test.dart +++ b/pkg/analyzer/test/src/dart/analysis/session_test.dart @@ -2,12 +2,10 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/analysis/session.dart'; import 'package:analyzer/dart/ast/ast.dart'; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/utilities/extensions/file_system.dart'; @@ -125,7 +123,7 @@ class AnalysisSessionImpl_BlazeWorkspaceTest var session = contextFor(file).currentSession; var result = await session.getUnitElementValid(file); expect(result.path, file.path); - expect(result.element.classes, hasLength(1)); + expect(result.fragment.classes2, hasLength(1)); expect(result.uri.toString(), 'package:dart.my/a.dart'); } } @@ -266,10 +264,10 @@ class B {} var session = contextFor(testFile).currentSession; var result = await session.getLibraryByUriValid('package:test/test.dart'); - var library = result.element; - expect(library.getClass('A'), isNotNull); - expect(library.getClass('B'), isNotNull); - expect(library.getClass('C'), isNull); + var library = result.element2; + expect(library.getClass2('A'), isNotNull); + expect(library.getClass2('B'), isNotNull); + expect(library.getClass2('C'), isNull); } test_getLibraryByUri_inconsistent() async { @@ -330,8 +328,8 @@ class B {} ); var parsedLibrary = session.getParsedLibraryValid(testFile); - var element = libraryResult.element.getClass('A')!; - var declaration = parsedLibrary.getElementDeclaration(element)!; + var element = libraryResult.element2.getClass2('A')!; + var declaration = parsedLibrary.getElementDeclaration2(element.firstFragment)!; var node = declaration.node as ClassDeclaration; expect(node.name.lexeme, 'A'); expect(node.offset, 0); @@ -345,12 +343,12 @@ class B {} var resolvedUnit = await session.getResolvedUnit(testFile.path) as ResolvedUnitResult; var typeProvider = resolvedUnit.typeProvider; - var intClass = typeProvider.intType.element; + var intClass = typeProvider.intType.element3; var parsedLibrary = session.getParsedLibraryValid(testFile); expect(() { - parsedLibrary.getElementDeclaration(intClass); + parsedLibrary.getElementDeclaration2(intClass.firstFragment); }, throwsArgumentError); } @@ -363,19 +361,19 @@ int foo = 0; var parsedLibrary = session.getParsedLibraryValid(testFile); var unitResult = await session.getUnitElementValid(testFile); - var fooElement = unitResult.element.topLevelVariables[0]; - expect(fooElement.name, 'foo'); + var fooElement = unitResult.fragment.topLevelVariables2[0]; + expect(fooElement.name2, 'foo'); // We can get the variable element declaration. - var fooDeclaration = parsedLibrary.getElementDeclaration(fooElement)!; + var fooDeclaration = parsedLibrary.getElementDeclaration2(fooElement)!; var fooNode = fooDeclaration.node as VariableDeclaration; expect(fooNode.name.lexeme, 'foo'); expect(fooNode.offset, 4); expect(fooNode.length, 7); // Synthetic elements don't have nodes. - expect(parsedLibrary.getElementDeclaration(fooElement.getter!), isNull); - expect(parsedLibrary.getElementDeclaration(fooElement.setter!), isNull); + expect(parsedLibrary.getElementDeclaration2(fooElement.getter2!), isNull); + expect(parsedLibrary.getElementDeclaration2(fooElement.setter2!), isNull); } test_getParsedLibrary_inconsistent() async { @@ -477,7 +475,7 @@ class C3 {} var libraryResult = await session.getLibraryByUriValid( 'package:test/test.dart', ); - var element = libraryResult.element; + var element = libraryResult.element2; var parsedLibrary = session.getParsedLibraryByElementValid(element); expect(parsedLibrary.session, session); @@ -498,12 +496,12 @@ class C3 {} var libraryResult = await session.getLibraryByUriValid( 'package:test/test.dart', ); - var element = libraryResult.element; + var element = libraryResult.element2; var aaaFile = getFile('$workspaceRootPath/aaa/lib/a.dart'); var aaaSession = contextFor(aaaFile).currentSession; - var result = aaaSession.getParsedLibraryByElement(element); + var result = aaaSession.getParsedLibraryByElement2(element); expect(result, isA()); } @@ -558,13 +556,13 @@ class B2 extends X {} expect(resolvedLibrary.session, session); var typeProvider = resolvedLibrary.typeProvider; - expect(typeProvider.intType.element.name, 'int'); + expect(typeProvider.intType.element3.name3, 'int'); - var libraryElement = resolvedLibrary.element; + var libraryElement = resolvedLibrary.element2; - var aClass = libraryElement.getClass('A')!; + var aClass = libraryElement.getClass2('A')!; - var bClass = libraryElement.getClass('B')!; + var bClass = libraryElement.getClass2('B')!; var aUnitResult = resolvedLibrary.units[0]; expect(aUnitResult.path, a.path); @@ -584,19 +582,19 @@ class B2 extends X {} expect(bUnitResult.unit.declarations, hasLength(2)); expect(bUnitResult.errors, isNotEmpty); - var aDeclaration = resolvedLibrary.getElementDeclaration(aClass)!; + var aDeclaration = resolvedLibrary.getElementDeclaration2(aClass.firstFragment)!; var aNode = aDeclaration.node as ClassDeclaration; expect(aNode.name.lexeme, 'A'); expect(aNode.offset, 16); expect(aNode.length, 16); - expect(aNode.declaredElement!.name, 'A'); + expect(aNode.declaredFragment!.name2, 'A'); - var bDeclaration = resolvedLibrary.getElementDeclaration(bClass)!; + var bDeclaration = resolvedLibrary.getElementDeclaration2(bClass.firstFragment)!; var bNode = bDeclaration.node as ClassDeclaration; expect(bNode.name.lexeme, 'B'); expect(bNode.offset, 19); expect(bNode.length, 16); - expect(bNode.declaredElement!.name, 'B'); + expect(bNode.declaredFragment!.name2, 'B'); } test_getResolvedLibrary_getElementDeclaration_notThisLibrary() async { @@ -606,8 +604,8 @@ class B2 extends X {} var resolvedLibrary = await session.getResolvedLibraryValid(testFile); expect(() { - var intClass = resolvedLibrary.typeProvider.intType.element; - resolvedLibrary.getElementDeclaration(intClass); + var intClass = resolvedLibrary.typeProvider.intType.element3; + resolvedLibrary.getElementDeclaration2(intClass.firstFragment); }, throwsArgumentError); } @@ -618,22 +616,22 @@ int foo = 0; var session = contextFor(testFile).currentSession; var resolvedLibrary = await session.getResolvedLibraryValid(testFile); - var unitElement = resolvedLibrary.element.definingCompilationUnit; + var unitElement = resolvedLibrary.element2.firstFragment; - var fooElement = unitElement.topLevelVariables[0]; - expect(fooElement.name, 'foo'); + var fooElement = unitElement.topLevelVariables2[0]; + expect(fooElement.name2, 'foo'); // We can get the variable element declaration. - var fooDeclaration = resolvedLibrary.getElementDeclaration(fooElement)!; + var fooDeclaration = resolvedLibrary.getElementDeclaration2(fooElement)!; var fooNode = fooDeclaration.node as VariableDeclaration; expect(fooNode.name.lexeme, 'foo'); expect(fooNode.offset, 4); expect(fooNode.length, 7); - expect(fooNode.declaredElement!.name, 'foo'); + expect(fooNode.declaredFragment!.name2, 'foo'); // Synthetic elements don't have nodes. - expect(resolvedLibrary.getElementDeclaration(fooElement.getter!), isNull); - expect(resolvedLibrary.getElementDeclaration(fooElement.setter!), isNull); + expect(resolvedLibrary.getElementDeclaration2(fooElement.getter2!), isNull); + expect(resolvedLibrary.getElementDeclaration2(fooElement.setter2!), isNull); } test_getResolvedLibrary_inconsistent() async { @@ -684,14 +682,14 @@ part 'c.dart'; var libraryResult = await session.getLibraryByUriValid( 'package:test/test.dart', ); - var element = libraryResult.element; + var element = libraryResult.element2; var result = await session.getResolvedLibraryByElementValid(element); expect(result.session, session); expect(result.units, hasLength(1)); expect(result.units[0].path, test.path); expect(result.units[0].uri, Uri.parse('package:test/test.dart')); - expect(result.units[0].unit.declaredElement, isNotNull); + expect(result.units[0].unit.declaredFragment, isNotNull); } test_getResolvedLibraryByElement_differentSession() async { @@ -701,12 +699,12 @@ part 'c.dart'; var libraryResult = await session.getLibraryByUriValid( 'package:test/test.dart', ); - var element = libraryResult.element; + var element = libraryResult.element2; var aaaFile = getFile('$workspaceRootPath/aaa/lib/a.dart'); var aaaSession = contextFor(aaaFile).currentSession; - var result = await aaaSession.getResolvedLibraryByElement(element); + var result = await aaaSession.getResolvedLibraryByElement2(element); expect(result, isA()); } @@ -724,7 +722,7 @@ class B {} expect(unitResult.uri, Uri.parse('package:test/test.dart')); expect(unitResult.unit.declarations, hasLength(2)); expect(unitResult.typeProvider, isNotNull); - expect(unitResult.libraryElement, isNotNull); + expect(unitResult.libraryElement2, isNotNull); } test_getResolvedUnit_inconsistent() async { @@ -906,13 +904,13 @@ unitElementResult sink.writelnWithIndent('element'); sink.withIndent(() { - var element = result.element as CompilationUnitElementImpl; + var element = result.fragment as CompilationUnitElementImpl; sink.writelnWithIndent('reference: ${element.reference}'); - var library = element.library; + var library = (element as LibraryFragment).element as LibraryElementImpl; sink.writelnWithIndent('library: ${library.reference}'); - var classListStr = element.classes.map((e) => e.name).join(', '); + var classListStr = element.classes2.map((e) => e.name2).join(', '); sink.writelnWithIndent('classes: $classListStr'); }); }); @@ -934,8 +932,8 @@ extension on AnalysisSession { return await getLibraryByUri(uriStr) as LibraryElementResult; } - ParsedLibraryResult getParsedLibraryByElementValid(LibraryElement element) { - return getParsedLibraryByElement(element) as ParsedLibraryResult; + ParsedLibraryResult getParsedLibraryByElementValid(LibraryElement2 element) { + return getParsedLibraryByElement2(element) as ParsedLibraryResult; } ParsedLibraryResult getParsedLibraryValid(File file) { @@ -947,8 +945,8 @@ extension on AnalysisSession { } Future getResolvedLibraryByElementValid( - LibraryElement element) async { - return await getResolvedLibraryByElement(element) as ResolvedLibraryResult; + LibraryElement2 element) async { + return await getResolvedLibraryByElement2(element) as ResolvedLibraryResult; } Future getResolvedLibraryValid(File file) async { From 34be38dcce8da65400d671de26a21d11b99a3bef Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jan 2025 21:33:29 -0800 Subject: [PATCH 23/76] Elements. Migrate test/src/task/strong/dart2_inference_test.dart Change-Id: I067759366d7d5661f840885abcacebd088218f80 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404180 Reviewed-by: Brian Wilkerson Reviewed-by: Phil Quitslund Commit-Queue: Keerti Parthasarathy --- .../src/task/strong/dart2_inference_test.dart | 52 +++++++++---------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart b/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart index 1f540a8b4411..c5560776dce1 100644 --- a/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart +++ b/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart @@ -2,10 +2,8 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/dart/ast/ast.dart'; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/test_utilities/function_ast_visitor.dart'; @@ -247,7 +245,7 @@ void test(List listA, List listB) { String vSearch, String vType, String fSearch, String fType) { var node = findNode.declaredIdentifier(vSearch); - var element = node.declaredElement as LocalVariableElement; + var element = node.declaredElement2 as LocalVariableElement2; assertType(element.type, vType); var invocation = findNode.methodInvocation(fSearch); @@ -269,12 +267,12 @@ class C { } '''; await resolveTestCode(code); - ClassElement c = findElement.class_('C'); + ClassElement2 c = findElement2.class_('C'); - PropertyAccessorElement x = c.accessors[0]; + SetterElement x = c.setters2[0]; expect(x.returnType, VoidTypeImpl.instance); - MethodElement operator = c.methods[0]; + MethodElement2 operator = c.methods2[0]; expect(operator.displayName, '[]='); expect(operator.returnType, VoidTypeImpl.instance); } @@ -290,12 +288,12 @@ class Derived extends Base { operator[]=(int x, int y) {} }'''; await resolveTestCode(code); - ClassElement c = findElement.class_('Derived'); + ClassElement2 c = findElement2.class_('Derived'); - PropertyAccessorElement x = c.accessors[0]; + SetterElement x = c.setters2[0]; expect(x.returnType, VoidTypeImpl.instance); - MethodElement operator = c.methods[0]; + MethodElement2 operator = c.methods2[0]; expect(operator.displayName, '[]='); expect(operator.returnType, VoidTypeImpl.instance); } @@ -307,12 +305,12 @@ var y = {}; '''; await resolveTestCode(code); var xNode = findNode.variableDeclaration('x = '); - var xElement = xNode.declaredElement!; - assertType(xElement.type, 'List'); + var xfragment = xNode.declaredFragment!; + assertType(xfragment.element.type, 'List'); var yNode = findNode.variableDeclaration('y = '); - var yElement = yNode.declaredElement!; - assertType(yElement.type, 'Map'); + var yfragment = yNode.declaredFragment!; + assertType(yfragment.element.type, 'Map'); } test_listMap_null() async { @@ -322,12 +320,12 @@ var y = {null: null}; '''; await resolveTestCode(code); var xNode = findNode.variableDeclaration('x = '); - var xElement = xNode.declaredElement!; - assertType(xElement.type, 'List'); + var xFragment = xNode.declaredFragment!; + assertType(xFragment.element.type, 'List'); var yNode = findNode.variableDeclaration('y = '); - var yElement = yNode.declaredElement!; - assertType(yElement.type, 'Map'); + var yFragment = yNode.declaredFragment!; + assertType(yFragment.element.type, 'Map'); } test_logicalAnd() async { @@ -475,12 +473,12 @@ main() { '''; await resolveTestCode(code); var xNode = findNode.variableDeclaration('x = '); - var xElement = xNode.declaredElement!; - expect(xElement.type, VoidTypeImpl.instance); + var xFragment = xNode.declaredFragment!; + expect(xFragment.element.type, VoidTypeImpl.instance); var yNode = findNode.variableDeclaration('y = '); - var yElement = yNode.declaredElement!; - expect(yElement.type, VoidTypeImpl.instance); + var yFragment = yNode.declaredFragment!; + expect(yFragment.element.type, VoidTypeImpl.instance); } test_voidType_topLevelFunction() async { @@ -493,12 +491,12 @@ main() { '''; await resolveTestCode(code); var xNode = findNode.variableDeclaration('x = '); - var xElement = xNode.declaredElement!; - expect(xElement.type, VoidTypeImpl.instance); + var xFragment = xNode.declaredFragment!; + expect(xFragment.element.type, VoidTypeImpl.instance); var yNode = findNode.variableDeclaration('y = '); - var yElement = yNode.declaredElement!; - expect(yElement.type, VoidTypeImpl.instance); + var yFragment = yNode.declaredFragment!; + expect(yFragment.element.type, VoidTypeImpl.instance); } void _assertTypeAnnotations() { @@ -528,7 +526,7 @@ main() { if (comment != null) { var expectedType = types[comment.offset]; if (expectedType != null) { - var element = node.staticElement as VariableElement; + var element = node.element as VariableElement2; String actualType = typeString(element.type); expect(actualType, expectedType, reason: '@${comment.offset}'); } From 70e77158e64833997f8de072f0ae6faa80aacfed Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Mon, 13 Jan 2025 22:04:10 -0800 Subject: [PATCH 24/76] Elements. Migrate lib/src/utilities/completion/optype.dart Change-Id: I46f1f2e6de31d2583b21c3f96699e85e0b4feab6 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403840 Commit-Queue: Keerti Parthasarathy Reviewed-by: Brian Wilkerson --- .../lib/src/utilities/completion/optype.dart | 67 +++++++++---------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart index 9e364cfe6bdb..19e2da891726 100644 --- a/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart +++ b/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart @@ -2,16 +2,13 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:analyzer/dart/ast/syntactic_entity.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/dart/ast/extensions.dart'; -import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element; import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart'; import 'package:analyzer_plugin/src/utilities/extensions/token.dart'; @@ -218,20 +215,20 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { void visitArgumentList(ArgumentList node) { final entity = this.entity; var parent = node.parent; - List? parameters; + List? parameters; if (parent is InstanceCreationExpression) { - Element? constructor; + Element2? constructor; var name = parent.constructorName.name; if (name != null) { - constructor = name.staticElement; + constructor = name.element; } else { - var classElem = parent.constructorName.type.element; - if (classElem is ClassElement) { - constructor = classElem.unnamedConstructor; + var classElem = parent.constructorName.type.element2; + if (classElem is ClassElement2) { + constructor = classElem.unnamedConstructor2; } } - if (constructor is ConstructorElement) { - parameters = constructor.parameters; + if (constructor is ConstructorElement2) { + parameters = constructor.formalParameters; } else if (constructor == null) { // If unresolved, then include named arguments optype.includeNamedArgumentSuggestions = true; @@ -239,22 +236,22 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { } else if (parent is InvocationExpression) { var function = parent.function; if (function is SimpleIdentifier) { - var elem = function.staticElement; - if (elem is FunctionTypedElement) { - parameters = elem.parameters; + var elem = function.element; + if (elem is FunctionTypedElement2) { + parameters = elem.formalParameters; } else if (elem == null) { // If unresolved, then include named arguments optype.includeNamedArgumentSuggestions = true; } } } else if (parent is SuperConstructorInvocation) { - parameters = parent.staticElement?.parameters; + parameters = parent.element?.formalParameters; } else if (parent is RedirectingConstructorInvocation) { - parameters = parent.staticElement?.parameters; + parameters = parent.element?.formalParameters; } else if (parent is Annotation) { - var constructor = parent.element; - if (constructor is ConstructorElement) { - parameters = constructor.parameters; + var constructor = parent.element2; + if (constructor is ConstructorElement2) { + parameters = constructor.formalParameters; } else if (constructor == null) { // If unresolved, then include named arguments optype.includeNamedArgumentSuggestions = true; @@ -651,7 +648,7 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { } else { var grandparent = parent.parent; if (grandparent is ArgumentList) { - var parameter = parent.staticParameterElement; + var parameter = parent.correspondingParameter; if (parameter != null) { var parameterType = parameter.type; if (parameterType is FunctionType && @@ -663,7 +660,7 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { } } } else if (parent is MethodDeclaration) { - type = parent.declaredElement?.returnType; + type = parent.declaredFragment?.element.returnType; if (type != null && type is VoidType) { optype.includeVoidReturnSuggestions = true; } @@ -1155,10 +1152,10 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { optype.completionLocation = 'TypeArgumentList_argument'; } else { var argKind = 'unnamed'; - var method = node.methodName.staticElement; - if (method is MethodElement && - method.parameters.isNotEmpty && - method.parameters[0].isNamed) { + var method = node.methodName.element; + if (method is MethodElement2 && + method.formalParameters.isNotEmpty && + method.formalParameters[0].isNamed) { argKind = 'named'; } optype.completionLocation = 'ArgumentList_method_$argKind'; @@ -1192,21 +1189,21 @@ class _OpTypeAstVisitor extends GeneralizingAstVisitor { // Check for named parameters in constructor calls. var grandparent = node.parent?.parent; - Element? element; + Element2? element; if (grandparent is ConstructorReferenceNode) { - element = grandparent.staticElement; + element = grandparent.element; } else if (grandparent is InstanceCreationExpression) { - element = grandparent.constructorName.staticElement; + element = grandparent.constructorName.element; } else if (grandparent is MethodInvocation) { - element = grandparent.methodName.staticElement; + element = grandparent.methodName.element; } - if (element is ExecutableElement) { - var parameters = element.parameters; + if (element is ExecutableElement2) { + var parameters = element.formalParameters; var parameterElement = parameters.firstWhereOrNull((e) { - if (e is DefaultFieldFormalParameterElementImpl) { - return e.field?.name == node.name.label.name; + if (e is FieldFormalParameterElement2) { + return e.field2?.name3 == node.name.label.name; } - return e.isNamed && e.name == node.name.label.name; + return e.isNamed && e.name3 == node.name.label.name; }); // Suggest tear-offs. if (parameterElement?.type is FunctionType) { From 37e3a7a75ea84238c22b636f3500d549e5a05e08 Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Tue, 14 Jan 2025 01:29:05 -0800 Subject: [PATCH 25/76] [deps] Roll jsshell & firefox to newer version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Firefox performs more strict validation when enabling the `js-string` builtin. Namely it requires the wasm array to `fromCharCodeArray` to be nullable (as per-spec), where D8 is more lenient and allows non-nullable wasm array just fine. Issue https://github.com/dart-lang/sdk/issues/59899 Change-Id: I22f2add0eacfaa4265011ca5f47cac92642b69d0 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404300 Reviewed-by: Ömer Ağacan Commit-Queue: Martin Kustermann --- DEPS | 4 ++-- sdk/lib/_internal/wasm/lib/js_helper_patch.dart | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/DEPS b/DEPS index 1c9ad4451a88..73acaa0b9be3 100644 --- a/DEPS +++ b/DEPS @@ -72,7 +72,7 @@ vars = { # instructions. d8, the V8 shell, is always checked out. "checkout_javascript_engines": False, "d8_tag": "version:13.4.32", - "jsshell_tag": "version:133.0", + "jsshell_tag": "version:134.0", "jsc_tag": "version:288804", # https://chrome-infra-packages.appspot.com/p/fuchsia/third_party/clang @@ -174,7 +174,7 @@ vars = { "download_chrome": False, "chrome_tag": "132.0.6834.83", "download_firefox": False, - "firefox_tag": "133.0.3", + "firefox_tag": "134.0", # Emscripten is used in dart2wasm tests. "download_emscripten": False, diff --git a/sdk/lib/_internal/wasm/lib/js_helper_patch.dart b/sdk/lib/_internal/wasm/lib/js_helper_patch.dart index 1ddd5e8e4e0e..0b8aae1ce5f5 100644 --- a/sdk/lib/_internal/wasm/lib/js_helper_patch.dart +++ b/sdk/lib/_internal/wasm/lib/js_helper_patch.dart @@ -61,7 +61,7 @@ String jsStringToDartString(JSStringImpl jsString) { @pragma("wasm:import", "wasm:js-string.fromCharCodeArray") external WasmExternRef _jsStringFromCharCodeArray( - WasmArray array, + WasmArray? array, WasmI32 start, WasmI32 end, ); From 45d5b483da0fd271cd09430c2375844d39426a2e Mon Sep 17 00:00:00 2001 From: Tess Strickland Date: Tue, 14 Jan 2025 03:20:44 -0800 Subject: [PATCH 26/76] [dartfuzz] Handle more types in minimized literal generation. Previously, the minimizer only handled a small, handpicked set of types when replacing expressions with minimized literals of the expression's type. This CL adds minimal literal generation for any type that has a known constructor and generalizes handling of lists, sets, and maps. TEST=dartfuzz Change-Id: Ifeaacfd4dec1ba8f66f4fee9cf8c7fb74193b0d2 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403861 Reviewed-by: Ryan Macnak Commit-Queue: Tess Strickland --- runtime/tools/dartfuzz/dartfuzz.dart | 1164 +++++++++++++++++--------- runtime/tools/dartfuzz/minimize.py | 2 +- 2 files changed, 788 insertions(+), 378 deletions(-) diff --git a/runtime/tools/dartfuzz/dartfuzz.dart b/runtime/tools/dartfuzz/dartfuzz.dart index 2b73e2891ec6..1246d12d28e9 100644 --- a/runtime/tools/dartfuzz/dartfuzz.dart +++ b/runtime/tools/dartfuzz/dartfuzz.dart @@ -42,13 +42,13 @@ enum MethodType { ffiMethod, instanceMethod, callMethod, - extensionMethod + extensionMethod, } /// Base class for all methods in the program generated by DartFuzz. abstract class Method { Method(this.name, this.parameters, this.fuzzer) - : recursionAllowed = fuzzer.coinFlip() { + : recursionAllowed = fuzzer.coinFlip() { if (recursionAllowed) { // Add the recursion depth parameter. parameters.add(DartType.INT); @@ -58,12 +58,17 @@ abstract class Method { String get recursionDepthParamName => '$paramName${parameters.length - 1}'; DartType get returnType => parameters[0]; - void emitCallParameters(int depth, bool isRecursiveCall, - {RhsFilter? rhsFilter}) { + void emitCallParameters( + int depth, + bool isRecursiveCall, { + RhsFilter? rhsFilter, + }) { if (isRecursiveCall && !recursionAllowed) { throw StateError('Did not expect a recursive call in $name'); } - fuzzer.emitParenWrapped(() => fuzzer.emitCommaSeparated((int i) { + fuzzer.emitParenWrapped( + () => fuzzer.emitCommaSeparated( + (int i) { // If this function can be called recursively, the last parameter is the // recursion depth parameter. if (i == parameters.length - 1 && recursionAllowed) { @@ -78,7 +83,11 @@ abstract class Method { } else { fuzzer.emitExpr(depth, parameters[i], rhsFilter: rhsFilter); } - }, parameters.length, start: 1)); + }, + parameters.length, + start: 1, + ), + ); } void disableRecursionScope(Function callback) { @@ -89,15 +98,18 @@ abstract class Method { } void emitRecursionBaseCase() { - fuzzer.emitIfStatement(() { - fuzzer.emit('$recursionDepthParamName >= '); - fuzzer.emitSmallPositiveInt(); - }, () { - // Temporarily set recursionAllowed to false so that we don't have a - // recursive call in the return statement of the base case. - disableRecursionScope(fuzzer.emitReturn); - return false; - }); + fuzzer.emitIfStatement( + () { + fuzzer.emit('$recursionDepthParamName >= '); + fuzzer.emitSmallPositiveInt(); + }, + () { + // Temporarily set recursionAllowed to false so that we don't have a + // recursive call in the return statement of the base case. + disableRecursionScope(fuzzer.emitReturn); + return false; + }, + ); } void emitFunctionBody() { @@ -150,10 +162,12 @@ abstract class Method { fuzzer.emitNewline(); } - String emitCall(int depth, - {RhsFilter? rhsFilter, - bool includeSemicolon = false, - bool isRecursiveCall = false}) { + String emitCall( + int depth, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + bool isRecursiveCall = false, + }) { var outputName = name; fuzzer.emitLn(outputName, newline: false); emitCallParameters(depth + 1, isRecursiveCall, rhsFilter: rhsFilter); @@ -177,15 +191,18 @@ abstract class Method { /// Class for global methods generated by DartFuzz. class GlobalMethod extends Method { GlobalMethod(String name, List parameters, DartFuzz fuzzer) - : super(name, parameters, fuzzer); + : super(name, parameters, fuzzer); } /// Class for ffi methods generated by DartFuzz. class FfiMethod extends Method { FfiMethod( - String namePrefix, int index, List parameters, DartFuzz fuzzer) - : ffiCastName = '${namePrefix}FfiCast$index', - super('${namePrefix}Ffi$index', parameters, fuzzer); + String namePrefix, + int index, + List parameters, + DartFuzz fuzzer, + ) : ffiCastName = '${namePrefix}FfiCast$index', + super('${namePrefix}Ffi$index', parameters, fuzzer); @override void emitFunctionBody() { @@ -216,14 +233,19 @@ class FfiMethod extends Method { /// Class for instance methods generated by DartFuzz. class InstanceMethod extends Method { InstanceMethod( - String name, List parameters, DartFuzz fuzzer, this.className) - : super(name, parameters, fuzzer); + String name, + List parameters, + DartFuzz fuzzer, + this.className, + ) : super(name, parameters, fuzzer); @override - String emitCall(int depth, - {RhsFilter? rhsFilter, - bool includeSemicolon = false, - bool isRecursiveCall = false}) { + String emitCall( + int depth, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + bool isRecursiveCall = false, + }) { var outputName = name; if (fuzzer.currentClassIndex == null) { // If we're calling an instance method from outside the class, then we @@ -243,13 +265,15 @@ class InstanceMethod extends Method { class CallMethod extends Method { CallMethod(List parameters, DartFuzz fuzzer, this.className) - : super('call', parameters, fuzzer); + : super('call', parameters, fuzzer); @override - String emitCall(int depth, - {RhsFilter? rhsFilter, - bool includeSemicolon = false, - bool isRecursiveCall = false}) { + String emitCall( + int depth, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + bool isRecursiveCall = false, + }) { String outputName; outputName = '$className()'; fuzzer.emitLn(outputName, newline: false); @@ -273,9 +297,14 @@ class CallMethod extends Method { // Class for extension methods generated by DartFuzz. class ExtensionMethod extends Method { - ExtensionMethod(String name, List parameters, DartFuzz fuzzer, - this.className, this.extensionName, this.type) - : super(name, parameters, fuzzer); + ExtensionMethod( + String name, + List parameters, + DartFuzz fuzzer, + this.className, + this.extensionName, + this.type, + ) : super(name, parameters, fuzzer); @override String emitCall( int depth, { @@ -291,9 +320,10 @@ class ExtensionMethod extends Method { // using a variable of the Dart type or using explicit extension // application. if (fuzzer.currentClassIndex == null || type != null) { - var invokingObject = type != null - ? fuzzer.pickScalarVar(type!.toNonNullable()) - : '$className()'; + var invokingObject = + type != null + ? fuzzer.pickScalarVar(type!.toNonNullable()) + : '$className()'; if (fuzzer.coinFlip()) { outputName = '$extensionName($invokingObject).$name'; @@ -345,11 +375,16 @@ class DartApi { if (ffi) { typeToLibraryMethods[DartType.INT] = [ ...[ - DartLib('intComputation', - [DartType.VOID, ...List.filled(4, DartType.INT)], true), + DartLib('intComputation', [ + DartType.VOID, + ...List.filled(4, DartType.INT), + ], true), DartLib('takeMaxUint16', [DartType.VOID, DartType.INT], true), - DartLib( - 'sumPlus42', [DartType.VOID, DartType.INT, DartType.INT], true), + DartLib('sumPlus42', [ + DartType.VOID, + DartType.INT, + DartType.INT, + ], true), DartLib('returnMaxUint8', [DartType.VOID, DartType.VOID], true), DartLib('returnMaxUint16', [DartType.VOID, DartType.VOID], true), DartLib('returnMaxUint32', [DartType.VOID, DartType.VOID], true), @@ -358,10 +393,14 @@ class DartApi { DartLib('returnMinInt32', [DartType.VOID, DartType.VOID], true), DartLib('takeMinInt16', [DartType.VOID, DartType.INT], true), DartLib('takeMinInt32', [DartType.VOID, DartType.INT], true), - DartLib('uintComputation', - [DartType.VOID, ...List.filled(4, DartType.INT)], true), - DartLib('sumSmallNumbers', - [DartType.VOID, ...List.filled(6, DartType.INT)], true), + DartLib('uintComputation', [ + DartType.VOID, + ...List.filled(4, DartType.INT), + ], true), + DartLib('sumSmallNumbers', [ + DartType.VOID, + ...List.filled(6, DartType.INT), + ], true), DartLib('takeMinInt8', [DartType.VOID, DartType.INT], true), DartLib('takeMaxUint32', [DartType.VOID, DartType.INT], true), DartLib('takeMaxUint8', [DartType.VOID, DartType.INT], true), @@ -369,24 +408,33 @@ class DartApi { DartLib('minInt32', [DartType.VOID, DartType.VOID], true), // Use small int to avoid overflow divergences due to size // differences in intptr_t on 32-bit and 64-bit platforms. - DartLib('sumManyIntsOdd', - [DartType.VOID, ...List.filled(11, DartType.INT)], true, - restrictions: [ - Restriction.none, - ...List.filled(11, Restriction.small) - ]), - DartLib('sumManyInts', - [DartType.VOID, ...List.filled(10, DartType.INT)], true, - restrictions: [ - Restriction.none, - ...List.filled(10, Restriction.small) - ]), - DartLib('regress37069', - [DartType.VOID, ...List.filled(11, DartType.INT)], true, - restrictions: [ - Restriction.none, - ...List.filled(11, Restriction.small) - ]), + DartLib( + 'sumManyIntsOdd', + [DartType.VOID, ...List.filled(11, DartType.INT)], + true, + restrictions: [ + Restriction.none, + ...List.filled(11, Restriction.small), + ], + ), + DartLib( + 'sumManyInts', + [DartType.VOID, ...List.filled(10, DartType.INT)], + true, + restrictions: [ + Restriction.none, + ...List.filled(10, Restriction.small), + ], + ), + DartLib( + 'regress37069', + [DartType.VOID, ...List.filled(11, DartType.INT)], + true, + restrictions: [ + Restriction.none, + ...List.filled(11, Restriction.small), + ], + ), ], ...DartLib.intLibs, ]; @@ -394,37 +442,34 @@ class DartApi { typeToLibraryMethods[DartType.DOUBLE] = [ if (ffi) ...[ DartLib('times1_337Float', [DartType.VOID, DartType.DOUBLE], true), - DartLib( - 'sumManyDoubles', - [DartType.VOID, ...List.filled(10, DartType.DOUBLE)], - true), + DartLib('sumManyDoubles', [ + DartType.VOID, + ...List.filled(10, DartType.DOUBLE), + ], true), DartLib('times1_337Double', [DartType.VOID, DartType.DOUBLE], true), - DartLib( - 'sumManyNumbers', - [ - DartType.VOID, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE, - DartType.INT, - DartType.DOUBLE - ], - true), + DartLib('sumManyNumbers', [ + DartType.VOID, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + DartType.INT, + DartType.DOUBLE, + ], true), DartLib('inventFloatValue', [DartType.VOID, DartType.VOID], true), DartLib('smallDouble', [DartType.VOID, DartType.VOID], true), ], @@ -438,8 +483,16 @@ class DartApi { /// Class that generates a random, but runnable Dart program for fuzz testing. class DartFuzz { - DartFuzz(this.seed, this.fp, this.ffi, this.flatTp, this.file, - {this.minimize = false, this.smask, this.emask}); + DartFuzz( + this.seed, + this.fp, + this.ffi, + this.flatTp, + this.file, { + this.minimize = false, + this.smask, + this.emask, + }); void run() { // Initialize program variables. @@ -459,19 +512,31 @@ class DartFuzz { globalVars = fillTypes1(limit: numGlobalVars); globalVars.addAll(dartType.allTypes); globalMethods = getMethods( - numGlobalMethods, numMethodParams, MethodType.globalMethod, - namePrefix: methodName); + numGlobalMethods, + numMethodParams, + MethodType.globalMethod, + namePrefix: methodName, + ); classFields = fillTypes2(limit2: numClasses, limit1: numLocalVars); final numClassMethods = 1 + numClasses - classFields.length; - classMethods = getClassMethods(classFields.length, numClassMethods, - numMethodParams, fillTypes1(limit: numMethodParams)); + classMethods = getClassMethods( + classFields.length, + numClassMethods, + numMethodParams, + fillTypes1(limit: numMethodParams), + ); virtualClassMethods = >>[]; classParents = []; // Setup optional ffi methods and types. if (ffi) { - globalMethods.addAll(getMethods( - numGlobalMethods, numMethodParams, MethodType.ffiMethod, - namePrefix: methodName)); + globalMethods.addAll( + getMethods( + numGlobalMethods, + numMethodParams, + MethodType.ffiMethod, + namePrefix: methodName, + ), + ); } // Generate. emitHeader(); @@ -479,9 +544,13 @@ class DartFuzz { emitMethods(globalMethods); for (var i = 0; i < numDartTypeExtensions; ++i) { var type = oneOfSet(dartType.allTypes); - emitAndAddExtensionMethods(globalMethods, type.name, '${methodName}E$i', - '$methodName${i}_Extension', - type: type); + emitAndAddExtensionMethods( + globalMethods, + type.name, + '${methodName}E$i', + '$methodName${i}_Extension', + type: type, + ); } emitClasses(); emitMain(); @@ -494,15 +563,21 @@ class DartFuzz { assert(localVars.isEmpty); } - List getMethods(int maxMethods, int maxParams, MethodType methodType, - {String? className, - String? extensionName, - String? namePrefix, - DartType? type}) { + List getMethods( + int maxMethods, + int maxParams, + MethodType methodType, { + String? className, + String? extensionName, + String? namePrefix, + DartType? type, + }) { final list = []; for (var i = 0, n = chooseOneUpTo(maxMethods); i < n; i++) { final params = fillTypes1( - limit: maxParams, isFfi: methodType == MethodType.ffiMethod); + limit: maxParams, + isFfi: methodType == MethodType.ffiMethod, + ); switch (methodType) { case MethodType.globalMethod: list.add(GlobalMethod('$namePrefix$i', params, this)); @@ -514,8 +589,16 @@ class DartFuzz { list.add(InstanceMethod('$namePrefix$i', params, this, className!)); break; case MethodType.extensionMethod: - list.add(ExtensionMethod( - '$namePrefix$i', params, this, className!, extensionName!, type)); + list.add( + ExtensionMethod( + '$namePrefix$i', + params, + this, + className!, + extensionName!, + type, + ), + ); break; default: break; @@ -524,13 +607,21 @@ class DartFuzz { return list; } - List> getClassMethods(int numClasses, int maxMethods, - int maxParams, List callMethodParams) { + List> getClassMethods( + int numClasses, + int maxMethods, + int maxParams, + List callMethodParams, + ) { final methodsForAllClasses = >[]; for (var i = 0; i < numClasses; i++) { final methodsForCurrentClass = getMethods( - maxMethods, maxParams, MethodType.instanceMethod, - className: 'X$i', namePrefix: '$methodName${i}_'); + maxMethods, + maxParams, + MethodType.instanceMethod, + className: 'X$i', + namePrefix: '$methodName${i}_', + ); // Add the call method for the current class. The prototype for the call // method is pre-decided. This is because we are possibly overriding the // parent class' call method, in which case the prototype should be the @@ -566,8 +657,11 @@ class DartFuzz { void emitZero() => emit('0'); - void emitTryCatchFinally(Function tryBody, Function catchBody, - {Function? finallyBody}) { + void emitTryCatchFinally( + Function tryBody, + Function catchBody, { + Function? finallyBody, + }) { emitLn('try ', newline: false); emitBraceWrapped(() => tryBody()); emit(' on OutOfMemoryError '); @@ -582,8 +676,11 @@ class DartFuzz { } } - dynamic emitWrapped(List pair, Function exprEmitter, - {bool shouldIndent = true}) { + dynamic emitWrapped( + List pair, + Function exprEmitter, { + bool shouldIndent = true, + }) { assert(pair.length == 2); emit(pair[0]); if (shouldIndent) { @@ -601,10 +698,15 @@ class DartFuzz { return result; } - dynamic emitParenWrapped(Function exprEmitter, - {bool includeSemicolon = false}) { - final result = - emitWrapped(const ['(', ')'], exprEmitter, shouldIndent: false); + dynamic emitParenWrapped( + Function exprEmitter, { + bool includeSemicolon = false, + }) { + final result = emitWrapped( + const ['(', ')'], + exprEmitter, + shouldIndent: false, + ); if (includeSemicolon) { emit(';'); } @@ -617,8 +719,12 @@ class DartFuzz { dynamic emitSquareBraceWrapped(Function exprEmitter) => emitWrapped(const ['[', ']'], exprEmitter, shouldIndent: false); - dynamic emitCommaSeparated(Function(int) elementBuilder, int length, - {int start = 0, bool newline = false}) { + dynamic emitCommaSeparated( + Function(int) elementBuilder, + int length, { + int start = 0, + bool newline = false, + }) { for (var i = start; i < length; ++i) { elementBuilder(i); if (i + 1 != length) { @@ -642,8 +748,10 @@ class DartFuzz { } bool emitIfStatement( - Function ifConditionEmitter, bool Function() ifBodyEmitter, - {bool Function()? elseBodyEmitter}) { + Function ifConditionEmitter, + bool Function() ifBodyEmitter, { + bool Function()? elseBodyEmitter, + }) { emitLn('if ', newline: false); emitParenWrapped(ifConditionEmitter); emit(' '); @@ -656,12 +764,17 @@ class DartFuzz { return ifMayFallThrough || elseMayFallThrough; } - void emitImport(String library, {String? asName}) => (asName == null) - ? emitLn("import '$library';") - : emitLn("import '$library' as $asName;"); + void emitImport(String library, {String? asName}) => + (asName == null) + ? emitLn("import '$library';") + : emitLn("import '$library' as $asName;"); - void emitBinaryComparison(Function e1, String op, Function e2, - {bool includeSemicolon = false}) { + void emitBinaryComparison( + Function e1, + String op, + Function e2, { + bool includeSemicolon = false, + }) { e1(); emit(' $op '); e2(); @@ -688,34 +801,80 @@ class DartFuzz { skipExpr = false; } - void emitMinimizedLiteral(DartType tp) { - switch (tp) { - case DartType.BOOL: - emit('true'); - break; - case DartType.INT: - emit('1'); - break; - case DartType.DOUBLE: - emit('1.0'); - break; - case DartType.STRING: - emit('"a"'); - break; - case DartType.LIST_INT: - emit('[1]'); - break; - case DartType.SET_INT: - emit('{1}'); - break; - case DartType.MAP_INT_STRING: - emit('{1: "a"}'); - break; - default: - throw 'Unknown DartType $tp'; + void _emitMinimizedLiteralHelper(StringBuffer sb, DartType tp) { + // isListType returns true for types like Uint8List which can't be written + // simply with a list notation, so check this before the isListType check. + if (tp.hasConstructor(tp)) { + final constructorName = tp.constructors(tp).first; + if (constructorName.isNotEmpty) { + sb.write('${tp.name}.$constructorName'); + } else { + sb.write(tp.name); + } + sb.write('('); + final paramTypes = tp.constructorParameters(tp, constructorName); + if (paramTypes.isNotEmpty) { + _emitMinimizedLiteralHelper(sb, paramTypes[0]); + for (int i = 1; i < paramTypes.length; i++) { + sb.write(','); + _emitMinimizedLiteralHelper(sb, paramTypes[i]); + } + } + sb.write(')'); + } else if (DartType.isListType(tp)) { + sb.write('['); + _emitMinimizedLiteralHelper(sb, tp.elementType(tp)); + sb.write(']'); + } else if (DartType.isSetType(tp)) { + sb.write('{'); + _emitMinimizedLiteralHelper(sb, tp.elementType(tp)); + sb.write('}'); + } else if (DartType.isMapType(tp)) { + sb.write('{'); + _emitMinimizedLiteralHelper(sb, tp.indexType(tp)); + sb.write(':'); + _emitMinimizedLiteralHelper(sb, tp.elementType(tp)); + sb.write('}'); + } else { + switch (tp.toNonNullable()) { + case DartType.ENDIAN: + sb.write('Endian.little'); + break; + case DartType.NUM: + if (coinFlip()) { + _emitMinimizedLiteralHelper(sb, DartType.INT); + } else { + _emitMinimizedLiteralHelper(sb, DartType.DOUBLE); + } + break; + case DartType.BOOL: + sb.write('true'); + break; + case DartType.INT: + sb.write('1'); + break; + case DartType.DOUBLE: + sb.write('1.0'); + break; + case DartType.STRING: + sb.write('"a"'); + break; + default: + if (!tp.isNullable) { + throw 'Unknown DartType $tp'; + } + // Only fall back to null if an non-null element cannot be generated. + sb.write('null'); + } } } + void emitMinimizedLiteral(DartType tp) { + final sb = StringBuffer(); + _emitMinimizedLiteralHelper(sb, tp); + emit(sb.toString()); + } + // Process the opening of a statement. // Determine whether the statement should be skipped based on the // statement index stored in stmtCntr and the statement mask stored @@ -811,8 +970,10 @@ class DartFuzz { void emitHeader() { emitLn('// The Dart Project Fuzz Tester ($version).'); emitLn('// Program generated as:'); - emitLn('// dart dartfuzz.dart --seed $seed --${fp ? "" : "no-"}fp ' - '--${ffi ? "" : "no-"}ffi --${flatTp ? "" : "no-"}flat'); + emitLn( + '// dart dartfuzz.dart --seed $seed --${fp ? "" : "no-"}fp ' + '--${ffi ? "" : "no-"}ffi --${flatTp ? "" : "no-"}flat', + ); emitLn('// @dart=2.14'); emitNewline(); emitImport('dart:async'); @@ -831,12 +992,20 @@ class DartFuzz { emitNewline(); } - void emitFfiCast(String dartFuncName, String ffiFuncName, String typeName, - List pars) { + void emitFfiCast( + String dartFuncName, + String ffiFuncName, + String typeName, + List pars, + ) { emit('${pars[0].name} Function'); - emitParenWrapped(() => emitCommaSeparated( - (int i) => emit('${pars[i].name}'), pars.length, - start: 1)); + emitParenWrapped( + () => emitCommaSeparated( + (int i) => emit('${pars[i].name}'), + pars.length, + start: 1, + ), + ); emit(' $dartFuncName = ffi.Pointer.fromFunction<$typeName>'); emitParenWrapped(() { emit('$ffiFuncName, '); @@ -924,25 +1093,35 @@ class DartFuzz { emitNewline(); emitNewline(); emitAndAddExtensionMethods( - classMethods[currentClassIndex!], - 'X$currentClassIndex', - 'XE$currentClassIndex', - '$methodName${currentClassIndex}_Extension'); + classMethods[currentClassIndex!], + 'X$currentClassIndex', + 'XE$currentClassIndex', + '$methodName${currentClassIndex}_Extension', + ); currentClassIndex = null; } } void emitAndAddExtensionMethods( - List methodList, className, extensionName, namePrefix, - {DartType? type}) { + List methodList, + className, + extensionName, + namePrefix, { + DartType? type, + }) { var endIndex = methodList.length; - methodList.addAll(getMethods(numExtensionMethodsPerClass, numMethodParams, + methodList.addAll( + getMethods( + numExtensionMethodsPerClass, + numMethodParams, MethodType.extensionMethod, className: className, // Randomly select between named and anonymous extensions. extensionName: coinFlip() ? extensionName : '', namePrefix: namePrefix, - type: type)); + type: type, + ), + ); emit('extension $extensionName on $className '); emitBraceWrapped(() { // Emit the newly added methods. @@ -960,74 +1139,93 @@ class DartFuzz { void emitLoadFfiLib() { if (ffi) { - emitLn('// The following throws an uncaught exception if the ffi library ' - 'is not found.'); - emitLn('// By not catching this exception, we terminate the program with ' - 'a full stack trace'); + emitLn( + '// The following throws an uncaught exception if the ffi library ' + 'is not found.', + ); + emitLn( + '// By not catching this exception, we terminate the program with ' + 'a full stack trace', + ); emitLn('// which, in turn, flags the problem prominently'); - emitIfStatement(() => emit('ffiTestFunctions == null'), - () => emitPrint('Did not load ffi test functions')); + emitIfStatement( + () => emit('ffiTestFunctions == null'), + () => emitPrint('Did not load ffi test functions'), + ); emitNewline(); } } void emitMain() => emitFunctionDefinition('main', () { - emitLoadFfiLib(); - - // Call each global method once. - for (var i = 0; i < globalMethods.length; i++) { - late String outputName; - emitTryCatchFinally( - () => outputName = - globalMethods[i].emitCall(1, includeSemicolon: true), - () => emitPrint('${outputName}() throws')); - emitNewline(); - } + emitLoadFfiLib(); + + // Call each global method once. + for (var i = 0; i < globalMethods.length; i++) { + late String outputName; + emitTryCatchFinally( + () => outputName = globalMethods[i].emitCall(1, includeSemicolon: true), + () => emitPrint('${outputName}() throws'), + ); + emitNewline(); + } - // Call each class method once. - for (var i = 0; i < classMethods.length; i++) { - for (var j = 0; j < classMethods[i].length; j++) { + // Call each class method once. + for (var i = 0; i < classMethods.length; i++) { + for (var j = 0; j < classMethods[i].length; j++) { + late String outputName; + emitNewline(); + emitTryCatchFinally( + () => + outputName = classMethods[i][j].emitCall( + 1, + includeSemicolon: true, + ), + () => emitPrint('$outputName throws'), + ); + } + // Call each virtual class method once. + var parentClass = classParents[i]; + while (parentClass >= 0) { + if (virtualClassMethods[i].containsKey(parentClass)) { + for ( + var j = 0; + j < virtualClassMethods[i][parentClass]!.length; + j++ + ) { late String outputName; emitNewline(); emitTryCatchFinally( - () => outputName = - classMethods[i][j].emitCall(1, includeSemicolon: true), - () => emitPrint('$outputName throws')); - } - // Call each virtual class method once. - var parentClass = classParents[i]; - while (parentClass >= 0) { - if (virtualClassMethods[i].containsKey(parentClass)) { - for (var j = 0; - j < virtualClassMethods[i][parentClass]!.length; - j++) { - late String outputName; - emitNewline(); - emitTryCatchFinally( - () => outputName = classMethods[parentClass][j] - .emitCall(1, includeSemicolon: true), - () => emitPrint('$outputName throws')); - } - } - parentClass = classParents[parentClass]; + () => + outputName = classMethods[parentClass][j].emitCall( + 1, + includeSemicolon: true, + ), + () => emitPrint('$outputName throws'), + ); } } + parentClass = classParents[parentClass]; + } + } - emitNewline(); - emitTryCatchFinally(() { - emitLn('X${classFields.length - 1}().run();', newline: false); - }, () { - emitPrint('X${classFields.length - 1}().run() throws'); - }); + emitNewline(); + emitTryCatchFinally( + () { + emitLn('X${classFields.length - 1}().run();', newline: false); + }, + () { + emitPrint('X${classFields.length - 1}().run() throws'); + }, + ); + emitNewline(); + emitTryCatchFinally(() { + for (var i = 0; i < globalVars.length; i++) { + emitPrint('$varName$i: \$$varName$i'); emitNewline(); - emitTryCatchFinally(() { - for (var i = 0; i < globalVars.length; i++) { - emitPrint('$varName$i: \$$varName$i'); - emitNewline(); - } - }, () => emitPrint('print() throws')); - }); + } + }, () => emitPrint('print() throws')); + }); // // Declarations. @@ -1037,17 +1235,23 @@ class DartFuzz { for (var i = 0; i < vars.length; i++) { var tp = vars[i]; final varName = '$name$i'; - emitVariableDeclaration(varName, tp, - initializerEmitter: () => emitConstructorOrLiteral(0, tp)); + emitVariableDeclaration( + varName, + tp, + initializerEmitter: () => emitConstructorOrLiteral(0, tp), + ); } emitNewline(); } - void emitVariableDeclaration(String name, DartType tp, - {Function? initializerEmitter, - bool indent = true, - bool newline = true, - bool includeSemicolon = true}) { + void emitVariableDeclaration( + String name, + DartType tp, { + Function? initializerEmitter, + bool indent = true, + bool newline = true, + bool includeSemicolon = true, + }) { final typeName = tp.dartName; if (indent) { emitIndentation(); @@ -1062,10 +1266,14 @@ class DartFuzz { } } - void emitParDecls(List pars) => emitCommaSeparated((int i) { - var tp = pars[i]; - emit('${tp.dartName} $paramName$i'); - }, pars.length, start: 1); + void emitParDecls(List pars) => emitCommaSeparated( + (int i) { + var tp = pars[i]; + emit('${tp.dartName} $paramName$i'); + }, + pars.length, + start: 1, + ); // // Comments (for FE and analysis tools). @@ -1171,12 +1379,16 @@ class DartFuzz { // Emit a one-way if statement. bool emitIf1(int depth) => emitIfStatement( - () => emitExpr(0, DartType.BOOL), () => emitStatements(depth + 1)); + () => emitExpr(0, DartType.BOOL), + () => emitStatements(depth + 1), + ); // Emit a two-way if statement. bool emitIf2(int depth) => emitIfStatement( - () => emitExpr(0, DartType.BOOL), () => emitStatements(depth + 1), - elseBodyEmitter: () => emitStatements(depth + 1)); + () => emitExpr(0, DartType.BOOL), + () => emitStatements(depth + 1), + elseBodyEmitter: () => emitStatements(depth + 1), + ); // Emit a simple increasing for-loop. bool emitFor(int depth) { @@ -1188,10 +1400,19 @@ class DartFuzz { emitLn('for ', newline: false); emitParenWrapped(() { final name = '$localName$i'; - emitVariableDeclaration(name, DartType.INT, - initializerEmitter: emitZero, newline: false, indent: false); - emitBinaryComparison(() => emit(name), '<', emitSmallPositiveInt, - includeSemicolon: true); + emitVariableDeclaration( + name, + DartType.INT, + initializerEmitter: emitZero, + newline: false, + indent: false, + ); + emitBinaryComparison( + () => emit(name), + '<', + emitSmallPositiveInt, + includeSemicolon: true, + ); emit('$name++'); }); emitBraceWrapped(() { @@ -1284,11 +1505,15 @@ class DartFuzz { emitIndentation(); emitBraceWrapped(() { final name = '$localName$i'; - emitVariableDeclaration(name, DartType.INT, - initializerEmitter: () => emitSmallPositiveInt()); + emitVariableDeclaration( + name, + DartType.INT, + initializerEmitter: () => emitSmallPositiveInt(), + ); emitLn('while ', newline: false); emitParenWrapped( - () => emitBinaryComparison(() => emit('--$name'), '>', emitZero)); + () => emitBinaryComparison(() => emit('--$name'), '>', emitZero), + ); emitBraceWrapped(() { nest++; iterVars.add(name); @@ -1325,9 +1550,13 @@ class DartFuzz { }); emit(' while '); emitParenWrapped( - () => emitBinaryComparison( - () => emit('++$name'), '<', emitSmallPositiveInt), - includeSemicolon: true); + () => emitBinaryComparison( + () => emit('++$name'), + '<', + emitSmallPositiveInt, + ), + includeSemicolon: true, + ); }); emitNewline(); return true; @@ -1359,8 +1588,10 @@ class DartFuzz { emitBraceWrapped(() { bodyEmitter(); emitNewline(); - emitLn('break;', - newline: false); // always generate, avoid FE complaints + emitLn( + 'break;', + newline: false, + ); // always generate, avoid FE complaints }); } @@ -1371,8 +1602,10 @@ class DartFuzz { var step = chooseOneUpTo(10); final maxCases = 3; for (var i = 0; i < maxCases; i++, start += step) { - emitCase(() => emitStatement(depth + 1), - kase: (i == 2 && coinFlip()) ? null : start); + emitCase( + () => emitStatement(depth + 1), + kase: (i == 2 && coinFlip()) ? null : start, + ); if (i + 1 != maxCases) { emitNewline(); } @@ -1388,11 +1621,15 @@ class DartFuzz { var tp = oneOfSet(dartType.allTypes); final i = localVars.length; final name = '$localName$i'; - emitVariableDeclaration(name, tp, initializerEmitter: () { - localVars.add(null); // declared, but don't use - emitExpr(0, tp); - localVars.removeLast(); // will get type - }); + emitVariableDeclaration( + name, + tp, + initializerEmitter: () { + localVars.add(null); // declared, but don't use + emitExpr(0, tp); + localVars.removeLast(); // will get type + }, + ); localVars.add(tp); emitStatements(depth + 1); localVars.removeLast(); @@ -1562,8 +1799,12 @@ class DartFuzz { emit("'"); } - void emitElementExpr(int depth, DartType tp, - {RhsFilter? rhsFilter, bool isConst = false}) { + void emitElementExpr( + int depth, + DartType tp, { + RhsFilter? rhsFilter, + bool isConst = false, + }) { // Inside a constant collection, keep collection elements constants too. if (isConst) { if (DartType.isCollectionType(tp)) { @@ -1579,8 +1820,12 @@ class DartFuzz { } } - void emitElement(int depth, DartType tp, - {RhsFilter? rhsFilter, bool isConst = false}) { + void emitElement( + int depth, + DartType tp, { + RhsFilter? rhsFilter, + bool isConst = false, + }) { // Get the element type contained in type tp. // E.g. element type of List is String. final elementType = dartType.elementType(tp); @@ -1592,12 +1837,20 @@ class DartFuzz { emitElementExpr(depth, indexType, rhsFilter: rhsFilter, isConst: isConst); emit(' : '); // Emit construct for the map value type. - emitElementExpr(depth, elementType, - rhsFilter: rhsFilter, isConst: isConst); + emitElementExpr( + depth, + elementType, + rhsFilter: rhsFilter, + isConst: isConst, + ); } else { // List and Set types. - emitElementExpr(depth, elementType, - rhsFilter: rhsFilter, isConst: isConst); + emitElementExpr( + depth, + elementType, + rhsFilter: rhsFilter, + isConst: isConst, + ); } } @@ -1605,8 +1858,11 @@ class DartFuzz { var r = (depth <= exprDepth) ? choose(10) : 10; // TODO (felih): disable complex collection constructs for new types for // now. - if (!{DartType.MAP_INT_STRING, DartType.LIST_INT, DartType.SET_INT} - .contains(tp)) { + if (!{ + DartType.MAP_INT_STRING, + DartType.LIST_INT, + DartType.SET_INT, + }.contains(tp)) { emitElement(depth, tp, rhsFilter: rhsFilter); return; } @@ -1618,8 +1874,9 @@ class DartFuzz { break; case 1: emitLn('if ', newline: false); - emitParenWrapped(() => - emitElementExpr(depth + 1, DartType.BOOL, rhsFilter: rhsFilter)); + emitParenWrapped( + () => emitElementExpr(depth + 1, DartType.BOOL, rhsFilter: rhsFilter), + ); emitCollectionElement(depth + 1, tp, rhsFilter: rhsFilter); if (coinFlip()) { emitNewline(); @@ -1640,26 +1897,47 @@ class DartFuzz { localVars.add(null); // declared, but don't use switch (choose(3)) { case 0: - emitVariableDeclaration(local, DartType.INT, - initializerEmitter: emitZero, indent: false); - emitBinaryComparison(() => emit(local), '<', - () => emitSmallPositiveInt(limit: 16), - includeSemicolon: true); + emitVariableDeclaration( + local, + DartType.INT, + initializerEmitter: emitZero, + indent: false, + ); + emitBinaryComparison( + () => emit(local), + '<', + () => emitSmallPositiveInt(limit: 16), + includeSemicolon: true, + ); emit('$local++'); break; case 1: - emitVariableDeclaration(local, DartType.INT, - includeSemicolon: false, indent: false); + emitVariableDeclaration( + local, + DartType.INT, + includeSemicolon: false, + indent: false, + ); emit(' in '); - emitCollection(depth + 1, DartType.LIST_INT, - rhsFilter: rhsFilter); + emitCollection( + depth + 1, + DartType.LIST_INT, + rhsFilter: rhsFilter, + ); break; default: - emitVariableDeclaration(local, DartType.INT, - includeSemicolon: false, indent: false); + emitVariableDeclaration( + local, + DartType.INT, + includeSemicolon: false, + indent: false, + ); emit(' in '); - emitCollection(depth + 1, DartType.SET_INT, - rhsFilter: rhsFilter); + emitCollection( + depth + 1, + DartType.SET_INT, + rhsFilter: rhsFilter, + ); break; } localVars.removeLast(); // will get type @@ -1701,9 +1979,10 @@ class DartFuzz { // Collection length decreases as depth increases. var collectionLength = max(1, 8 - depth); emitCommaSeparated( - (int _) => emitCollectionElement(depth, tp, rhsFilter: rhsFilter), - chooseOneUpTo(collectionLength), - newline: DartType.isMapType(tp)); + (int _) => emitCollectionElement(depth, tp, rhsFilter: rhsFilter), + chooseOneUpTo(collectionLength), + newline: DartType.isMapType(tp), + ); }, shouldIndent: DartType.isMapType(tp)); } @@ -1719,14 +1998,16 @@ class DartFuzz { var elementType = dartType.elementType(tp); l = 'const <${elementType.dartName}>{'; r = '}'; - canHaveElements = (elementType != DartType.DOUBLE) && + canHaveElements = + (elementType != DartType.DOUBLE) && (elementType != DartType.DOUBLE_NULLABLE); } else if (DartType.isMapType(tp)) { var indexType = dartType.indexType(tp); var elementType = dartType.elementType(tp); l = 'const <${indexType.dartName},${elementType.dartName}>{'; r = '}'; - canHaveElements = (indexType != DartType.DOUBLE) && + canHaveElements = + (indexType != DartType.DOUBLE) && (indexType != DartType.DOUBLE_NULLABLE); } else { throw "Unrecognized collection type $tp"; @@ -1739,13 +2020,19 @@ class DartFuzz { emit(r); return; } - emitWrapped([l, r], - () => emitElement(depth, tp, rhsFilter: rhsFilter, isConst: true), - shouldIndent: DartType.isMapType(tp)); + emitWrapped( + [l, r], + () => emitElement(depth, tp, rhsFilter: rhsFilter, isConst: true), + shouldIndent: DartType.isMapType(tp), + ); } - void emitLiteral(int depth, DartType tp, - {bool smallPositiveValue = false, RhsFilter? rhsFilter}) { + void emitLiteral( + int depth, + DartType tp, { + bool smallPositiveValue = false, + RhsFilter? rhsFilter, + }) { if (tp.isNullable) { if (choose(20) == 0) { emitNull(); @@ -1793,8 +2080,12 @@ class DartFuzz { // Emit a constructor for a type, this can either be a trivial constructor // (i.e. parsed from a literal) or an actual function invocation. - void emitConstructorOrLiteral(int depth, DartType tp, - {RhsFilter? rhsFilter, bool includeSemicolon = false}) { + void emitConstructorOrLiteral( + int depth, + DartType tp, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + }) { // If there is at least one non trivial constructor for the type tp // select one of these constructors. if (dartType.hasConstructor(tp)) { @@ -1812,14 +2103,20 @@ class DartFuzz { } emitParenWrapped(() { // Iterate over constructor parameters. - var constructorParameters = - dartType.constructorParameters(tp, constructor); + var constructorParameters = dartType.constructorParameters( + tp, + constructor, + ); emitCommaSeparated((int i) { // If we are emitting a constructor parameter, we want to use small // values to avoid programs that run out of memory. // TODO (felih): maybe allow occasionally? - emitLiteral(depth + 1, constructorParameters[i], - smallPositiveValue: true, rhsFilter: rhsFilter); + emitLiteral( + depth + 1, + constructorParameters[i], + smallPositiveValue: true, + rhsFilter: rhsFilter, + ); }, constructorParameters.length); }); } else { @@ -1832,8 +2129,11 @@ class DartFuzz { } // Pick an existing variable of the given type. - String? pickScalarVar(DartType tp, - {bool isLhs = false, RhsFilter? rhsFilter}) { + String? pickScalarVar( + DartType tp, { + bool isLhs = false, + RhsFilter? rhsFilter, + }) { // Randomly specialize interface type, unless emitting left hand side. if (!isLhs) tp = maybeSpecializeInterface(tp); // Collect all choices from globals, fields, locals, and parameters. @@ -1895,8 +2195,11 @@ class DartFuzz { return '${choices.elementAt(choose(choices.length))}'; } - String? emitScalarVar(DartType tp, - {bool isLhs = false, RhsFilter? rhsFilter}) { + String? emitScalarVar( + DartType tp, { + bool isLhs = false, + RhsFilter? rhsFilter, + }) { final emittedVar = pickScalarVar(tp, isLhs: isLhs, rhsFilter: rhsFilter); if (emittedVar != null) { if (rhsFilter != null && (emittedVar == rhsFilter.lhsVar)) { @@ -1907,8 +2210,13 @@ class DartFuzz { return emittedVar; } - String? emitSubscriptedVar(int depth, DartType tp, - {bool isLhs = false, String? assignOp, RhsFilter? rhsFilter}) { + String? emitSubscriptedVar( + int depth, + DartType tp, { + bool isLhs = false, + String? assignOp, + RhsFilter? rhsFilter, + }) { String? ret; // Check if type tp is an indexable element of some other type. if (dartType.isIndexableElementType(tp)) { @@ -1926,33 +2234,48 @@ class DartFuzz { final indexType = dartType.indexType(iterType); // Emit a variable of the selected list or map type. ret = emitScalarVar(iterType, isLhs: isLhs, rhsFilter: rhsFilter); - emitSquareBraceWrapped(() => - // Emit an expression resolving into the index type. For - // collection type, only constant collections are used - // to avoid rehashing the same value into many entries. - DartType.isCollectionType(indexType) - ? emitConstCollection(depth + 1, indexType) - : emitExpr(depth + 1, indexType)); + emitSquareBraceWrapped( + () => + // Emit an expression resolving into the index type. For + // collection type, only constant collections are used + // to avoid rehashing the same value into many entries. + DartType.isCollectionType(indexType) + ? emitConstCollection(depth + 1, indexType) + : emitExpr(depth + 1, indexType), + ); // Map.[] and Expando.[] have a nullable result, but we should not write // map[key]! = value. if (!tp.isNullable && !isLhs) { emit('!'); } } else { - ret = emitScalarVar(tp, - isLhs: isLhs, rhsFilter: rhsFilter); // resort to scalar + ret = emitScalarVar( + tp, + isLhs: isLhs, + rhsFilter: rhsFilter, + ); // resort to scalar } return ret; } - String? emitVar(int depth, DartType tp, - {bool isLhs = false, String? assignOp, RhsFilter? rhsFilter}) { + String? emitVar( + int depth, + DartType tp, { + bool isLhs = false, + String? assignOp, + RhsFilter? rhsFilter, + }) { switch (choose(2)) { case 0: return emitScalarVar(tp, isLhs: isLhs, rhsFilter: rhsFilter); default: - return emitSubscriptedVar(depth, tp, - isLhs: isLhs, assignOp: assignOp, rhsFilter: rhsFilter); + return emitSubscriptedVar( + depth, + tp, + isLhs: isLhs, + assignOp: assignOp, + rhsFilter: rhsFilter, + ); } } @@ -1976,7 +2299,8 @@ class DartFuzz { emit(oneOfSet(dartType.uniOps(tp))); var uniOpParam = tp.toNonNullable(); emitParenWrapped( - () => emitExpr(depth + 1, uniOpParam, rhsFilter: rhsFilter)); + () => emitExpr(depth + 1, uniOpParam, rhsFilter: rhsFilter), + ); }); } @@ -2059,8 +2383,12 @@ class DartFuzz { } // Emit library call. - void emitLibraryCall(int depth, DartType tp, - {RhsFilter? rhsFilter, bool includeSemicolon = false}) { + void emitLibraryCall( + int depth, + DartType tp, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + }) { var lib = getLibraryMethod(tp); if (lib == null || (!fp && isTypedDataFloatType(lib.proto))) { // We cannot find a library method, or we found a library method but its @@ -2074,9 +2402,14 @@ class DartFuzz { var prototype = lib.proto; // Receiver. if (prototype[0] != DartType.VOID) { - emitParenWrapped(() => emitArg( - depth + 1, prototype[0], lib.getRestriction(0), - rhsFilter: rhsFilter)); + emitParenWrapped( + () => emitArg( + depth + 1, + prototype[0], + lib.getRestriction(0), + rhsFilter: rhsFilter, + ), + ); emit('.'); } // Call. @@ -2086,11 +2419,15 @@ class DartFuzz { emitParenWrapped(() { if (prototype[1] != DartType.VOID) { emitCommaSeparated( - (int i) => emitArg( - depth + 1, prototype[i], lib.getRestriction(i), - rhsFilter: rhsFilter), - prototype.length, - start: 1); + (int i) => emitArg( + depth + 1, + prototype[i], + lib.getRestriction(i), + rhsFilter: rhsFilter, + ), + prototype.length, + start: 1, + ); } }); } @@ -2105,16 +2442,24 @@ class DartFuzz { } // Helper for a method call. - bool pickedCall(int depth, DartType tp, List methods, int m, - {RhsFilter? rhsFilter}) { + bool pickedCall( + int depth, + DartType tp, + List methods, + int m, { + RhsFilter? rhsFilter, + }) { for (var i = m - 1; i >= 0; i--) { if (tp == methods[i].returnType) { var isRecursiveCall = (currentMethod == methods[i]); if (isRecursiveCall && !methods[i].recursionAllowed) { continue; } - methods[i].emitCall(depth + 1, - rhsFilter: rhsFilter, isRecursiveCall: isRecursiveCall); + methods[i].emitCall( + depth + 1, + rhsFilter: rhsFilter, + isRecursiveCall: isRecursiveCall, + ); return true; } } @@ -2127,8 +2472,13 @@ class DartFuzz { if (currentClassIndex == null) { // Outside a class but inside a method: call backward in global methods. if (currentMethodIndex != null && - pickedCall(depth, tp, globalMethods, currentMethodIndex! + 1, - rhsFilter: rhsFilter)) { + pickedCall( + depth, + tp, + globalMethods, + currentMethodIndex! + 1, + rhsFilter: rhsFilter, + )) { return; } } else { @@ -2155,8 +2505,13 @@ class DartFuzz { m1 = currentMethodIndex! + 1; } final m2 = globalMethods.length; - if (pickedCall(depth, tp, classMethods[classIndex], m1, - rhsFilter: rhsFilter) || + if (pickedCall( + depth, + tp, + classMethods[classIndex], + m1, + rhsFilter: rhsFilter, + ) || pickedCall(depth, tp, globalMethods, m2, rhsFilter: rhsFilter)) { return; } @@ -2165,8 +2520,12 @@ class DartFuzz { } // Emit expression. - void emitExpr(int depth, DartType tp, - {RhsFilter? rhsFilter, bool includeSemicolon = false}) { + void emitExpr( + int depth, + DartType tp, { + RhsFilter? rhsFilter, + bool includeSemicolon = false, + }) { final resetExprStmt = processExprOpen(tp); // Continuing nested expressions becomes less likely as the depth grows. if (choose(depth + 1) > exprDepth) { @@ -2187,8 +2546,11 @@ class DartFuzz { emitPreOrPostExpr(depth, tp, rhsFilter: rhsFilter); break; case 4: - emitLibraryCall(depth, tp, - rhsFilter: RhsFilter.cloneEmpty(rhsFilter)); + emitLibraryCall( + depth, + tp, + rhsFilter: RhsFilter.cloneEmpty(rhsFilter), + ); break; case 5: emitMethodCall(depth, tp, rhsFilter: RhsFilter.cloneEmpty(rhsFilter)); @@ -2234,8 +2596,12 @@ class DartFuzz { : null; // Emit a library argument, possibly subject to restrictions. - void emitArg(int depth, DartType type, Restriction restriction, - {RhsFilter? rhsFilter}) { + void emitArg( + int depth, + DartType type, + Restriction restriction, { + RhsFilter? rhsFilter, + }) { if ((type == DartType.INT) && (restriction == Restriction.small)) { emitSmallPositiveInt(); } else if ((type == DartType.DOUBLE) && !fp) { @@ -2265,8 +2631,11 @@ class DartFuzz { return list; } - List> fillTypes2( - {bool isFfi = false, int limit2 = 4, int limit1 = 4}) { + List> fillTypes2({ + bool isFfi = false, + int limit2 = 4, + int limit1 = 4, + }) { final list = >[]; for (var i = 0, n = chooseOneUpTo(limit2); i < n; i++) { list.add(fillTypes1(limit: limit1, isFfi: isFfi)); @@ -2294,8 +2663,14 @@ class DartFuzz { void emitFfiType(DartType tp) { if (tp == DartType.INT) { - emit(oneOf( - const ['ffi.Int8', 'ffi.Int16', 'ffi.Int32', 'ffi.Int64'])); + emit( + oneOf(const [ + 'ffi.Int8', + 'ffi.Int16', + 'ffi.Int32', + 'ffi.Int64', + ]), + ); } else if (tp == DartType.DOUBLE) { emit(oneOf(const ['ffi.Float', 'ffi.Double'])); } else { @@ -2309,9 +2684,13 @@ class DartFuzz { emitFfiType(pars[0]); emit(' Function'); emitParenWrapped( - () => emitCommaSeparated((int i) => emitFfiType(pars[i]), pars.length, - start: 1), - includeSemicolon: true); + () => emitCommaSeparated( + (int i) => emitFfiType(pars[i]), + pars.length, + start: 1, + ), + includeSemicolon: true, + ); emitNewline(); emitNewline(); } @@ -2459,7 +2838,7 @@ class DartFuzz { 0xffffffff7fffffff, 0xffffffff80000000, 0xffffffff80000001, - 0xffffffffffffffff + 0xffffffffffffffff, ]; } @@ -2486,25 +2865,48 @@ void main(List arguments) { const kMini = 'mini'; const kSMask = 'smask'; const kEMask = 'emask'; - final parser = ArgParser() - ..addOption(kSeed, - help: 'random seed (0 forces time-based seed)', defaultsTo: '0') - ..addFlag(kFp, help: 'enables floating-point operations', defaultsTo: true) - ..addFlag(kFfi, - help: 'enables FFI method calls (default: off)', defaultsTo: false) - ..addFlag(kFlat, - help: 'enables flat types (default: off)', defaultsTo: false) - // Minimization mode extensions. - ..addFlag(kMini, - help: 'enables minimization mode (default: off)', defaultsTo: false) - ..addOption(kSMask, - help: 'Bitmask indicating which statements to omit' - '(Bit=1 omits)', - defaultsTo: '0') - ..addOption(kEMask, - help: 'Bitmask indicating which expressions to omit' - '(Bit=1 omits)', - defaultsTo: '0'); + final parser = + ArgParser() + ..addOption( + kSeed, + help: 'random seed (0 forces time-based seed)', + defaultsTo: '0', + ) + ..addFlag( + kFp, + help: 'enables floating-point operations', + defaultsTo: true, + ) + ..addFlag( + kFfi, + help: 'enables FFI method calls (default: off)', + defaultsTo: false, + ) + ..addFlag( + kFlat, + help: 'enables flat types (default: off)', + defaultsTo: false, + ) + // Minimization mode extensions. + ..addFlag( + kMini, + help: 'enables minimization mode (default: off)', + defaultsTo: false, + ) + ..addOption( + kSMask, + help: + 'Bitmask indicating which statements to omit' + '(Bit=1 omits)', + defaultsTo: '0', + ) + ..addOption( + kEMask, + help: + 'Bitmask indicating which expressions to omit' + '(Bit=1 omits)', + defaultsTo: '0', + ); final ArgResults results; try { results = parser.parse(arguments); @@ -2521,8 +2923,16 @@ void main(List arguments) { final minimize = results[kMini]; final smask = BigInt.parse(results[kSMask]); final emask = BigInt.parse(results[kEMask]); - final dartFuzz = DartFuzz(seed, fp, ffi, flatTp, file, - minimize: minimize, smask: smask, emask: emask); + final dartFuzz = DartFuzz( + seed, + fp, + ffi, + flatTp, + file, + minimize: minimize, + smask: smask, + emask: emask, + ); dartFuzz.run(); file.closeSync(); // Print information that will be parsed by minimize.py diff --git a/runtime/tools/dartfuzz/minimize.py b/runtime/tools/dartfuzz/minimize.py index c9be86ae7adf..a54e440fe0db 100755 --- a/runtime/tools/dartfuzz/minimize.py +++ b/runtime/tools/dartfuzz/minimize.py @@ -139,7 +139,7 @@ def generate_dart(dartfuzz_cmd, dart_test, smask, mask, do_expr): p = subprocess.Popen(cmds, stdout=subprocess.PIPE) p_stdout, p_stderr = p.communicate() if p.returncode != 0: - raise 'Invalid return code on generate %d' % p.returncode + raise RuntimeError('Invalid return code on generate %d' % p.returncode) mask_new = 0 if do_expr: mask_new = int(p_stdout.decode().splitlines()[EXPRESSION_MASK_LINE]) From 6aeb8657810ab3dc55b2a60bcd4328be6490dd10 Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Tue, 14 Jan 2025 04:09:47 -0800 Subject: [PATCH 27/76] [dart2wasm] Workaround bug in JavaScriptCore/WebKit in test runner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The recent roll of JSC caused *many* failures on the dart2wasm-linux-optimized-jsc configuration. I believe this is due to a interpretation/optimization bug in JavaScriptCore/WebKit. => Filed https://bugs.webkit.org/show_bug.cgi?id=285902 It seems we can workaround this by passing `--useWasmIPInt=false` in the test runner for now. Issue https://github.com/dart-lang/sdk/issues/59899 Change-Id: Ie7ae7bf0a5654eb3362bc23934becd8162227992 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404104 Reviewed-by: Ömer Ağacan --- pkg/test_runner/lib/src/runtime_configuration.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/test_runner/lib/src/runtime_configuration.dart b/pkg/test_runner/lib/src/runtime_configuration.dart index 3f277af4dbeb..d0c7643bffe7 100644 --- a/pkg/test_runner/lib/src/runtime_configuration.dart +++ b/pkg/test_runner/lib/src/runtime_configuration.dart @@ -246,9 +246,13 @@ class JSCRuntimeConfiguration extends CommandLineJavaScriptRuntime { if (compiler != Compiler.dart2wasm) { throw 'No test runner setup for jsc + dart2js yet'; } + // TODO(https://bugs.webkit.org/show_bug.cgi?id=285902): Once the + // JavaScriptCore/WebKit bug is fixed we should be able to remove this + // again. + const jscBugWorkaround = '--shell-option=--useWasmIPInt=false'; return [ Dart2WasmCommandLineCommand(moniker, 'pkg/dart2wasm/tool/run_benchmark', - ['--jsc', ...arguments], environmentOverrides) + ['--jsc', jscBugWorkaround, ...arguments], environmentOverrides) ]; } } From ac9acf51659ec55d0dc1096305a0c7c7a5aa34dc Mon Sep 17 00:00:00 2001 From: Daco Harkes Date: Tue, 14 Jan 2025 04:54:20 -0800 Subject: [PATCH 28/76] [deps] Roll dart-lang/native MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I556a179784952cf12ff97da155d0f5596f91b500 Cq-Include-Trybots: luci.dart.try:pkg-linux-debug-try,pkg-linux-release-arm64-try,pkg-linux-release-try,pkg-mac-release-arm64-try,pkg-mac-release-try,pkg-win-release-arm64-try,pkg-win-release-try Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403985 Reviewed-by: Moritz Sümmermann Commit-Queue: Daco Harkes --- DEPS | 2 +- pkg/dartdev/test/native_assets/helpers.dart | 2 + pkg/dartdev/test/native_assets/test_test.dart | 44 +++++++++++-------- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/DEPS b/DEPS index 73acaa0b9be3..feda6329ceb2 100644 --- a/DEPS +++ b/DEPS @@ -141,7 +141,7 @@ vars = { "markdown_rev": "19aaded4300d24bedcbf52ade792b203ddf030b0", "material_color_utilities_rev": "799b6ba2f3f1c28c67cc7e0b4f18e0c7d7f3c03e", # dart-native-interop-team@ is rolling breaking changes manually while the assets features are in experimental. - "native_rev": "14368a80bae9e3f381a2e59c91405338d82451ee", # disable tools/rev_sdk_deps.dart + "native_rev": "f179ec2693179e48ff1fce827914fd1711c1a941", # disable tools/rev_sdk_deps.dart "protobuf_rev": "b7dd58cdbd879beee4c3fbf8ee80fce8e97bad26", "pub_rev": "58de642dc1d07601f6eb2b4ecd94555c0210106b", # disable tools/rev_sdk_deps.dart "shelf_rev": "bf799519cda2898a7c5af06dcfdd5fe6443afd79", diff --git a/pkg/dartdev/test/native_assets/helpers.dart b/pkg/dartdev/test/native_assets/helpers.dart index c985ebbeed41..3e4efab9cf7e 100644 --- a/pkg/dartdev/test/native_assets/helpers.dart +++ b/pkg/dartdev/test/native_assets/helpers.dart @@ -184,8 +184,10 @@ Future nativeAssetsTest( 'dart_app', 'drop_dylib_link', 'native_add_duplicate', + 'native_add_version_skew', 'native_add', 'native_dynamic_linking', + 'system_library', 'treeshaking_native_libs', ], Platform.script.resolve( diff --git a/pkg/dartdev/test/native_assets/test_test.dart b/pkg/dartdev/test/native_assets/test_test.dart index 0a3cdf2b1ddb..f85c69cce111 100644 --- a/pkg/dartdev/test/native_assets/test_test.dart +++ b/pkg/dartdev/test/native_assets/test_test.dart @@ -13,27 +13,33 @@ void main(List args) async { // No --source option, `dart run` from source does not output target program // stdout. - test('dart test', timeout: longTimeout, () async { - await nativeAssetsTest('native_add', (packageUri) async { - final result = await runDart( - arguments: [ - '--enable-experiment=native-assets', - 'test', - ], - workingDirectory: packageUri, - logger: logger, - ); - expect( - result.stdout, - stringContainsInOrder( - [ - 'native add test', - 'All tests passed!', + for (final package in [ + 'native_add', + 'native_add_version_skew', + 'native_dynamic_linking', + 'system_library', + ]) { + test('package:$package dart test', timeout: longTimeout, () async { + await nativeAssetsTest(package, (packageUri) async { + final result = await runDart( + arguments: [ + '--enable-experiment=native-assets', + 'test', ], - ), - ); + workingDirectory: packageUri, + logger: logger, + ); + expect( + result.stdout, + stringContainsInOrder( + [ + 'All tests passed!', + ], + ), + ); + }); }); - }); + } test('dart run test:test', timeout: longTimeout, () async { await nativeAssetsTest('native_add', (packageUri) async { From e13db8b7739def53f2c2d1609839c40464fd740e Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Tue, 14 Jan 2025 05:07:38 -0800 Subject: [PATCH 29/76] [dart2wasm] Remove --turboshaft-wasm flag (which was removed from D8) in test runner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Running tests currently result in a warning by D8: Warning: unknown flag --turboshaft-wasm. Turboshaft was enabled by default in V8 and is no longer exposed as a flag. Change-Id: I487f145ba60b20d7c61397c4ad4c5af1d0263b60 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404320 Reviewed-by: Ömer Ağacan Commit-Queue: Martin Kustermann --- pkg/test_runner/lib/src/compiler_configuration.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/pkg/test_runner/lib/src/compiler_configuration.dart b/pkg/test_runner/lib/src/compiler_configuration.dart index a8776ea232bd..2dbee62fe480 100644 --- a/pkg/test_runner/lib/src/compiler_configuration.dart +++ b/pkg/test_runner/lib/src/compiler_configuration.dart @@ -609,7 +609,6 @@ class Dart2WasmCompilerConfiguration extends CompilerConfiguration { final isD8 = runtimeConfiguration is D8RuntimeConfiguration; return [ if (isD8) ...[ - '--shell-option=--turboshaft-wasm', '--shell-option=--experimental-wasm-imported-strings', ], wasmFilename, From 61336f32ab43c11747eb22ff6d1ca91c38b987c6 Mon Sep 17 00:00:00 2001 From: Martin Kustermann Date: Tue, 14 Jan 2025 05:20:33 -0800 Subject: [PATCH 30/76] [dart2wasm] Mark timing out test as SkipSlow on all browsers, not just Chrome MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The root cause is that an `asyncEnd()` doesn't get executed which will make the test not print `unittest-suite-success` which will make the test controller keep waiting indefinitly until the test times out. => This is true on all browsers, not just Chrome Though commandline JS engines don't have this problem as they will simply exit once there's no longer work and event loop is empty. => Here the test runner will recognize the missing `unittest-suite-success` and report the tests as failing. Issue https://github.com/dart-lang/sdk/issues/55182 Change-Id: Id217e9bd715d99f9927e7e18b03385aa2880b27f Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404107 Reviewed-by: Ömer Ağacan Commit-Queue: Martin Kustermann --- tests/co19/co19-dart2wasm.status | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/co19/co19-dart2wasm.status b/tests/co19/co19-dart2wasm.status index 8e96ee9d4f9d..6e7acf4139d3 100644 --- a/tests/co19/co19-dart2wasm.status +++ b/tests/co19/co19-dart2wasm.status @@ -15,5 +15,5 @@ LibTest/io/*: SkipByDesign # dart:io is not supported. LibTest/isolate/*: SkipByDesign # dart:isolate is not supported. LibTest/mirrors/*: SkipByDesign # dart:mirrors is not supported. -[ $compiler == dart2wasm && $runtime == chrome ] -Language/Expressions/Function_Invocation/async_generator_invokation_t10: SkipSlow # Issue(http://dartbug.com/55025) +[ $compiler == dart2wasm && $browser ] +Language/Expressions/Function_Invocation/async_generator_invokation_t10: SkipSlow # Issue(http://dartbug.com/55182): Will timeout on browsers (due to no asyncEnd() firing) but eagerly fail on commandline JS engines. From e1ba3ea504fb561cfdc3cdc67c5ae61fe0c19d4a Mon Sep 17 00:00:00 2001 From: Paul Berry Date: Tue, 14 Jan 2025 06:40:18 -0800 Subject: [PATCH 31/76] [_fe_analyzer_shared] Move TypeConstraintGatherer to its own file. Since the class `TypeConstraintGatherer` (which is only used in `_fe_analyzer_shared`'s unit tests) is now used both by `type_constraint_gatherer_test.dart` and by `mini_ast.dart`, it makes sense for it to live in its own file. Change-Id: I7c8a58cfbf3724e2c8313b701345bc47ce032522 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404060 Commit-Queue: Paul Berry Reviewed-by: Chloe Stefantsova --- pkg/_fe_analyzer_shared/test/mini_ast.dart | 3 +- .../test/mini_type_constraint_gatherer.dart | 112 ++++++++ .../type_constraint_gatherer_test.dart | 255 ++++++------------ 3 files changed, 189 insertions(+), 181 deletions(-) create mode 100644 pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart diff --git a/pkg/_fe_analyzer_shared/test/mini_ast.dart b/pkg/_fe_analyzer_shared/test/mini_ast.dart index e9b5c314d4f3..a0f57e0c5722 100644 --- a/pkg/_fe_analyzer_shared/test/mini_ast.dart +++ b/pkg/_fe_analyzer_shared/test/mini_ast.dart @@ -34,9 +34,8 @@ import 'package:_fe_analyzer_shared/src/type_inference/variable_bindings.dart'; import 'package:_fe_analyzer_shared/src/types/shared_type.dart'; import 'package:test/test.dart'; -import 'type_inference/type_constraint_gatherer_test.dart'; - import 'mini_ir.dart'; +import 'mini_type_constraint_gatherer.dart'; import 'mini_types.dart'; final RegExp _locationRegExp = diff --git a/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart b/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart new file mode 100644 index 000000000000..ef5dba028c55 --- /dev/null +++ b/pkg/_fe_analyzer_shared/test/mini_type_constraint_gatherer.dart @@ -0,0 +1,112 @@ +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer_operations.dart'; +import 'package:_fe_analyzer_shared/src/type_inference/type_constraint.dart'; +import 'package:_fe_analyzer_shared/src/types/shared_type.dart'; + +import 'mini_ast.dart'; +import 'mini_types.dart'; + +class TypeConstraintGatherer extends TypeConstraintGenerator + with + TypeConstraintGeneratorMixin { + @override + final Set typeParametersToConstrain = {}; + + @override + final bool enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr; + + @override + final MiniAstOperations typeAnalyzerOperations = MiniAstOperations(); + + final constraints = []; + + TypeConstraintGatherer(Set typeVariablesBeingConstrained, + {this.enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr = false}) + : super(inferenceUsingBoundsIsEnabled: false) { + for (var typeVariableName in typeVariablesBeingConstrained) { + typeParametersToConstrain + .add(TypeRegistry.addTypeParameter(typeVariableName)); + } + } + + @override + TypeConstraintGeneratorState get currentState => + TypeConstraintGeneratorState(constraints.length); + + @override + void addLowerConstraintForParameter(TypeParameter typeParameter, Type lower, + {required Node? astNodeForTesting}) { + constraints.add('$lower <: $typeParameter'); + } + + @override + void addUpperConstraintForParameter(TypeParameter typeParameter, Type upper, + {required Node? astNodeForTesting}) { + constraints.add('$typeParameter <: $upper'); + } + + @override + Map> + computeConstraints() { + // TODO(cstefantsova): implement computeConstraints + throw UnimplementedError(); + } + + @override + void eliminateTypeParametersInGeneratedConstraints( + Object eliminator, TypeConstraintGeneratorState eliminationStartState, + {required Node? astNodeForTesting}) { + // TODO(paulberry): implement eliminateTypeParametersInGeneratedConstraints + } + + @override + List? getTypeArgumentsAsInstanceOf(Type type, String typeDeclaration) { + // We just have a few cases hardcoded here to make the tests work. + // TODO(paulberry): if this gets too unwieldy, replace it with a more + // general implementation. + switch ((type, typeDeclaration)) { + case (PrimaryType(name: 'List', :var args), 'Iterable'): + // List inherits from Iterable + return args; + case (PrimaryType(name: 'MyListOfInt'), 'List'): + // MyListOfInt inherits from List + return [Type('int')]; + case (PrimaryType(name: 'Future'), 'int'): + case (PrimaryType(name: 'int'), 'String'): + case (PrimaryType(name: 'List'), 'Future'): + case (PrimaryType(name: 'String'), 'int'): + case (PrimaryType(name: 'Future'), 'String'): + // Unrelated types + return null; + default: + throw UnimplementedError( + 'getTypeArgumentsAsInstanceOf($type, $typeDeclaration)'); + } + } + + @override + ( + Type, + Type, { + List typeParametersToEliminate + }) instantiateFunctionTypesAndProvideFreshTypeParameters( + SharedFunctionTypeStructure + p, + SharedFunctionTypeStructure + q, + {required bool leftSchema}) { + // TODO(paulberry): implement instantiateFunctionTypesAndProvideEliminator + throw UnimplementedError(); + } + + @override + void restoreState(TypeConstraintGeneratorState state) { + constraints.length = state.count; + } +} diff --git a/pkg/_fe_analyzer_shared/test/type_inference/type_constraint_gatherer_test.dart b/pkg/_fe_analyzer_shared/test/type_inference/type_constraint_gatherer_test.dart index 57d600a96d7d..983c521795f6 100644 --- a/pkg/_fe_analyzer_shared/test/type_inference/type_constraint_gatherer_test.dart +++ b/pkg/_fe_analyzer_shared/test/type_inference/type_constraint_gatherer_test.dart @@ -3,12 +3,11 @@ // BSD-style license that can be found in the LICENSE file. import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer_operations.dart'; -import 'package:_fe_analyzer_shared/src/type_inference/type_constraint.dart'; -import 'package:_fe_analyzer_shared/src/types/shared_type.dart'; import 'package:checks/checks.dart'; import 'package:test/scaffolding.dart'; import '../mini_ast.dart'; +import '../mini_type_constraint_gatherer.dart'; import '../mini_types.dart'; main() { @@ -31,7 +30,7 @@ main() { Type('void Function()'), Type('void Function()'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); group('Matching functions with positional parameters:', () { @@ -41,7 +40,7 @@ main() { Type('void Function(int, String)'), Type('void Function(T, U)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); test('Some optional on LHS', () { @@ -52,7 +51,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); }); @@ -63,7 +62,7 @@ main() { Type('int Function(int)'), Type('String Function(int)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to parameter types', () { @@ -72,7 +71,7 @@ main() { Type('void Function(int)'), Type('void Function(String)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to optional parameters on RHS', () { @@ -81,7 +80,7 @@ main() { Type('void Function()'), Type('void Function([int])'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to more parameters being required on LHS', () { @@ -90,7 +89,7 @@ main() { Type('void Function(int)'), Type('void Function([int])'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -103,7 +102,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); test('Some optional on LHS', () { @@ -114,7 +113,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); test('Optional named parameter on LHS', () { @@ -125,7 +124,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int']); + check(tcg.constraints).unorderedEquals(['T <: int']); }); test('Extra optional named parameter on LHS', () { @@ -136,7 +135,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int']); + check(tcg.constraints).unorderedEquals(['T <: int']); }); }); @@ -147,7 +146,7 @@ main() { Type('int Function({int x})'), Type('String Function({int x})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to named parameter types', () { @@ -158,7 +157,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to required named parameter on LHS', () { @@ -169,7 +168,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to optional named parameter on RHS', () { @@ -178,7 +177,7 @@ main() { Type('void Function()'), Type('void Function({int x})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to named parameter on RHS, with decoys on LHS', @@ -190,7 +189,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -202,7 +201,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); group('Non-matching functions with named and positional parameters:', () { @@ -216,7 +215,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to positional parameter length mismatch', () { @@ -227,7 +226,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); }); @@ -239,7 +238,7 @@ main() { Type('()'), Type('()'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); group('Matching records:', () { @@ -249,7 +248,7 @@ main() { Type('(int, String)'), Type('(T, U)'), leftSchema: true, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['int <: T', 'String <: U']); + check(tcg.constraints).unorderedEquals(['int <: T', 'String <: U']); }); test('With named parameters', () { @@ -258,7 +257,7 @@ main() { Type('(int, {String foo})'), Type('(T, {U foo})'), leftSchema: true, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['int <: T', 'String <: U']); + check(tcg.constraints).unorderedEquals(['int <: T', 'String <: U']); }); }); @@ -269,7 +268,7 @@ main() { Type('(int,)'), Type('(String,)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to parameter numbers', () { @@ -278,7 +277,7 @@ main() { Type('()'), Type('(int,)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to more parameters on LHS', () { @@ -287,7 +286,7 @@ main() { Type('(int,)'), Type('()'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -298,7 +297,7 @@ main() { Type('({int x, String y})'), Type('({int x, String y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals([]); + check(tcg.constraints).unorderedEquals([]); }); test('Type parameters in RHS', () { @@ -307,7 +306,7 @@ main() { Type('({int x, String y})'), Type('({T x, U y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['int <: T', 'String <: U']); + check(tcg.constraints).unorderedEquals(['int <: T', 'String <: U']); }); test('Type parameters in LHS', () { @@ -316,7 +315,7 @@ main() { Type('({T x, U y})'), Type('({int x, String y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); }); @@ -327,7 +326,7 @@ main() { Type('({int x, String y})'), Type('({int x, String y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals([]); + check(tcg.constraints).unorderedEquals([]); }); test('Type parameters in RHS', () { @@ -336,7 +335,7 @@ main() { Type('({int x, String y})'), Type('({T x, U y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['int <: T', 'String <: U']); + check(tcg.constraints).unorderedEquals(['int <: T', 'String <: U']); }); test('Type parameters in LHS', () { @@ -345,7 +344,7 @@ main() { Type('({T x, U y})'), Type('({int x, String y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); }); @@ -358,7 +357,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to named parameter numbers', () { @@ -367,7 +366,7 @@ main() { Type('({T x, U y, num z})'), Type('({int x, String y})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-matching due to named parameter names', () { @@ -376,7 +375,7 @@ main() { Type('(num, {T x, U y})'), Type('(num, {int x, String x2})'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); }); @@ -389,7 +388,7 @@ main() { Type('FutureOr'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); test('FutureOr does not match FutureOr because arguments fail to match', @@ -400,7 +399,7 @@ main() { Type('FutureOr'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Future matches FutureOr favoring Future branch', () { @@ -416,7 +415,7 @@ main() { Type('Future'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['int <: T']); + check(tcg.constraints).deepEquals(['int <: T']); }); test('Future matches FutureOr preferring to generate constraints', () { @@ -432,7 +431,7 @@ main() { Type('Future<_>'), Type('FutureOr'), leftSchema: true, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['Future<_> <: T']); + check(tcg.constraints).deepEquals(['Future<_> <: T']); }); test('Type matches FutureOr favoring the Future branch', () { @@ -448,7 +447,7 @@ main() { Type('T'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: Future']); + check(tcg.constraints).deepEquals(['T <: Future']); }); test('Testing FutureOr as the lower bound of the constraint', () { @@ -457,7 +456,7 @@ main() { Type('FutureOr'), Type('dynamic'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: dynamic']); + check(tcg.constraints).deepEquals(['T <: dynamic']); }); test('FutureOr does not match Future in general', () { @@ -469,7 +468,7 @@ main() { Type('FutureOr<(T,)>'), Type('Future<(int,)>'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Testing nested FutureOr as the lower bound of the constraint', () { @@ -478,7 +477,7 @@ main() { Type('FutureOr>'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: dynamic', 'T <: dynamic']); + check(tcg.constraints).deepEquals(['T <: dynamic', 'T <: dynamic']); }); test('Future matches FutureOr with no constraints', () { @@ -489,7 +488,7 @@ main() { Type('Future'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Type matches FutureOr favoring the branch that matches', () { @@ -501,7 +500,7 @@ main() { Type('List'), Type('FutureOr>'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); group('Nullable FutureOr on RHS:', () { @@ -511,7 +510,7 @@ main() { Type('FutureOr'), Type('FutureOr?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Matches, according to CFE discrepancy', () { @@ -521,7 +520,7 @@ main() { Type('FutureOr'), Type('FutureOr?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); }); @@ -532,7 +531,7 @@ main() { Type('FutureOr?'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Matches, according to CFE discrepancy', () { @@ -542,7 +541,7 @@ main() { Type('FutureOr?'), Type('FutureOr'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); }); }); @@ -555,7 +554,7 @@ main() { Type('T?'), Type('Null'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: Null']); + check(tcg.constraints).deepEquals(['T <: Null']); }); test('Nullable does not match Nullable because base types fail to match', @@ -566,7 +565,7 @@ main() { Type('int?'), Type('String?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Nullable does not match non-nullable', () { @@ -576,7 +575,7 @@ main() { Type('(int, T)?'), Type('(int, String)'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Both LHS and RHS nullable, matching', () { @@ -585,7 +584,7 @@ main() { Type('T?'), Type('int?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); test('Both LHS and RHS nullable, not matching', () { @@ -594,7 +593,7 @@ main() { Type('(T, int)?'), Type('(int, String)?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isFalse(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -612,7 +611,7 @@ main() { Type('Null'), Type('T?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['Null <: T']); + check(tcg.constraints).deepEquals(['Null <: T']); }); test('Type matches Nullable favoring the non-Null branch', () { @@ -628,7 +627,7 @@ main() { Type('T'), Type('int?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); test('Null matches Nullable with no constraints', () { @@ -639,7 +638,7 @@ main() { Type('Null'), Type('int?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Dynamic matches Object?', () { @@ -648,7 +647,7 @@ main() { Type('dynamic'), Type('Object?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('void matches Object?', () { @@ -657,7 +656,7 @@ main() { Type('void'), Type('Object?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('LHS not nullable, matches with no constraints', () { @@ -666,7 +665,7 @@ main() { Type('int'), Type('int?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -678,7 +677,7 @@ main() { Type('Map'), Type('Map'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['T <: int', 'U <: String']); + check(tcg.constraints).unorderedEquals(['T <: int', 'U <: String']); }); test('Covariant, not matching', () { @@ -687,7 +686,7 @@ main() { Type('Map'), Type('Map'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(false); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Contravariant, matching', () { @@ -698,7 +697,7 @@ main() { Type('Contravariant'), Type('Contravariant'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals(['int <: T', 'String <: U']); + check(tcg.constraints).unorderedEquals(['int <: T', 'String <: U']); }); test('Contravariant, not matching', () { @@ -711,7 +710,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(false); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Invariant, matching', () { @@ -722,7 +721,7 @@ main() { Type('Invariant'), Type('Invariant'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).unorderedEquals( + check(tcg.constraints).unorderedEquals( ['T <: int', 'U <: String', 'int <: T', 'String <: U']); }); @@ -734,7 +733,7 @@ main() { Type('Invariant'), Type('Invariant'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(false); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Unrelated, matchable', () { @@ -747,7 +746,7 @@ main() { Type('Unrelated'), Type('Unrelated'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Unrelated, not matchable', () { @@ -760,7 +759,7 @@ main() { Type('Unrelated'), Type('Unrelated'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -771,7 +770,7 @@ main() { Type('List'), Type('Iterable'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).deepEquals(['T <: int']); + check(tcg.constraints).deepEquals(['T <: int']); }); test('Change in type args', () { @@ -780,7 +779,7 @@ main() { Type('MyListOfInt'), Type('List'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(true); - check(tcg._constraints).deepEquals(['int <: T']); + check(tcg.constraints).deepEquals(['int <: T']); }); test('LHS nullable', () { @@ -793,7 +792,7 @@ main() { Type('List?'), Type('Iterable'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(false); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('RHS nullable', () { @@ -806,7 +805,7 @@ main() { Type('List'), Type('Iterable?'), leftSchema: false, astNodeForTesting: Node.placeholder())) .equals(false); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -816,7 +815,7 @@ main() { Type('void Function()'), Type('int'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isNull(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); test('Non-interface type on RHS', () { @@ -825,7 +824,7 @@ main() { Type('int'), Type('void Function()'), leftSchema: false, astNodeForTesting: Node.placeholder())) .isNull(); - check(tcg._constraints).isEmpty(); + check(tcg.constraints).isEmpty(); }); }); @@ -839,7 +838,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['String <: T']); + check(tcg.constraints).unorderedEquals(['String <: T']); }); test('Promoted parameter on LHS', () { @@ -853,109 +852,7 @@ main() { leftSchema: false, astNodeForTesting: Node.placeholder())) .isTrue(); - check(tcg._constraints).unorderedEquals(['num <: T']); + check(tcg.constraints).unorderedEquals(['num <: T']); }); }); } - -class TypeConstraintGatherer extends TypeConstraintGenerator - with - TypeConstraintGeneratorMixin { - @override - final Set typeParametersToConstrain = {}; - - @override - final bool enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr; - - @override - final MiniAstOperations typeAnalyzerOperations = MiniAstOperations(); - - final _constraints = []; - - TypeConstraintGatherer(Set typeVariablesBeingConstrained, - {this.enableDiscrepantObliviousnessOfNullabilitySuffixOfFutureOr = false}) - : super(inferenceUsingBoundsIsEnabled: false) { - for (var typeVariableName in typeVariablesBeingConstrained) { - typeParametersToConstrain - .add(TypeRegistry.addTypeParameter(typeVariableName)); - } - } - - @override - TypeConstraintGeneratorState get currentState => - TypeConstraintGeneratorState(_constraints.length); - - @override - List? getTypeArgumentsAsInstanceOf(Type type, String typeDeclaration) { - // We just have a few cases hardcoded here to make the tests work. - // TODO(paulberry): if this gets too unwieldy, replace it with a more - // general implementation. - switch ((type, typeDeclaration)) { - case (PrimaryType(name: 'List', :var args), 'Iterable'): - // List inherits from Iterable - return args; - case (PrimaryType(name: 'MyListOfInt'), 'List'): - // MyListOfInt inherits from List - return [Type('int')]; - case (PrimaryType(name: 'Future'), 'int'): - case (PrimaryType(name: 'int'), 'String'): - case (PrimaryType(name: 'List'), 'Future'): - case (PrimaryType(name: 'String'), 'int'): - case (PrimaryType(name: 'Future'), 'String'): - // Unrelated types - return null; - default: - throw UnimplementedError( - 'getTypeArgumentsAsInstanceOf($type, $typeDeclaration)'); - } - } - - @override - void restoreState(TypeConstraintGeneratorState state) { - _constraints.length = state.count; - } - - @override - void addUpperConstraintForParameter(TypeParameter typeParameter, Type upper, - {required Node? astNodeForTesting}) { - _constraints.add('$typeParameter <: $upper'); - } - - @override - void addLowerConstraintForParameter(TypeParameter typeParameter, Type lower, - {required Node? astNodeForTesting}) { - _constraints.add('$lower <: $typeParameter'); - } - - @override - void eliminateTypeParametersInGeneratedConstraints( - Object eliminator, TypeConstraintGeneratorState eliminationStartState, - {required Node? astNodeForTesting}) { - // TODO(paulberry): implement eliminateTypeParametersInGeneratedConstraints - } - - @override - ( - Type, - Type, { - List typeParametersToEliminate - }) instantiateFunctionTypesAndProvideFreshTypeParameters( - SharedFunctionTypeStructure - p, - SharedFunctionTypeStructure - q, - {required bool leftSchema}) { - // TODO(paulberry): implement instantiateFunctionTypesAndProvideEliminator - throw UnimplementedError(); - } - - @override - Map> - computeConstraints() { - // TODO(cstefantsova): implement computeConstraints - throw UnimplementedError(); - } -} From 2dec4fe1eff1efcff5bd589347a4de6c9c5c12fe Mon Sep 17 00:00:00 2001 From: Keerti Parthasarathy Date: Tue, 14 Jan 2025 08:48:39 -0800 Subject: [PATCH 32/76] Elements. Migrate lib/src/dart/ast/utilities.dart Change-Id: I4db055c461a31b88b52dadb736738a203fe3ec1c Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404221 Commit-Queue: Keerti Parthasarathy Reviewed-by: Brian Wilkerson Reviewed-by: Phil Quitslund --- pkg/analyzer/lib/src/dart/ast/utilities.dart | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart index 2a415d5c7a8f..3157ea6a4dfa 100644 --- a/pkg/analyzer/lib/src/dart/ast/utilities.dart +++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - /// @docImport 'package:analyzer/src/lint/linter.dart'; /// @docImport 'package:analyzer/src/lint/linter_visitor.dart'; library; @@ -2349,7 +2347,7 @@ class NodeReplacer extends ThrowingAstVisitor { return true; } else if (identical(node.defaultValue, _oldNode)) { node.defaultValue = _newNode as ExpressionImpl; - var parameterElement = node.declaredElement; + var parameterElement = node.declaredFragment; if (parameterElement is DefaultParameterElementImpl) { parameterElement.constantInitializer = _newNode; } else if (parameterElement is DefaultFieldFormalParameterElementImpl) { From c36dac8fc9c518dc9334935ee04212342a989991 Mon Sep 17 00:00:00 2001 From: Konstantin Shcheglov Date: Tue, 14 Jan 2025 08:52:01 -0800 Subject: [PATCH 33/76] Elements. Migrate ReplaceTopBottomVisitor. Change-Id: I2784d949aad4c0cbd9c0e34ed570c1a97bfb6228 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/403949 Reviewed-by: Brian Wilkerson Commit-Queue: Konstantin Shcheglov --- .../element/replace_top_bottom_visitor.dart | 26 +++++++++---------- pkg/analyzer/lib/src/dart/element/type.dart | 14 ++++++++++ .../test/generated/elements_types_mixin.dart | 13 ++++++---- 3 files changed, 34 insertions(+), 19 deletions(-) diff --git a/pkg/analyzer/lib/src/dart/element/replace_top_bottom_visitor.dart b/pkg/analyzer/lib/src/dart/element/replace_top_bottom_visitor.dart index 97925cbcde1c..97381ed7c794 100644 --- a/pkg/analyzer/lib/src/dart/element/replace_top_bottom_visitor.dart +++ b/pkg/analyzer/lib/src/dart/element/replace_top_bottom_visitor.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// ignore_for_file: analyzer_use_new_elements - import 'package:_fe_analyzer_shared/src/type_inference/type_analyzer_operations.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/src/dart/element/element.dart'; @@ -42,7 +40,7 @@ class ReplaceTopBottomVisitor { var alias = type.alias; if (alias != null) { return _instantiatedTypeAlias(type, alias, variance); - } else if (type is InterfaceType) { + } else if (type is InterfaceTypeImpl) { return _interfaceType(type, variance); } else if (type is FunctionType) { return _functionType(type, variance); @@ -53,7 +51,7 @@ class ReplaceTopBottomVisitor { DartType _functionType(FunctionType type, Variance variance) { var newReturnType = process(type.returnType, variance); - var newParameters = type.parameters.map((parameter) { + var newParameters = type.formalParameters.map((parameter) { return parameter.copyWith( type: process( parameter.type, @@ -62,9 +60,9 @@ class ReplaceTopBottomVisitor { ); }).toList(); - return FunctionTypeImpl( - typeFormals: type.typeFormals, - parameters: newParameters, + return FunctionTypeImpl.v2( + typeParameters: type.typeParameters, + formalParameters: newParameters, returnType: newReturnType, nullabilitySuffix: type.nullabilitySuffix, ); @@ -75,15 +73,15 @@ class ReplaceTopBottomVisitor { InstantiatedTypeAliasElement alias, Variance variance, ) { - var aliasElement = alias.element; + var aliasElement = alias.element2; var aliasArguments = alias.typeArguments; - var typeParameters = aliasElement.typeParameters; + var typeParameters = aliasElement.typeParameters2; assert(typeParameters.length == aliasArguments.length); var newTypeArguments = []; for (var i = 0; i < typeParameters.length; i++) { - var typeParameter = typeParameters[i] as TypeParameterElementImpl; + var typeParameter = typeParameters[i] as TypeParameterElementImpl2; newTypeArguments.add( process( aliasArguments[i], @@ -98,8 +96,8 @@ class ReplaceTopBottomVisitor { ); } - DartType _interfaceType(InterfaceType type, Variance variance) { - var typeParameters = type.element.typeParameters; + InterfaceTypeImpl _interfaceType(InterfaceTypeImpl type, Variance variance) { + var typeParameters = type.element3.typeParameters2; if (typeParameters.isEmpty) { return type; } @@ -113,8 +111,8 @@ class ReplaceTopBottomVisitor { newTypeArguments.add(newTypeArgument); } - return InterfaceTypeImpl( - element: type.element, + return InterfaceTypeImpl.v2( + element: type.element3, nullabilitySuffix: type.nullabilitySuffix, typeArguments: newTypeArguments, ); diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart index 37ba01ef616a..ec9ecc9aee4c 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart @@ -611,6 +611,20 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { } } + factory InterfaceTypeImpl.v2({ + required InterfaceElementImpl2 element, + required List typeArguments, + required NullabilitySuffix nullabilitySuffix, + InstantiatedTypeAliasElement? alias, + }) { + return InterfaceTypeImpl( + element: element.asElement, + typeArguments: typeArguments, + nullabilitySuffix: nullabilitySuffix, + alias: alias, + ); + } + InterfaceTypeImpl._({ required this.element, required this.typeArguments, diff --git a/pkg/analyzer/test/generated/elements_types_mixin.dart b/pkg/analyzer/test/generated/elements_types_mixin.dart index 50eefb9473b1..f868f5b96909 100644 --- a/pkg/analyzer/test/generated/elements_types_mixin.dart +++ b/pkg/analyzer/test/generated/elements_types_mixin.dart @@ -580,11 +580,14 @@ mixin ElementsTypesMixin { required List typeParameters, required DartType aliasedType, }) { - var element = TypeAliasElementImpl(name, 0); - element.enclosingElement3 = testLibrary.definingCompilationUnit; - element.typeParameters = typeParameters; - element.aliasedType = aliasedType; - return element; + var fragment = TypeAliasElementImpl(name, 0); + fragment.enclosingElement3 = testLibrary.definingCompilationUnit; + fragment.typeParameters = typeParameters; + fragment.aliasedType = aliasedType; + + TypeAliasElementImpl2(Reference.root(), fragment); + + return fragment; } DartType typeAliasTypeNone( From 9b71817072489f0a7a39ae512f8f17e348b9175b Mon Sep 17 00:00:00 2001 From: Danny Tuppeny Date: Tue, 14 Jan 2025 08:56:41 -0800 Subject: [PATCH 34/76] [analysis_server] Fix duplicate reporting of some LSP type parsing errors Parse errors for spec types were being reported twice - once by the containing object (in canParse()), and once by the nested canParse() call for the nested type. This skips reporting the error for nested calls to a canParse() method, which will always report the error itself. Change-Id: I03e4a9638fd6a3fc77eac918f6fd16def93327d6 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404105 Reviewed-by: Samuel Rawlins Reviewed-by: Brian Wilkerson --- .../test/tool/lsp_spec/json_test.dart | 16 +- .../tool/lsp_spec/codegen_dart.dart | 11 +- .../lib/protocol_custom_generated.dart | 12 -- .../lib/protocol_generated.dart | 200 ------------------ 4 files changed, 24 insertions(+), 215 deletions(-) diff --git a/pkg/analysis_server/test/tool/lsp_spec/json_test.dart b/pkg/analysis_server/test/tool/lsp_spec/json_test.dart index 110d47eebd4c..f9f13647c4ce 100644 --- a/pkg/analysis_server/test/tool/lsp_spec/json_test.dart +++ b/pkg/analysis_server/test/tool/lsp_spec/json_test.dart @@ -288,7 +288,7 @@ void main() { expect(reporter.errors.first, equals('params.kind must not be null')); }); - test('canParse records fields of the wrong type', () { + test('canParse records fields of the wrong type (non-spec types)', () { var reporter = LspJsonReporter('params'); expect(RenameFileOptions.canParse({'overwrite': 1}, reporter), isFalse); expect(reporter.errors, hasLength(1)); @@ -298,6 +298,20 @@ void main() { ); }); + test('canParse records fields of the wrong type (spec types)', () { + var reporter = LspJsonReporter('params'); + expect( + ClientCapabilities.canParse({'textDocument': 1}, reporter), + isFalse, + ); + expect( + reporter.errors.single, + equals( + 'params.textDocument must be of type TextDocumentClientCapabilities', + ), + ); + }); + test('canParse records nested undefined fields', () { var reporter = LspJsonReporter('params'); expect( diff --git a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart index 1b45c0d502ee..befdd2ab1bff 100644 --- a/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart +++ b/pkg/analysis_server/tool/lsp_spec/codegen_dart.dart @@ -514,8 +514,15 @@ void _writeCanParseType( buffer ..write(') {') - ..indent() - ..writeIndentedln('reporter.reportError($quote$failureMessage$quote);') + ..indent(); + if (!_isSpecType(type)) { + // Only report an error for non-spec types, as spec types will have reported + // their own error in the nested canParse() call. + buffer.writeIndentedln( + 'reporter.reportError($quote$failureMessage$quote);', + ); + } + buffer ..writeIndentedln('return false;') ..outdent() ..writeIndentedln('}') diff --git a/third_party/pkg/language_server_protocol/lib/protocol_custom_generated.dart b/third_party/pkg/language_server_protocol/lib/protocol_custom_generated.dart index e21ef90168b4..b764958d1afe 100644 --- a/third_party/pkg/language_server_protocol/lib/protocol_custom_generated.dart +++ b/third_party/pkg/language_server_protocol/lib/protocol_custom_generated.dart @@ -52,7 +52,6 @@ bool _canParseArgumentEdit( } if ((!nullCheck || value != null) && !ArgumentEdit.canParse(value, reporter)) { - reporter.reportError('must be of type ArgumentEdit'); return false; } } finally { @@ -102,7 +101,6 @@ bool _canParseElement( return false; } if ((!nullCheck || value != null) && !Element.canParse(value, reporter)) { - reporter.reportError('must be of type Element'); return false; } } finally { @@ -128,7 +126,6 @@ bool _canParseErrorCodes( } if ((!nullCheck || value != null) && !ErrorCodes.canParse(value, reporter)) { - reporter.reportError('must be of type ErrorCodes'); return false; } } finally { @@ -154,7 +151,6 @@ bool _canParseFlutterOutline( } if ((!nullCheck || value != null) && !FlutterOutline.canParse(value, reporter)) { - reporter.reportError('must be of type FlutterOutline'); return false; } } finally { @@ -180,7 +176,6 @@ bool _canParseInsertTextFormat( } if ((!nullCheck || value != null) && !InsertTextFormat.canParse(value, reporter)) { - reporter.reportError('must be of type InsertTextFormat'); return false; } } finally { @@ -501,7 +496,6 @@ bool _canParseMethod( return false; } if ((!nullCheck || value != null) && !Method.canParse(value, reporter)) { - reporter.reportError('must be of type Method'); return false; } } finally { @@ -526,7 +520,6 @@ bool _canParseOutline( return false; } if ((!nullCheck || value != null) && !Outline.canParse(value, reporter)) { - reporter.reportError('must be of type Outline'); return false; } } finally { @@ -551,7 +544,6 @@ bool _canParsePosition( return false; } if ((!nullCheck || value != null) && !Position.canParse(value, reporter)) { - reporter.reportError('must be of type Position'); return false; } } finally { @@ -576,7 +568,6 @@ bool _canParseRange( return false; } if ((!nullCheck || value != null) && !Range.canParse(value, reporter)) { - reporter.reportError('must be of type Range'); return false; } } finally { @@ -602,7 +593,6 @@ bool _canParseResponseError( } if ((!nullCheck || value != null) && !ResponseError.canParse(value, reporter)) { - reporter.reportError('must be of type ResponseError'); return false; } } finally { @@ -653,7 +643,6 @@ bool _canParseTextDocumentIdentifier( } if ((!nullCheck || value != null) && !TextDocumentIdentifier.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentIdentifier'); return false; } } finally { @@ -679,7 +668,6 @@ bool _canParseTypeHierarchyAnchor( } if ((!nullCheck || value != null) && !TypeHierarchyAnchor.canParse(value, reporter)) { - reporter.reportError('must be of type TypeHierarchyAnchor'); return false; } } finally { diff --git a/third_party/pkg/language_server_protocol/lib/protocol_generated.dart b/third_party/pkg/language_server_protocol/lib/protocol_generated.dart index 1a831cec22e8..9be3454867d1 100644 --- a/third_party/pkg/language_server_protocol/lib/protocol_generated.dart +++ b/third_party/pkg/language_server_protocol/lib/protocol_generated.dart @@ -859,7 +859,6 @@ bool _canParseCallHierarchyClientCapabilities( } if ((!nullCheck || value != null) && !CallHierarchyClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type CallHierarchyClientCapabilities'); return false; } } finally { @@ -885,7 +884,6 @@ bool _canParseCallHierarchyItem( } if ((!nullCheck || value != null) && !CallHierarchyItem.canParse(value, reporter)) { - reporter.reportError('must be of type CallHierarchyItem'); return false; } } finally { @@ -911,7 +909,6 @@ bool _canParseClientCapabilities( } if ((!nullCheck || value != null) && !ClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ClientCapabilities'); return false; } } finally { @@ -937,7 +934,6 @@ bool _canParseClientCodeActionKindOptions( } if ((!nullCheck || value != null) && !ClientCodeActionKindOptions.canParse(value, reporter)) { - reporter.reportError('must be of type ClientCodeActionKindOptions'); return false; } } finally { @@ -963,7 +959,6 @@ bool _canParseClientCompletionItemOptionsKind( } if ((!nullCheck || value != null) && !ClientCompletionItemOptionsKind.canParse(value, reporter)) { - reporter.reportError('must be of type ClientCompletionItemOptionsKind'); return false; } } finally { @@ -989,7 +984,6 @@ bool _canParseClientInfo( } if ((!nullCheck || value != null) && !ClientInfo.canParse(value, reporter)) { - reporter.reportError('must be of type ClientInfo'); return false; } } finally { @@ -1015,8 +1009,6 @@ bool _canParseClientSemanticTokensRequestOptions( } if ((!nullCheck || value != null) && !ClientSemanticTokensRequestOptions.canParse(value, reporter)) { - reporter - .reportError('must be of type ClientSemanticTokensRequestOptions'); return false; } } finally { @@ -1042,7 +1034,6 @@ bool _canParseCodeActionClientCapabilities( } if ((!nullCheck || value != null) && !CodeActionClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type CodeActionClientCapabilities'); return false; } } finally { @@ -1069,8 +1060,6 @@ bool _canParseCodeActionClientCapabilitiesCodeActionLiteralSupport( if ((!nullCheck || value != null) && !CodeActionClientCapabilitiesCodeActionLiteralSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type CodeActionClientCapabilitiesCodeActionLiteralSupport'); return false; } } finally { @@ -1096,8 +1085,6 @@ bool _canParseCodeActionClientCapabilitiesResolveSupport( } if ((!nullCheck || value != null) && !CodeActionClientCapabilitiesResolveSupport.canParse(value, reporter)) { - reporter.reportError( - 'must be of type CodeActionClientCapabilitiesResolveSupport'); return false; } } finally { @@ -1123,7 +1110,6 @@ bool _canParseCodeActionContext( } if ((!nullCheck || value != null) && !CodeActionContext.canParse(value, reporter)) { - reporter.reportError('must be of type CodeActionContext'); return false; } } finally { @@ -1149,7 +1135,6 @@ bool _canParseCodeActionDisabled( } if ((!nullCheck || value != null) && !CodeActionDisabled.canParse(value, reporter)) { - reporter.reportError('must be of type CodeActionDisabled'); return false; } } finally { @@ -1175,7 +1160,6 @@ bool _canParseCodeActionKind( } if ((!nullCheck || value != null) && !CodeActionKind.canParse(value, reporter)) { - reporter.reportError('must be of type CodeActionKind'); return false; } } finally { @@ -1201,7 +1185,6 @@ bool _canParseCodeActionTriggerKind( } if ((!nullCheck || value != null) && !CodeActionTriggerKind.canParse(value, reporter)) { - reporter.reportError('must be of type CodeActionTriggerKind'); return false; } } finally { @@ -1227,7 +1210,6 @@ bool _canParseCodeDescription( } if ((!nullCheck || value != null) && !CodeDescription.canParse(value, reporter)) { - reporter.reportError('must be of type CodeDescription'); return false; } } finally { @@ -1253,7 +1235,6 @@ bool _canParseCodeLensClientCapabilities( } if ((!nullCheck || value != null) && !CodeLensClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type CodeLensClientCapabilities'); return false; } } finally { @@ -1279,7 +1260,6 @@ bool _canParseCodeLensOptions( } if ((!nullCheck || value != null) && !CodeLensOptions.canParse(value, reporter)) { - reporter.reportError('must be of type CodeLensOptions'); return false; } } finally { @@ -1305,8 +1285,6 @@ bool _canParseCodeLensWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !CodeLensWorkspaceClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type CodeLensWorkspaceClientCapabilities'); return false; } } finally { @@ -1331,7 +1309,6 @@ bool _canParseColor( return false; } if ((!nullCheck || value != null) && !Color.canParse(value, reporter)) { - reporter.reportError('must be of type Color'); return false; } } finally { @@ -1356,7 +1333,6 @@ bool _canParseCommand( return false; } if ((!nullCheck || value != null) && !Command.canParse(value, reporter)) { - reporter.reportError('must be of type Command'); return false; } } finally { @@ -1382,7 +1358,6 @@ bool _canParseCompletionClientCapabilities( } if ((!nullCheck || value != null) && !CompletionClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionClientCapabilities'); return false; } } finally { @@ -1408,8 +1383,6 @@ bool _canParseCompletionClientCapabilitiesCompletionItem( } if ((!nullCheck || value != null) && !CompletionClientCapabilitiesCompletionItem.canParse(value, reporter)) { - reporter.reportError( - 'must be of type CompletionClientCapabilitiesCompletionItem'); return false; } } finally { @@ -1435,8 +1408,6 @@ bool _canParseCompletionClientCapabilitiesCompletionList( } if ((!nullCheck || value != null) && !CompletionClientCapabilitiesCompletionList.canParse(value, reporter)) { - reporter.reportError( - 'must be of type CompletionClientCapabilitiesCompletionList'); return false; } } finally { @@ -1462,7 +1433,6 @@ bool _canParseCompletionContext( } if ((!nullCheck || value != null) && !CompletionContext.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionContext'); return false; } } finally { @@ -1488,7 +1458,6 @@ bool _canParseCompletionItemDefaults( } if ((!nullCheck || value != null) && !CompletionItemDefaults.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemDefaults'); return false; } } finally { @@ -1514,8 +1483,6 @@ bool _canParseCompletionItemInsertTextModeSupport( } if ((!nullCheck || value != null) && !CompletionItemInsertTextModeSupport.canParse(value, reporter)) { - reporter - .reportError('must be of type CompletionItemInsertTextModeSupport'); return false; } } finally { @@ -1541,7 +1508,6 @@ bool _canParseCompletionItemKind( } if ((!nullCheck || value != null) && !CompletionItemKind.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemKind'); return false; } } finally { @@ -1567,7 +1533,6 @@ bool _canParseCompletionItemLabelDetails( } if ((!nullCheck || value != null) && !CompletionItemLabelDetails.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemLabelDetails'); return false; } } finally { @@ -1593,7 +1558,6 @@ bool _canParseCompletionItemResolutionInfo( } if ((!nullCheck || value != null) && !CompletionItemResolutionInfo.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemResolutionInfo'); return false; } } finally { @@ -1619,7 +1583,6 @@ bool _canParseCompletionItemResolveSupport( } if ((!nullCheck || value != null) && !CompletionItemResolveSupport.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemResolveSupport'); return false; } } finally { @@ -1645,7 +1608,6 @@ bool _canParseCompletionItemTagSupport( } if ((!nullCheck || value != null) && !CompletionItemTagSupport.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionItemTagSupport'); return false; } } finally { @@ -1671,7 +1633,6 @@ bool _canParseCompletionOptions( } if ((!nullCheck || value != null) && !CompletionOptions.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionOptions'); return false; } } finally { @@ -1697,7 +1658,6 @@ bool _canParseCompletionTriggerKind( } if ((!nullCheck || value != null) && !CompletionTriggerKind.canParse(value, reporter)) { - reporter.reportError('must be of type CompletionTriggerKind'); return false; } } finally { @@ -1723,7 +1683,6 @@ bool _canParseCreateFileOptions( } if ((!nullCheck || value != null) && !CreateFileOptions.canParse(value, reporter)) { - reporter.reportError('must be of type CreateFileOptions'); return false; } } finally { @@ -1749,7 +1708,6 @@ bool _canParseDeclarationClientCapabilities( } if ((!nullCheck || value != null) && !DeclarationClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DeclarationClientCapabilities'); return false; } } finally { @@ -1775,7 +1733,6 @@ bool _canParseDefinitionClientCapabilities( } if ((!nullCheck || value != null) && !DefinitionClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DefinitionClientCapabilities'); return false; } } finally { @@ -1801,7 +1758,6 @@ bool _canParseDeleteFileOptions( } if ((!nullCheck || value != null) && !DeleteFileOptions.canParse(value, reporter)) { - reporter.reportError('must be of type DeleteFileOptions'); return false; } } finally { @@ -1827,7 +1783,6 @@ bool _canParseDiagnosticClientCapabilities( } if ((!nullCheck || value != null) && !DiagnosticClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DiagnosticClientCapabilities'); return false; } } finally { @@ -1881,7 +1836,6 @@ bool _canParseDiagnosticSeverity( } if ((!nullCheck || value != null) && !DiagnosticSeverity.canParse(value, reporter)) { - reporter.reportError('must be of type DiagnosticSeverity'); return false; } } finally { @@ -1907,8 +1861,6 @@ bool _canParseDiagnosticWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !DiagnosticWorkspaceClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type DiagnosticWorkspaceClientCapabilities'); return false; } } finally { @@ -1934,8 +1886,6 @@ bool _canParseDidChangeConfigurationClientCapabilities( } if ((!nullCheck || value != null) && !DidChangeConfigurationClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DidChangeConfigurationClientCapabilities'); return false; } } finally { @@ -1961,8 +1911,6 @@ bool _canParseDidChangeWatchedFilesClientCapabilities( } if ((!nullCheck || value != null) && !DidChangeWatchedFilesClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DidChangeWatchedFilesClientCapabilities'); return false; } } finally { @@ -1988,7 +1936,6 @@ bool _canParseDocumentColorClientCapabilities( } if ((!nullCheck || value != null) && !DocumentColorClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentColorClientCapabilities'); return false; } } finally { @@ -2014,8 +1961,6 @@ bool _canParseDocumentFormattingClientCapabilities( } if ((!nullCheck || value != null) && !DocumentFormattingClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type DocumentFormattingClientCapabilities'); return false; } } finally { @@ -2041,8 +1986,6 @@ bool _canParseDocumentHighlightClientCapabilities( } if ((!nullCheck || value != null) && !DocumentHighlightClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type DocumentHighlightClientCapabilities'); return false; } } finally { @@ -2068,7 +2011,6 @@ bool _canParseDocumentHighlightKind( } if ((!nullCheck || value != null) && !DocumentHighlightKind.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentHighlightKind'); return false; } } finally { @@ -2094,7 +2036,6 @@ bool _canParseDocumentLinkClientCapabilities( } if ((!nullCheck || value != null) && !DocumentLinkClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentLinkClientCapabilities'); return false; } } finally { @@ -2120,7 +2061,6 @@ bool _canParseDocumentLinkOptions( } if ((!nullCheck || value != null) && !DocumentLinkOptions.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentLinkOptions'); return false; } } finally { @@ -2146,8 +2086,6 @@ bool _canParseDocumentOnTypeFormattingClientCapabilities( } if ((!nullCheck || value != null) && !DocumentOnTypeFormattingClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DocumentOnTypeFormattingClientCapabilities'); return false; } } finally { @@ -2173,7 +2111,6 @@ bool _canParseDocumentOnTypeFormattingOptions( } if ((!nullCheck || value != null) && !DocumentOnTypeFormattingOptions.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentOnTypeFormattingOptions'); return false; } } finally { @@ -2199,8 +2136,6 @@ bool _canParseDocumentRangeFormattingClientCapabilities( } if ((!nullCheck || value != null) && !DocumentRangeFormattingClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DocumentRangeFormattingClientCapabilities'); return false; } } finally { @@ -2226,7 +2161,6 @@ bool _canParseDocumentSymbolClientCapabilities( } if ((!nullCheck || value != null) && !DocumentSymbolClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type DocumentSymbolClientCapabilities'); return false; } } finally { @@ -2252,8 +2186,6 @@ bool _canParseDocumentSymbolClientCapabilitiesSymbolKind( } if ((!nullCheck || value != null) && !DocumentSymbolClientCapabilitiesSymbolKind.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DocumentSymbolClientCapabilitiesSymbolKind'); return false; } } finally { @@ -2279,8 +2211,6 @@ bool _canParseDocumentSymbolClientCapabilitiesTagSupport( } if ((!nullCheck || value != null) && !DocumentSymbolClientCapabilitiesTagSupport.canParse(value, reporter)) { - reporter.reportError( - 'must be of type DocumentSymbolClientCapabilitiesTagSupport'); return false; } } finally { @@ -2334,7 +2264,6 @@ bool _canParseExecuteCommandClientCapabilities( } if ((!nullCheck || value != null) && !ExecuteCommandClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ExecuteCommandClientCapabilities'); return false; } } finally { @@ -2360,7 +2289,6 @@ bool _canParseExecuteCommandOptions( } if ((!nullCheck || value != null) && !ExecuteCommandOptions.canParse(value, reporter)) { - reporter.reportError('must be of type ExecuteCommandOptions'); return false; } } finally { @@ -2386,7 +2314,6 @@ bool _canParseExecutionSummary( } if ((!nullCheck || value != null) && !ExecutionSummary.canParse(value, reporter)) { - reporter.reportError('must be of type ExecutionSummary'); return false; } } finally { @@ -2412,7 +2339,6 @@ bool _canParseFailureHandlingKind( } if ((!nullCheck || value != null) && !FailureHandlingKind.canParse(value, reporter)) { - reporter.reportError('must be of type FailureHandlingKind'); return false; } } finally { @@ -2438,7 +2364,6 @@ bool _canParseFileChangeType( } if ((!nullCheck || value != null) && !FileChangeType.canParse(value, reporter)) { - reporter.reportError('must be of type FileChangeType'); return false; } } finally { @@ -2464,7 +2389,6 @@ bool _canParseFileOperationClientCapabilities( } if ((!nullCheck || value != null) && !FileOperationClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationClientCapabilities'); return false; } } finally { @@ -2490,7 +2414,6 @@ bool _canParseFileOperationOptions( } if ((!nullCheck || value != null) && !FileOperationOptions.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationOptions'); return false; } } finally { @@ -2516,7 +2439,6 @@ bool _canParseFileOperationPattern( } if ((!nullCheck || value != null) && !FileOperationPattern.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationPattern'); return false; } } finally { @@ -2542,7 +2464,6 @@ bool _canParseFileOperationPatternKind( } if ((!nullCheck || value != null) && !FileOperationPatternKind.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationPatternKind'); return false; } } finally { @@ -2568,7 +2489,6 @@ bool _canParseFileOperationPatternOptions( } if ((!nullCheck || value != null) && !FileOperationPatternOptions.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationPatternOptions'); return false; } } finally { @@ -2594,7 +2514,6 @@ bool _canParseFileOperationRegistrationOptions( } if ((!nullCheck || value != null) && !FileOperationRegistrationOptions.canParse(value, reporter)) { - reporter.reportError('must be of type FileOperationRegistrationOptions'); return false; } } finally { @@ -2620,7 +2539,6 @@ bool _canParseFoldingRangeClientCapabilities( } if ((!nullCheck || value != null) && !FoldingRangeClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type FoldingRangeClientCapabilities'); return false; } } finally { @@ -2646,8 +2564,6 @@ bool _canParseFoldingRangeClientCapabilitiesFoldingRange( } if ((!nullCheck || value != null) && !FoldingRangeClientCapabilitiesFoldingRange.canParse(value, reporter)) { - reporter.reportError( - 'must be of type FoldingRangeClientCapabilitiesFoldingRange'); return false; } } finally { @@ -2674,8 +2590,6 @@ bool _canParseFoldingRangeClientCapabilitiesFoldingRangeKind( if ((!nullCheck || value != null) && !FoldingRangeClientCapabilitiesFoldingRangeKind.canParse( value, reporter)) { - reporter.reportError( - 'must be of type FoldingRangeClientCapabilitiesFoldingRangeKind'); return false; } } finally { @@ -2701,7 +2615,6 @@ bool _canParseFoldingRangeKind( } if ((!nullCheck || value != null) && !FoldingRangeKind.canParse(value, reporter)) { - reporter.reportError('must be of type FoldingRangeKind'); return false; } } finally { @@ -2727,7 +2640,6 @@ bool _canParseFormattingOptions( } if ((!nullCheck || value != null) && !FormattingOptions.canParse(value, reporter)) { - reporter.reportError('must be of type FormattingOptions'); return false; } } finally { @@ -2753,7 +2665,6 @@ bool _canParseGeneralClientCapabilities( } if ((!nullCheck || value != null) && !GeneralClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type GeneralClientCapabilities'); return false; } } finally { @@ -2780,8 +2691,6 @@ bool _canParseGeneralClientCapabilitiesStaleRequestSupport( if ((!nullCheck || value != null) && !GeneralClientCapabilitiesStaleRequestSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type GeneralClientCapabilitiesStaleRequestSupport'); return false; } } finally { @@ -2807,7 +2716,6 @@ bool _canParseHoverClientCapabilities( } if ((!nullCheck || value != null) && !HoverClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type HoverClientCapabilities'); return false; } } finally { @@ -2833,7 +2741,6 @@ bool _canParseImplementationClientCapabilities( } if ((!nullCheck || value != null) && !ImplementationClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ImplementationClientCapabilities'); return false; } } finally { @@ -2859,7 +2766,6 @@ bool _canParseInlayHintClientCapabilities( } if ((!nullCheck || value != null) && !InlayHintClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type InlayHintClientCapabilities'); return false; } } finally { @@ -2885,8 +2791,6 @@ bool _canParseInlayHintClientCapabilitiesResolveSupport( } if ((!nullCheck || value != null) && !InlayHintClientCapabilitiesResolveSupport.canParse(value, reporter)) { - reporter.reportError( - 'must be of type InlayHintClientCapabilitiesResolveSupport'); return false; } } finally { @@ -2912,7 +2816,6 @@ bool _canParseInlayHintKind( } if ((!nullCheck || value != null) && !InlayHintKind.canParse(value, reporter)) { - reporter.reportError('must be of type InlayHintKind'); return false; } } finally { @@ -2938,8 +2841,6 @@ bool _canParseInlayHintWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !InlayHintWorkspaceClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type InlayHintWorkspaceClientCapabilities'); return false; } } finally { @@ -2965,7 +2866,6 @@ bool _canParseInlineValueClientCapabilities( } if ((!nullCheck || value != null) && !InlineValueClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type InlineValueClientCapabilities'); return false; } } finally { @@ -2991,7 +2891,6 @@ bool _canParseInlineValueContext( } if ((!nullCheck || value != null) && !InlineValueContext.canParse(value, reporter)) { - reporter.reportError('must be of type InlineValueContext'); return false; } } finally { @@ -3017,8 +2916,6 @@ bool _canParseInlineValueWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !InlineValueWorkspaceClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type InlineValueWorkspaceClientCapabilities'); return false; } } finally { @@ -3072,7 +2969,6 @@ bool _canParseInsertTextFormat( } if ((!nullCheck || value != null) && !InsertTextFormat.canParse(value, reporter)) { - reporter.reportError('must be of type InsertTextFormat'); return false; } } finally { @@ -3098,7 +2994,6 @@ bool _canParseInsertTextMode( } if ((!nullCheck || value != null) && !InsertTextMode.canParse(value, reporter)) { - reporter.reportError('must be of type InsertTextMode'); return false; } } finally { @@ -3174,8 +3069,6 @@ bool _canParseLinkedEditingRangeClientCapabilities( } if ((!nullCheck || value != null) && !LinkedEditingRangeClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type LinkedEditingRangeClientCapabilities'); return false; } } finally { @@ -4622,7 +4515,6 @@ bool _canParseLocation( return false; } if ((!nullCheck || value != null) && !Location.canParse(value, reporter)) { - reporter.reportError('must be of type Location'); return false; } } finally { @@ -4773,7 +4665,6 @@ bool _canParseMarkdownClientCapabilities( } if ((!nullCheck || value != null) && !MarkdownClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type MarkdownClientCapabilities'); return false; } } finally { @@ -4825,7 +4716,6 @@ bool _canParseMarkupKind( } if ((!nullCheck || value != null) && !MarkupKind.canParse(value, reporter)) { - reporter.reportError('must be of type MarkupKind'); return false; } } finally { @@ -4851,7 +4741,6 @@ bool _canParseMessageType( } if ((!nullCheck || value != null) && !MessageType.canParse(value, reporter)) { - reporter.reportError('must be of type MessageType'); return false; } } finally { @@ -4877,7 +4766,6 @@ bool _canParseMonikerClientCapabilities( } if ((!nullCheck || value != null) && !MonikerClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type MonikerClientCapabilities'); return false; } } finally { @@ -4903,7 +4791,6 @@ bool _canParseMonikerKind( } if ((!nullCheck || value != null) && !MonikerKind.canParse(value, reporter)) { - reporter.reportError('must be of type MonikerKind'); return false; } } finally { @@ -4929,7 +4816,6 @@ bool _canParseNotebookCellArrayChange( } if ((!nullCheck || value != null) && !NotebookCellArrayChange.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookCellArrayChange'); return false; } } finally { @@ -4955,7 +4841,6 @@ bool _canParseNotebookCellKind( } if ((!nullCheck || value != null) && !NotebookCellKind.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookCellKind'); return false; } } finally { @@ -4981,7 +4866,6 @@ bool _canParseNotebookDocument( } if ((!nullCheck || value != null) && !NotebookDocument.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookDocument'); return false; } } finally { @@ -5007,7 +4891,6 @@ bool _canParseNotebookDocumentChangeEvent( } if ((!nullCheck || value != null) && !NotebookDocumentChangeEvent.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookDocumentChangeEvent'); return false; } } finally { @@ -5033,7 +4916,6 @@ bool _canParseNotebookDocumentChangeEventCells( } if ((!nullCheck || value != null) && !NotebookDocumentChangeEventCells.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookDocumentChangeEventCells'); return false; } } finally { @@ -5059,8 +4941,6 @@ bool _canParseNotebookDocumentChangeEventCellsStructure( } if ((!nullCheck || value != null) && !NotebookDocumentChangeEventCellsStructure.canParse(value, reporter)) { - reporter.reportError( - 'must be of type NotebookDocumentChangeEventCellsStructure'); return false; } } finally { @@ -5086,8 +4966,6 @@ bool _canParseNotebookDocumentClientCapabilities( } if ((!nullCheck || value != null) && !NotebookDocumentClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type NotebookDocumentClientCapabilities'); return false; } } finally { @@ -5144,7 +5022,6 @@ bool _canParseNotebookDocumentIdentifier( } if ((!nullCheck || value != null) && !NotebookDocumentIdentifier.canParse(value, reporter)) { - reporter.reportError('must be of type NotebookDocumentIdentifier'); return false; } } finally { @@ -5170,8 +5047,6 @@ bool _canParseNotebookDocumentSyncClientCapabilities( } if ((!nullCheck || value != null) && !NotebookDocumentSyncClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type NotebookDocumentSyncClientCapabilities'); return false; } } finally { @@ -5277,8 +5152,6 @@ bool _canParseOptionalVersionedTextDocumentIdentifier( } if ((!nullCheck || value != null) && !OptionalVersionedTextDocumentIdentifier.canParse(value, reporter)) { - reporter.reportError( - 'must be of type OptionalVersionedTextDocumentIdentifier'); return false; } } finally { @@ -5303,7 +5176,6 @@ bool _canParsePosition( return false; } if ((!nullCheck || value != null) && !Position.canParse(value, reporter)) { - reporter.reportError('must be of type Position'); return false; } } finally { @@ -5329,7 +5201,6 @@ bool _canParsePositionEncodingKind( } if ((!nullCheck || value != null) && !PositionEncodingKind.canParse(value, reporter)) { - reporter.reportError('must be of type PositionEncodingKind'); return false; } } finally { @@ -5355,7 +5226,6 @@ bool _canParsePrepareSupportDefaultBehavior( } if ((!nullCheck || value != null) && !PrepareSupportDefaultBehavior.canParse(value, reporter)) { - reporter.reportError('must be of type PrepareSupportDefaultBehavior'); return false; } } finally { @@ -5381,8 +5251,6 @@ bool _canParsePublishDiagnosticsClientCapabilities( } if ((!nullCheck || value != null) && !PublishDiagnosticsClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type PublishDiagnosticsClientCapabilities'); return false; } } finally { @@ -5409,8 +5277,6 @@ bool _canParsePublishDiagnosticsClientCapabilitiesTagSupport( if ((!nullCheck || value != null) && !PublishDiagnosticsClientCapabilitiesTagSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type PublishDiagnosticsClientCapabilitiesTagSupport'); return false; } } finally { @@ -5435,7 +5301,6 @@ bool _canParseRange( return false; } if ((!nullCheck || value != null) && !Range.canParse(value, reporter)) { - reporter.reportError('must be of type Range'); return false; } } finally { @@ -5461,7 +5326,6 @@ bool _canParseReferenceClientCapabilities( } if ((!nullCheck || value != null) && !ReferenceClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ReferenceClientCapabilities'); return false; } } finally { @@ -5487,7 +5351,6 @@ bool _canParseReferenceContext( } if ((!nullCheck || value != null) && !ReferenceContext.canParse(value, reporter)) { - reporter.reportError('must be of type ReferenceContext'); return false; } } finally { @@ -5513,8 +5376,6 @@ bool _canParseRegularExpressionsClientCapabilities( } if ((!nullCheck || value != null) && !RegularExpressionsClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type RegularExpressionsClientCapabilities'); return false; } } finally { @@ -5540,7 +5401,6 @@ bool _canParseRenameClientCapabilities( } if ((!nullCheck || value != null) && !RenameClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type RenameClientCapabilities'); return false; } } finally { @@ -5566,7 +5426,6 @@ bool _canParseRenameFileOptions( } if ((!nullCheck || value != null) && !RenameFileOptions.canParse(value, reporter)) { - reporter.reportError('must be of type RenameFileOptions'); return false; } } finally { @@ -5592,7 +5451,6 @@ bool _canParseSelectionRange( } if ((!nullCheck || value != null) && !SelectionRange.canParse(value, reporter)) { - reporter.reportError('must be of type SelectionRange'); return false; } } finally { @@ -5618,7 +5476,6 @@ bool _canParseSelectionRangeClientCapabilities( } if ((!nullCheck || value != null) && !SelectionRangeClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type SelectionRangeClientCapabilities'); return false; } } finally { @@ -5644,7 +5501,6 @@ bool _canParseSemanticTokensClientCapabilities( } if ((!nullCheck || value != null) && !SemanticTokensClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type SemanticTokensClientCapabilities'); return false; } } finally { @@ -5670,7 +5526,6 @@ bool _canParseSemanticTokensLegend( } if ((!nullCheck || value != null) && !SemanticTokensLegend.canParse(value, reporter)) { - reporter.reportError('must be of type SemanticTokensLegend'); return false; } } finally { @@ -5724,8 +5579,6 @@ bool _canParseSemanticTokensWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !SemanticTokensWorkspaceClientCapabilities.canParse(value, reporter)) { - reporter.reportError( - 'must be of type SemanticTokensWorkspaceClientCapabilities'); return false; } } finally { @@ -5751,7 +5604,6 @@ bool _canParseServerCapabilities( } if ((!nullCheck || value != null) && !ServerCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ServerCapabilities'); return false; } } finally { @@ -5777,7 +5629,6 @@ bool _canParseServerCompletionItemOptions( } if ((!nullCheck || value != null) && !ServerCompletionItemOptions.canParse(value, reporter)) { - reporter.reportError('must be of type ServerCompletionItemOptions'); return false; } } finally { @@ -5803,7 +5654,6 @@ bool _canParseServerInfo( } if ((!nullCheck || value != null) && !ServerInfo.canParse(value, reporter)) { - reporter.reportError('must be of type ServerInfo'); return false; } } finally { @@ -5829,7 +5679,6 @@ bool _canParseShowDocumentClientCapabilities( } if ((!nullCheck || value != null) && !ShowDocumentClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type ShowDocumentClientCapabilities'); return false; } } finally { @@ -5855,8 +5704,6 @@ bool _canParseShowMessageRequestClientCapabilities( } if ((!nullCheck || value != null) && !ShowMessageRequestClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type ShowMessageRequestClientCapabilities'); return false; } } finally { @@ -5883,8 +5730,6 @@ bool _canParseShowMessageRequestClientCapabilitiesMessageActionItem( if ((!nullCheck || value != null) && !ShowMessageRequestClientCapabilitiesMessageActionItem.canParse( value, reporter)) { - reporter.reportError( - 'must be of type ShowMessageRequestClientCapabilitiesMessageActionItem'); return false; } } finally { @@ -5910,7 +5755,6 @@ bool _canParseSignatureHelp( } if ((!nullCheck || value != null) && !SignatureHelp.canParse(value, reporter)) { - reporter.reportError('must be of type SignatureHelp'); return false; } } finally { @@ -5936,7 +5780,6 @@ bool _canParseSignatureHelpClientCapabilities( } if ((!nullCheck || value != null) && !SignatureHelpClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type SignatureHelpClientCapabilities'); return false; } } finally { @@ -5963,8 +5806,6 @@ bool _canParseSignatureHelpClientCapabilitiesSignatureInformation( if ((!nullCheck || value != null) && !SignatureHelpClientCapabilitiesSignatureInformation.canParse( value, reporter)) { - reporter.reportError( - 'must be of type SignatureHelpClientCapabilitiesSignatureInformation'); return false; } } finally { @@ -5990,7 +5831,6 @@ bool _canParseSignatureHelpContext( } if ((!nullCheck || value != null) && !SignatureHelpContext.canParse(value, reporter)) { - reporter.reportError('must be of type SignatureHelpContext'); return false; } } finally { @@ -6016,7 +5856,6 @@ bool _canParseSignatureHelpOptions( } if ((!nullCheck || value != null) && !SignatureHelpOptions.canParse(value, reporter)) { - reporter.reportError('must be of type SignatureHelpOptions'); return false; } } finally { @@ -6042,7 +5881,6 @@ bool _canParseSignatureHelpTriggerKind( } if ((!nullCheck || value != null) && !SignatureHelpTriggerKind.canParse(value, reporter)) { - reporter.reportError('must be of type SignatureHelpTriggerKind'); return false; } } finally { @@ -6068,8 +5906,6 @@ bool _canParseSignatureInformationParameterInformation( } if ((!nullCheck || value != null) && !SignatureInformationParameterInformation.canParse(value, reporter)) { - reporter.reportError( - 'must be of type SignatureInformationParameterInformation'); return false; } } finally { @@ -6147,7 +5983,6 @@ bool _canParseSymbolKind( } if ((!nullCheck || value != null) && !SymbolKind.canParse(value, reporter)) { - reporter.reportError('must be of type SymbolKind'); return false; } } finally { @@ -6173,7 +6008,6 @@ bool _canParseTextDocumentClientCapabilities( } if ((!nullCheck || value != null) && !TextDocumentClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentClientCapabilities'); return false; } } finally { @@ -6199,7 +6033,6 @@ bool _canParseTextDocumentIdentifier( } if ((!nullCheck || value != null) && !TextDocumentIdentifier.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentIdentifier'); return false; } } finally { @@ -6225,7 +6058,6 @@ bool _canParseTextDocumentItem( } if ((!nullCheck || value != null) && !TextDocumentItem.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentItem'); return false; } } finally { @@ -6251,7 +6083,6 @@ bool _canParseTextDocumentSaveReason( } if ((!nullCheck || value != null) && !TextDocumentSaveReason.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentSaveReason'); return false; } } finally { @@ -6277,8 +6108,6 @@ bool _canParseTextDocumentSyncClientCapabilities( } if ((!nullCheck || value != null) && !TextDocumentSyncClientCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type TextDocumentSyncClientCapabilities'); return false; } } finally { @@ -6304,7 +6133,6 @@ bool _canParseTextDocumentSyncKind( } if ((!nullCheck || value != null) && !TextDocumentSyncKind.canParse(value, reporter)) { - reporter.reportError('must be of type TextDocumentSyncKind'); return false; } } finally { @@ -6357,7 +6185,6 @@ bool _canParseTextEdit( return false; } if ((!nullCheck || value != null) && !TextEdit.canParse(value, reporter)) { - reporter.reportError('must be of type TextEdit'); return false; } } finally { @@ -6383,7 +6210,6 @@ bool _canParseTraceValue( } if ((!nullCheck || value != null) && !TraceValue.canParse(value, reporter)) { - reporter.reportError('must be of type TraceValue'); return false; } } finally { @@ -6409,7 +6235,6 @@ bool _canParseTypeDefinitionClientCapabilities( } if ((!nullCheck || value != null) && !TypeDefinitionClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type TypeDefinitionClientCapabilities'); return false; } } finally { @@ -6435,7 +6260,6 @@ bool _canParseTypeHierarchyClientCapabilities( } if ((!nullCheck || value != null) && !TypeHierarchyClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type TypeHierarchyClientCapabilities'); return false; } } finally { @@ -6461,7 +6285,6 @@ bool _canParseTypeHierarchyItem( } if ((!nullCheck || value != null) && !TypeHierarchyItem.canParse(value, reporter)) { - reporter.reportError('must be of type TypeHierarchyItem'); return false; } } finally { @@ -6487,7 +6310,6 @@ bool _canParseTypeHierarchyItemInfo( } if ((!nullCheck || value != null) && !TypeHierarchyItemInfo.canParse(value, reporter)) { - reporter.reportError('must be of type TypeHierarchyItemInfo'); return false; } } finally { @@ -6513,7 +6335,6 @@ bool _canParseUniquenessLevel( } if ((!nullCheck || value != null) && !UniquenessLevel.canParse(value, reporter)) { - reporter.reportError('must be of type UniquenessLevel'); return false; } } finally { @@ -6592,8 +6413,6 @@ bool _canParseVersionedNotebookDocumentIdentifier( } if ((!nullCheck || value != null) && !VersionedNotebookDocumentIdentifier.canParse(value, reporter)) { - reporter - .reportError('must be of type VersionedNotebookDocumentIdentifier'); return false; } } finally { @@ -6619,7 +6438,6 @@ bool _canParseVersionedTextDocumentIdentifier( } if ((!nullCheck || value != null) && !VersionedTextDocumentIdentifier.canParse(value, reporter)) { - reporter.reportError('must be of type VersionedTextDocumentIdentifier'); return false; } } finally { @@ -6644,7 +6462,6 @@ bool _canParseWatchKind( return false; } if ((!nullCheck || value != null) && !WatchKind.canParse(value, reporter)) { - reporter.reportError('must be of type WatchKind'); return false; } } finally { @@ -6670,7 +6487,6 @@ bool _canParseWindowClientCapabilities( } if ((!nullCheck || value != null) && !WindowClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type WindowClientCapabilities'); return false; } } finally { @@ -6696,7 +6512,6 @@ bool _canParseWorkspaceClientCapabilities( } if ((!nullCheck || value != null) && !WorkspaceClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceClientCapabilities'); return false; } } finally { @@ -6722,7 +6537,6 @@ bool _canParseWorkspaceEdit( } if ((!nullCheck || value != null) && !WorkspaceEdit.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceEdit'); return false; } } finally { @@ -6748,7 +6562,6 @@ bool _canParseWorkspaceEditClientCapabilities( } if ((!nullCheck || value != null) && !WorkspaceEditClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceEditClientCapabilities'); return false; } } finally { @@ -6775,8 +6588,6 @@ bool _canParseWorkspaceEditClientCapabilitiesChangeAnnotationSupport( if ((!nullCheck || value != null) && !WorkspaceEditClientCapabilitiesChangeAnnotationSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type WorkspaceEditClientCapabilitiesChangeAnnotationSupport'); return false; } } finally { @@ -6802,7 +6613,6 @@ bool _canParseWorkspaceFoldersChangeEvent( } if ((!nullCheck || value != null) && !WorkspaceFoldersChangeEvent.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceFoldersChangeEvent'); return false; } } finally { @@ -6828,8 +6638,6 @@ bool _canParseWorkspaceFoldersServerCapabilities( } if ((!nullCheck || value != null) && !WorkspaceFoldersServerCapabilities.canParse(value, reporter)) { - reporter - .reportError('must be of type WorkspaceFoldersServerCapabilities'); return false; } } finally { @@ -6855,7 +6663,6 @@ bool _canParseWorkspaceOptions( } if ((!nullCheck || value != null) && !WorkspaceOptions.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceOptions'); return false; } } finally { @@ -6881,7 +6688,6 @@ bool _canParseWorkspaceSymbolClientCapabilities( } if ((!nullCheck || value != null) && !WorkspaceSymbolClientCapabilities.canParse(value, reporter)) { - reporter.reportError('must be of type WorkspaceSymbolClientCapabilities'); return false; } } finally { @@ -6908,8 +6714,6 @@ bool _canParseWorkspaceSymbolClientCapabilitiesResolveSupport( if ((!nullCheck || value != null) && !WorkspaceSymbolClientCapabilitiesResolveSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type WorkspaceSymbolClientCapabilitiesResolveSupport'); return false; } } finally { @@ -6936,8 +6740,6 @@ bool _canParseWorkspaceSymbolClientCapabilitiesSymbolKind( if ((!nullCheck || value != null) && !WorkspaceSymbolClientCapabilitiesSymbolKind.canParse( value, reporter)) { - reporter.reportError( - 'must be of type WorkspaceSymbolClientCapabilitiesSymbolKind'); return false; } } finally { @@ -6964,8 +6766,6 @@ bool _canParseWorkspaceSymbolClientCapabilitiesTagSupport( if ((!nullCheck || value != null) && !WorkspaceSymbolClientCapabilitiesTagSupport.canParse( value, reporter)) { - reporter.reportError( - 'must be of type WorkspaceSymbolClientCapabilitiesTagSupport'); return false; } } finally { From a0b6a489f33ece6777af112563d4161f268c9a28 Mon Sep 17 00:00:00 2001 From: Danny Tuppeny Date: Tue, 14 Jan 2025 08:56:41 -0800 Subject: [PATCH 35/76] [analysis_server] Allow legacy clients to set LSP capabilities in setClientCapabilities This adds a new field to the existing (legacy) setClientCapabilities parameters that accepts an LSP ClientCapabilities. This will allow a legacy client to indicate that it supports things like the `workspace/applyEdit` reverse-request. Change-Id: Ia3b75c701f1699c92f902e058daec4844ce664fa Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/404106 Reviewed-by: Brian Wilkerson Reviewed-by: Phil Quitslund Commit-Queue: Phil Quitslund --- pkg/analysis_server/doc/api.html | 18 ++++++- .../lib/protocol/protocol_constants.dart | 4 +- .../lib/protocol/protocol_generated.dart | 32 +++++++++-- .../server_set_client_capabilities.dart | 3 ++ .../lib/src/legacy_analysis_server.dart | 25 ++++++++- .../test/domain_server_test.dart | 54 +++++++++++++++++++ .../support/integration_test_methods.dart | 19 +++++++ .../support/protocol_matchers.dart | 3 +- .../spec/generated/java/AnalysisServer.java | 12 ++++- pkg/analysis_server/tool/spec/spec_input.html | 21 +++++++- .../lib/src/protocol/protocol_constants.dart | 4 +- .../lib/src/protocol/protocol_generated.dart | 28 ++++++++-- 12 files changed, 209 insertions(+), 14 deletions(-) diff --git a/pkg/analysis_server/doc/api.html b/pkg/analysis_server/doc/api.html index 563e10953851..e7247a6e73f7 100644 --- a/pkg/analysis_server/doc/api.html +++ b/pkg/analysis_server/doc/api.html @@ -110,7 +110,7 @@

Analysis Server API Specification

Version - 1.38.0 + 1.39.0

This document contains a specification of the API provided by the @@ -245,6 +245,10 @@

Enumerations

ignoring the item or treating it with some default/fallback handling.

Changelog

+

1.39.0

+
    +
  • Added a new lspCapabilities field to the setClientCapabilities parameters to allow clients to provide their LSP capabilities. These capabilities can indicate that a client can support lsp.handle requests in the server-to-client direction.
  • +

1.38.0