dart-lang / dart-lang/language

[patterns] Make `fromEnvironment` in map pattern keys an error?

Open
#2,936 13 comments 0 reactions 0 assignees View on GitHub
patterns question
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

Evaluation of constants of the form `T.fromEnvironment(...)` where `T` is `int`, `bool` or `String` is subject to various complications during compilation. For instance, such constant values are considered unresolved and do not have a known value during many compilation/analysis phases, and some tasks are done in backends when the value is actually known.

This creates some difficulties (for example, but surely not just) when there is a need to determine whether or not a particular map pattern uses the same key as some other map pattern.

```dart
void main() {
switch ({1 : true}) {
case {const int.fromEnvironment("one"): true} || {1: false}: print('Match!');
}
}
```

In this program, it is not known at a convenient point in time whether the value from the environment is identical to the literal `1` in the other map pattern, and this means that it is difficult to create code that makes the right decision about reusing the same key during the matching of the second map pattern.

Currently, the backends collaborate in doing things like this, such that it is possible to report a compile-time error for the following:

```dart
const s = {int.fromEnvironment("one"), 1}; // Compile/link-time error, if the value from the environment is 1.
void main() {}
```

I tend to think that the ability to use values from the environment as keys in map patterns is marginal. Hence, we could consider simply making it an error for any constant expression which is unresolved for this reason to be used as a key in a map pattern (note that this affects explicit invocations of `T.fromEnvironment(...)` as well as other constant expressions with a dependency on such invocations). We can always lift this restriction later on without breaking anything.

@dart-lang/language-team, WDYT?

@chloestefantsova, do you agree that this could be helpful?

Contributor guide

Open the contributing guide

Research direction

No file, test, or entry point is named. Start by reading the examples and the full comment thread, then determine whether unresolved fromEnvironment constants should be rejected as map-pattern keys. Done requires a settled language decision and a clearly identified specification or implementation path.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
18/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.