mirror of
https://github.com/imjasonh/nescript
synced 2026-07-08 08:55:38 +00:00
Language: struct literals
struct Vec2 { x: u8, y: u8 }
var pos: Vec2 = Vec2 { x: 100, y: 50 }
on frame {
pos = Vec2 { x: pos.x + 1, y: pos.y }
}
- AST: new \`Expr::StructLiteral(name, fields, span)\` variant
- Parser: in expression position, \`Ident {\` enters struct-literal
mode when the new \`restrict_struct_literals\` flag is off.
\`if\`/\`while\`/\`for\` conditions set the flag so the \`{\` keeps
going to the following block. Condition contexts can still use
struct literals by parenthesizing them.
- Analyzer: validates that the struct type exists, each named field
belongs to it, and each field value has a compatible type.
- IR lowering: desugars \`var = StructLiteral { ... }\` (both in
assignments and variable initializers) into per-field StoreVar
operations against the analyzer-synthesized \`var.field\`
variables. No IR type for struct values is needed.
- AST codegen: no-op (legacy path).
- examples/structs_enums_for.ne now uses a struct literal for the
initial \`player\` state instead of per-field assignments.
https://claude.ai/code/session_01W6eQFStA66EuMKHUFo2rx3
This commit is contained in:
parent
f17f1e7267
commit
c8ae433a7c
9 changed files with 221 additions and 13 deletions
|
|
@ -187,6 +187,31 @@ Fields are laid out contiguously in declaration order. A variable of
|
|||
struct type allocates enough contiguous bytes to hold all its fields;
|
||||
each field is accessible via the dot operator.
|
||||
|
||||
Struct literals initialize or assign all fields at once:
|
||||
|
||||
```
|
||||
struct Vec2 { x: u8, y: u8 }
|
||||
|
||||
// as an initializer
|
||||
var pos: Vec2 = Vec2 { x: 100, y: 50 }
|
||||
|
||||
// as an assignment
|
||||
on frame {
|
||||
pos = Vec2 { x: 0, y: 0 }
|
||||
if button.right {
|
||||
pos = Vec2 { x: pos.x + 1, y: pos.y }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Inside `if`, `while`, and `for` conditions the struct literal syntax
|
||||
is reserved for the following block, so wrap the literal in parens if
|
||||
you ever need one in a condition:
|
||||
|
||||
```
|
||||
if pos == (Vec2 { x: 0, y: 0 }) { /* ... */ }
|
||||
```
|
||||
|
||||
In v0.1 only primitive field types (`u8`, `i8`, `bool`) are supported —
|
||||
nested structs, `u16`, and array fields are not yet allowed.
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue