Skip to content

Analyzer/DDC: Allows downcasts of const?  #33304

Closed
@matanlurey

Description

@matanlurey

Related to #33303, I wouldn't have ever hit this error case if the IDE/analyzer would have stopped me (really, an internal customer I'm proxying for) write this code and check it in.

import 'package:test/test.dart';

class Provider {
  const Provider();
}

class Module {
  final List<Provider> providers;
  const Module(this.providers);
}

const aGoodModule = const Module(const [
  const Provider(),
]);

const listOfThings = const [
  const [],
  const Provider(),
];

const aBadModule = const Module(listOfThings);

void main() {
  test('$aBadModule should be invalid', () {
    expect(aBadModule.providers, const isInstanceOf<List<Provider>>());
  });
}

... produces no errors, warnings, hints, or lints, even in strong mode. This is invalid, though:

const aBadModule = const Module(/*List<Object>*/listOfThings);

... because Module statically requires List<Provider>. I sort of understand why, at runtime, this is allowed (because of downcasts - and @leafpetersen has seen my many many bugs on this), but I'm not sure why it is allowed statically in a const context (the CFE/VM seems to reject it).

Additionally, DDC builds the code ... it only later fails at runtime:

Type 'List<Object>' should be 'List<Provider>' to implement expected type 'List<Provider>'.
  dart:sdk_internal                     check_C
  dart2_const_downcast_test.dart 21:32  get aBadModule
  dart:sdk_internal                     get
  dart2_const_downcast_test.dart 24:10  main

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work onanalyzer-constantscustomer-google3legacy-area-analyzerUse area-devexp instead.type-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions