Skip to content

Should constant expressions be potentially constant? #4311

@eernstg

Description

@eernstg

The language specification implies in commentary that every constant expression is also a potentially constant expression:

The constant expressions is a subset of the potentially constant expressions

However, this is not expressed in the case of conditional expressions (e1 ? e2 : e3):

\item An expression of the form \code{$e_1$\,?\,$e_2$\,:\,$e_3$}
  is potentially constant if $e_1$, $e_2$, and $e_3$
  are all potentially constant expressions.
  It is constant if $e_1$ is a constant expression and either
  \begin{enumerate}
  \item $e_1$ evaluates to \TRUE{} and $e_2$ is a constant expression, or
  \item $e_1$ evaluates to \FALSE{} and $e_3$ is a constant expression.
  \end{enumerate}

For example, true ? 1 : v is a constant expression which is not potentially constant in the following example:

void main() {
  var v = 0;
  const c = true ? 1 : v; // OK.
}

We could add the word 'further' to make it 'It is further constant', like many other cases in the same itemized list, which would cause true ? 1 : v to be non-constant because it isn't potentially constant (because v isn't a constant variable, and it isn't a formal parameter of a constant constructor).

Alternatively, we could decide that it is not a problem that some constant expressions aren't potentially constant, and we could then adjust the commentary in the language specification.

I'd recommend the former. @dart-lang/language-team, WDYT?

Note that this would be a mildly breaking change. For instance, the CFE follows the specification and does not report the error on line 48 and 52 of LanguageFeatures/Static-access-shorthand/constant_expression_A10_t17.dart, but the analyzer does report these errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugThere is a mistake in the language specification or in an active document

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions