edubart / nelua-lang

Minimal, efficient, statically-typed and meta-programmable systems programming language heavily inspired by Lua, which compiles to C and native code.
https://nelua.io
MIT License
2k stars 62 forks source link

Proposal: Shorthand syntax for records (a.k.a Field Punning) #16

Closed resolritter closed 3 years ago

resolritter commented 4 years ago

Problem

Given a struct Point

local Point = @record {x: integer, y: integer, z: integer}

It is currently possible to initialize it in order

local x = 1
local y = 2
local z = 3

local p = Point {x, y, z}

but having it rely on order can lead to bugs

-- this is a bug: `x` and `y` are flipped in order
-- however, since they have the same type, the type checker can't catch it
local p = Point {y, x, z}

the following pattern is very common in Lua

local p = Point{
  x = x,
  y = y,
  z = z
}

However, it is repetitive, error-prone and verbose.

Proposal

Have a shorter initialization syntax. For example:

local p = Point { z, y, x }

That would look exactly like the array initialization syntax, though, so it could be changed to something else

local p = Point { =z, =y, =x }

Either syntax would be expanded to the same:

local p = Point { z = z, y = y, x = x }

Ordering doesn't matter on either case. Each variable gets assigned to the correct struct field with the same name.

Inspiration

edubart commented 3 years ago

This proposal has been implemented in master! After some thoughts I decided to support this as it is just a minor syntax sugar.