terralang / terra

Terra is a low-level system programming language that is embedded in and meta-programmed by the Lua programming language.
terralang.org
Other
2.71k stars 197 forks source link

Can't define function over std.Vector(StructType) without building the type first #645

Open jrfondren opened 10 months ago

jrfondren commented 10 months ago

In this code:

local std = require "std"

struct S {
  k: int
}

std.Vector(S) -- compile fails without this line

terra main()
  var a = [std.Vector(S)].salloc():init()
  a:insert().k = 1
  a:insert().k = 2
  a:insert().k = 3
  for i = 0ULL, a:size() do
    std.printf("x[%llu].k: %d\n", i, a(i).k)
  end
  std.printf("#%llu\n", f(a))
end

terra f(v: &std.Vector(S)): uint64
  return v:size()
end

main()

Without the commented line, compilation fails:

/terra/src/terralib.lua:1105: attempting to use type S before it is defined.

stack traceback:
        [C]: in function 'error'
        /terra/src/terralib.lua:381: in function 'erroratlocation'
        /terra/src/terralib.lua:1524: in function 'getvalue'
        /terra/src/terralib.lua:1373: in function 'getentries'
        /terra/src/terralib.lua:1563: in function 'getvalue'
        /terra/src/terralib.lua:1373: in function 'getlayout'
        /terra/src/terralib.lua:1642: in function 'userfn'
        [string "/std.t"]:119: Errors reported during finalizing type
        /terra/src/terralib.lua:2986: in function 'docheck'
        /terra/src/terralib.lua:3120: in function 'checkexp'
        ...
        [string "/std.t"]:110: in function 'fn'
        /terra/src/terralib.lua:1250: in function 'Vector'
        t5.t:20: in function 'userfn'
        t5.t:20: Errors reported during evaluating Lua code from Terra
terra f(v: &std.Vector(S)): uint64
           ^
        /terra/src/terralib.lua:1843: in function 'evalluaexpression'
        /terra/src/terralib.lua:1850: in function 'evaltype'
        /terra/src/terralib.lua:1870: in function 'evaluateparameterlist'
        /terra/src/terralib.lua:1068: in function 'evalformalparameters'
        /terra/src/terralib.lua:1143: in function 'defineobjects'
        t5.t:3: in main chunk
elliottslaughter commented 10 months ago

I agree that it doesn't seem like this ought to fail. The struct S is clearly defined, and if you go take a look at the std.t source you'll see the Vector type is too.

Unfortunately I don't have time to dig in further right now, but it probably has something to do with Terra's ordering of compilation. If you want to help out, I'd trace through the compiler to see what difference that line makes; presumably there is some path (e.g., completing a type T when used as &T) that's missing that ought to be there.