dart-lang / dart-lang/language

Add an expression-local declaration (let-expression).

Open
#1,052 3 comments 6 reactions 0 assignees View on GitHub
feature
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

There is no way to locally declare a variable in an expression.
In statements, a single statement can be replaced by a block statement that contains local variable declarations, but there is no way to do the same thing in an expression.

Example code (using "let/in" as syntax):

```
let var tmp = new Something() in new Other(tmp, tmp)
```

This can be useful in initializer lists where you can need to create a new object and use it in more than one place.

The current alternative, as used by the specification to explain desugaring of some constructs, uses a function literal to bind the new variable, like `((tmp) => new Other (tmp, tmp))(new Something())`.
This has the disadvantage of not working well with async operations (if `new Other(..)` was more complex and contained an await, it would not be a correct rewrite).

The new syntax could be used by the specification to define desugarings, and can be used to make some expressions more readable by reducing the scope of temporary variables.

Alternatively, now that we have definite assignment analysis, we could allow `var x = e` as an expression.
It would effectively introduce `x` into the current scope, but the variable cannot be accessed until after the declaration point, even if that is in the middle of an expression. It'll b definitely unassigned before and definitely assigned after, which is something we can already handle.

Then the above example becomes `Other(var tmp = Something(), tmp)`.
It will probably have to use the `var` or `final` marker, using a type can potentially be hard to parse: `f(x + int y = 2, 2)`.
The precedence of a declaration would be very low, so the only place it won't need to be parenthesized is if it's at the end of an expression, or it's a collection element or parameter list entry (comma delimited).

Contributor guide

Open the contributing guide

Research direction

Start with issue #1052 and the Dart language specification's existing desugaring examples. Compare the proposed let/in expression with the alternative declaration expression, including precedence, scope, definite assignment, and async behavior. Done requires a selected design and corresponding specification updates; the issue does not name implementation files or tests.

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
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.