Skip to content

match self.field: on a non-Copy enum field moves the field out and blanks it (patterns are projection, not owned demand) #1302

Closed

Description

@ehartford

Found rewriting `examples/json-parser` under #1150 ruling 4: its parser's `let is_lbrace = match self.current: Some(.LBrace) => true; _ => false` checks silently destroyed the lookahead token.

D22: "Patterns are structural projection, not owned demand." A `match` on a place with non-binding patterns must observe it. Instead the scrutinee is moved out of the field and the field is blanked:

```
error E = Bad
enum Tok { LBrace | S(str) }
type P { n: i32 = 0, cur: Option[Tok] = Some(.LBrace) }
extend P:
mut fn bump():
self.n += 1
self.cur = Some(.S(f"s{self.n}"))
mut fn outer():
self.bump()
let b = match self.cur:
Some(.LBrace) => true
_ => false
print(f"{b}") // false (correct: S was seen)
// self.cur now reads Some(.LBrace) again — the reset sentinel
```

MIR (`with check q5.w --dump-mir`, `P.outer`):

```
bb4: {
_6 = move _1.cur; // scrutinee moved out of the field
_8 = discriminant(_6);
...
bb5: {
_5 = copy _7;
_1.cur = const zst(ty137); // reset-on-move blanks self.cur
_1.cur = const zst(ty137);
...
bb10: { // the _ arm
_10 = move _6;
drop(_10) @ drop#13 scope-exit _10; // the token is dropped
```

Two consequences: (1) the field's value is gone after any `match` on it; (2) the all-zero reset sentinel of `Option[Tok]` decodes as `Some(.LBrace)` (variant 0 of variant 0), so the corruption reads as a plausible stale token rather than `None` — a blanked `Option` place should read as `None`.

`match &self.cur:`, `let cur = &self.cur; match cur:` and a free `fn is_lbrace(t: &Option[Tok])` observe correctly. `if let Some(.LBrace) = self.cur:` and a `fn` method whose body is `match self.cur:` corrupt the same way (read receiver!). Installed `with v0.15.2.1-g478b26481`.

The example's parser now consumes the token explicitly (`let tok = move self.current`) and peeks through `&self.current`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions