[analyzer] Issue 53927: Disallow final fields to be used in a const context.

Context: Added a field check in https://dart-review.googlesource.com/c/sdk/+/312347 which the goal back then was to cut down on more unnecessary errors, but this seemed to have caused a regression elsewhere.

Reverting this part of the change and other related tests.

Bug: https://github.com/dart-lang/sdk/issues/53927
Change-Id: I0774e050c73e677347caad836dd59c9cba71d044
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/333240
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
Commit-Queue: Kallen Tu <kallentu@google.com>
This commit is contained in:
Kallen Tu 2023-11-02 20:46:20 +00:00 committed by Commit Queue
parent c2ef69dff5
commit 988c301109
4 changed files with 27 additions and 3 deletions

View file

@ -1684,9 +1684,7 @@ class ConstantVisitor extends UnifyingAstVisitor<Constant> {
// already computed values of all dependencies first (or detect a cycle),
// so the value has already been computed and we can just return it.
var evaluationResult = variableElement.evaluationResult;
var isConstField = variableElement is FieldElement &&
(variableElement.isConst || variableElement.isFinal);
if (isConstField || variableElement.isConst) {
if (variableElement.isConst) {
switch (evaluationResult) {
case null:
// The constant value isn't computed yet, or there is an error while

View file

@ -2017,6 +2017,28 @@ List
''');
}
test_visitListLiteral_listElement_field_final() async {
await assertErrorsInCode(r'''
class A {
final String bar = '';
const A();
List<String> foo() => const [bar];
}
''', [
error(CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT, 79, 3),
]);
}
test_visitListLiteral_listElement_field_static() async {
await assertNoErrorsInCode(r'''
class A {
static const String bar = '';
const A();
List<String> foo() => const [bar];
}
''');
}
test_visitListLiteral_listElement_simple() async {
await assertNoErrorsInCode(r'''
const x = ['a', 'b', 'c'];

View file

@ -7,6 +7,8 @@
class C {
const C();
//^^^^^
// [analyzer] COMPILE_TIME_ERROR.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST
final x = 1;
final y = x;

View file

@ -9,6 +9,8 @@
class C {
const C();
//^^^^^
// [analyzer] COMPILE_TIME_ERROR.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST
final x = 1;
final y = x;