Skip to content
This repository was archived by the owner on Nov 20, 2024. It is now read-only.

Commit bd705ff

Browse files
authored
Fix prefer_final_fields with generic super-classes (#1298)
Fix prefer_final_fields with generic super-classes
1 parent 906d1bd commit bd705ff

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

lib/src/util/dart_type_utilities.dart

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'dart:collection';
77
import 'package:analyzer/dart/ast/ast.dart';
88
import 'package:analyzer/dart/element/element.dart';
99
import 'package:analyzer/dart/element/type.dart';
10+
import 'package:analyzer/src/dart/element/member.dart';
1011

1112
typedef bool AstNodePredicate(AstNode node);
1213

@@ -16,8 +17,25 @@ class DartTypeUtilities {
1617
(type is InterfaceType &&
1718
extendsClass(type.superclass, className, library));
1819

19-
static Element getCanonicalElement(Element element) =>
20-
element is PropertyAccessorElement ? element.variable : element;
20+
static Element getCanonicalElement(Element element) {
21+
if (element is PropertyAccessorElement) {
22+
final variable = element.variable;
23+
if (variable is FieldMember) {
24+
// A field element defined in a parameterized type where the values of
25+
// the type parameters are known.
26+
//
27+
// This concept should be invisible when comparing FieldElements, but a
28+
// bug in the analyzer causes FieldElements to not evaluate as
29+
// equivalent to equivalent FieldMembers. See
30+
// https://github.com/dart-lang/sdk/issues/35343.
31+
return variable.baseElement;
32+
} else {
33+
return variable;
34+
}
35+
} else {
36+
return element;
37+
}
38+
}
2139

2240
static Element getCanonicalElementFromIdentifier(AstNode rawNode) {
2341
if (rawNode is Expression) {

test/rules/prefer_final_fields.dart

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class E {
7373
}
7474
}
7575

76-
class F{
76+
class F {
7777
var _array = new List<int>(5); // LINT
7878

7979
void foo() {
@@ -85,9 +85,20 @@ class F{
8585
class IdBug686 {
8686
static int _id = 0;
8787
static String generateId({prefix: String}) {
88-
return (prefix ?? "id") + "-" +
89-
(_id++).toString() + "-" + _foo();
88+
return (prefix ?? "id") + "-" + (_id++).toString() + "-" + _foo();
9089
}
9190

9291
static String _foo() => '';
9392
}
93+
94+
// analyzer's `FieldMember` vs `FieldElement` caused
95+
// https://github.com/dart-lang/sdk/issues/34417
96+
abstract class GenericBase<T> {
97+
int _current = 0; // OK
98+
}
99+
100+
class GenericSub extends GenericBase<int> {
101+
void test() {
102+
_current = 1;
103+
}
104+
}

0 commit comments

Comments
 (0)