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
2.05k stars 66 forks source link

<comptime> record parameters can't be provided; fields can't be used in runtime code #238

Closed jrfondren closed 12 months ago

jrfondren commented 12 months ago

Code example

local box = @record{n: number}
local function unbox(b: box <comptime>) end

-- unbox({n=3}) -- error: in call of function 'sleepunits': expected a compile time argument at index 1

local b: box <comptime> = {n=3} -- ok
-- unbox(b) -- error: in call of function 'sleepunits': expected a compile time argument at index 1
-- local n = b.n -- cemitter.lua:446: `CEmitter:add_literal` for valtype `box` is not implemented

Expected behavior

As <comptime> enums work well, I expected records to work similarly. For example, this is fine (and is an adaptation of a Lisp macro example from Let Over Lambda):

local Duration = @enum{ s = 1, m, h, d, ms, us }

local function sleepunits(value: number, unit: Duration <comptime>)
  ## local units = { 1, 60, 3600, 86400, 1/1000, 1/1000000 }
  print('faking sleep for: ', value * #[units[unit.value]]#)
end

sleepunits(3, Duration.h)
sleepunits(3, Duration.m)

Workaround

In these examples, everything works as intended without <comptime>.

Environment

x86_64 linux Nelua 0.2.0-dev Build number: 1588 Git date: 2023-09-16 16:20:44 -0300 Git hash: 596fcca5c77932da8a07c249de59a9dff3099495 Semantic version: 0.2.0-dev.1588+596fcca5 Copyright (C) 2019-2022 Eduardo Bart (https://nelua.io/)

edubart commented 12 months ago

The <comptime> was not designed to be used with custom records, it was designed to work with just simple primitives like string, boolean, numbers and enums so the compiler can do simple in-place replacement of values.

But this deserves a better error message, I added one in https://github.com/edubart/nelua-lang/commit/3343daa7da088bba4e151f96849f80ebe4351cc8

Thanks for reporting.