/
terralib.lua
4754 lines (4372 loc) · 182 KB
/
terralib.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- See Copyright Notice in ../LICENSE.txt
local ffi = require("ffi")
-- LINE COVERAGE INFORMATION, must run test script with luajit and not terra to avoid overwriting coverage with old version
if false then
local converageloader = loadfile("coverageinfo.lua")
local linetable = converageloader and converageloader() or {}
local function dumplineinfo()
local F = io.open("coverageinfo.lua","w")
F:write("return {\n")
for k,v in pairs(linetable) do
F:write("["..k.."] = "..v..";\n")
end
F:write("}\n")
F:close()
end
local function debughook(event)
local info = debug.getinfo(2,"Sl")
if info.short_src == "src/terralib.lua" then
linetable[info.currentline] = linetable[info.currentline] or 0
linetable[info.currentline] = linetable[info.currentline] + 1
end
end
debug.sethook(debughook,"l")
-- make a fake ffi object that causes dumplineinfo to be called when
-- the lua state is removed
ffi.cdef [[
typedef struct {} __linecoverage;
]]
ffi.metatype("__linecoverage", { __gc = dumplineinfo } )
_G[{}] = ffi.new("__linecoverage")
end
terra.isverbose = 0 --set by C api
local function dbprint(level,...)
if terra.isverbose >= level then
print(...)
end
end
local function dbprintraw(level,obj)
if terra.isverbose >= level then
obj:printraw()
end
end
--debug wrapper around cdef function to print out all the things being defined
local oldcdef = ffi.cdef
ffi.cdef = function(...)
dbprint(2,...)
return oldcdef(...)
end
-- TREE
terra.tree = {} --metatype for trees
terra.tree.__index = terra.tree
function terra.tree:is(value)
return self.kind == terra.kinds[value]
end
function terra.tree:printraw()
local function header(key,t)
if type(t) == "table" and (getmetatable(t) == nil or type(getmetatable(t).__index) ~= "function") then
local kt = t["kind"]
return (type(kt) == "number" and terra.kinds[kt]) or (type(kt) == "string" and kt) or ""
elseif (key == "type" or key == "operator") and type(t) == "number" then
return terra.kinds[t] .. " (enum " .. tostring(t) .. ")"
else
return tostring(t)
end
end
local function isList(t)
return type(t) == "table" and #t ~= 0
end
local parents = {}
local depth = 0
local function printElem(t,spacing)
if(type(t) == "table") then
if parents[t] then
print(string.rep(" ",#spacing).."<cyclic reference>")
return
elseif depth > 0 and (terra.isfunction(t) or terra.isfunctiondefinition(t)) then
return --don't print the entire nested function...
end
parents[t] = true
depth = depth + 1
for k,v in pairs(t) do
if type(k) == "table" and not terra.issymbol(k) then
print("this table:")
terra.tree.printraw(k)
error("table is key?")
end
if k ~= "kind" and k ~= "offset" --[[and k ~= "linenumber"]] then
local prefix = spacing..tostring(k)..": "
if terra.types.istype(v) then --dont print the raw form of types unless printraw was called directly on the type
print(prefix..tostring(v))
else
print(prefix..header(k,v))
if isList(v) then
printElem(v,string.rep(" ",2+#spacing))
else
printElem(v,string.rep(" ",2+#prefix))
end
end
end
end
depth = depth - 1
parents[t] = nil
end
end
print(header(nil,self))
if type(self) == "table" then
printElem(self," ")
end
end
function terra.tree:copy(new_tree)
if not new_tree then
print(debug.traceback())
error("empty tree?")
end
for k,v in pairs(self) do
if not new_tree[k] then
new_tree[k] = v
end
end
return setmetatable(new_tree,getmetatable(self))
end
function terra.newtree(ref,body)
if not ref or not terra.istree(ref) then
terra.tree.printraw(ref)
print(debug.traceback())
error("not a tree?",2)
end
body.offset = ref.offset
body.linenumber = ref.linenumber
body.filename = ref.filename
return setmetatable(body,terra.tree)
end
function terra.newanchor(depth)
local info = debug.getinfo(1 + depth,"Sl")
local body = { linenumber = info and info.currentline or 0, filename = info and info.short_src or "unknown" }
return setmetatable(body,terra.tree)
end
function terra.istree(v)
return terra.tree == getmetatable(v)
end
-- END TREE
-- LIST
terra.list = {} --used for all ast lists
setmetatable(terra.list,{ __index = table })
terra.list.__index = terra.list
function terra.newlist(lst)
if lst == nil then
lst = {}
end
return setmetatable(lst,terra.list)
end
function terra.list:map(fn,...)
local l = terra.newlist()
if type(fn) == "function" then
for i,v in ipairs(self) do
l[i] = fn(v,...)
end
else
for i,v in ipairs(self) do
local sel = v[fn]
if type(sel) == "function" then
l[i] = sel(v,...)
else
l[i] = sel
end
end
end
return l
end
function terra.list:insertall(elems)
for i,e in ipairs(elems) do
self:insert(e)
end
end
function terra.list:printraw()
for i,v in ipairs(self) do
if v.printraw then
print(i,v:printraw())
else
print(i,v)
end
end
end
function terra.list:mkstring(begin,sep,finish)
if sep == nil then
begin,sep,finish = "",begin,""
end
return begin..table.concat(self:map(tostring),sep)..finish
end
function terra.islist(exp)
return getmetatable(exp) == terra.list
end
-- END LIST
-- CONTEXT
terra.context = {}
terra.context.__index = terra.context
function terra.context:isempty()
return #self.stack == 0
end
function terra.context:begin(obj) --obj is currently only a funcdefinition
obj.compileindex = self.nextindex
obj.lowlink = obj.compileindex
self.nextindex = self.nextindex + 1
self.diagnostics:begin()
table.insert(self.stack,obj)
table.insert(self.tobecompiled,obj)
end
function terra.context:min(n)
local curobj = self.stack[#self.stack]
curobj.lowlink = math.min(curobj.lowlink,n)
end
local typeerrordebugcallback
function terra.settypeerrordebugcallback(fn)
assert(type(fn) == "function")
typeerrordebugcallback = fn
end
function terra.context:finish(anchor)
local obj = table.remove(self.stack)
if obj.lowlink == obj.compileindex then
local scc = terra.newlist()
local functions = terra.newlist()
repeat
local tocompile = table.remove(self.tobecompiled)
scc:insert(tocompile)
assert(tocompile.state == "typechecking")
functions:insert(tocompile)
until tocompile == obj
if self.diagnostics:haserrors() then
for i,o in ipairs(scc) do
o.state = "error"
end
if typeerrordebugcallback then
for i,o in ipairs(scc) do
typeerrordebugcallback(o)
end
end
else
for i,o in ipairs(scc) do
o.state,o.scc = "typechecked",obj.compileindex
end
--dispatch callbacks that should occur once the function is typechecked
for i,o in ipairs(scc) do
if o.oncompletion then
for i,fn in ipairs(o.oncompletion) do
terra.invokeuserfunction(anchor,false,fn,o)
end
o.oncompletion = nil
end
end
end
end
self.diagnostics:finish()
end
function terra.context:oncompletion(obj,callback)
obj.oncompletion = obj.oncompletion or terra.newlist()
obj.oncompletion:insert(callback)
end
function terra.getcompilecontext()
if not terra.globalcompilecontext then
terra.globalcompilecontext = setmetatable({diagnostics = terra.newdiagnostics() , stack = {}, tobecompiled = {}, nextindex = 0},terra.context)
end
return terra.globalcompilecontext
end
-- END CONTEXT
-- ENVIRONMENT
terra.environment = {}
terra.environment.__index = terra.environment
function terra.environment:enterblock()
local e = {}
self._localenv = setmetatable(e,{ __index = self._localenv })
end
function terra.environment:leaveblock()
self._localenv = getmetatable(self._localenv).__index
end
function terra.environment:localenv()
return self._localenv
end
function terra.environment:luaenv()
return self._luaenv
end
function terra.environment:combinedenv()
return self._combinedenv
end
function terra.newenvironment(_luaenv)
local self = setmetatable({},terra.environment)
self._luaenv = _luaenv
self._combinedenv = setmetatable({}, {
__index = function(_,idx)
return self._localenv[idx] or self._luaenv[idx]
end;
__newindex = function()
error("cannot define global variables or assign to upvalues in an escape")
end;
})
self:enterblock()
return self
end
-- END ENVIRONMENT
-- DIAGNOSTICS
terra.diagnostics = {}
terra.diagnostics.__index = terra.diagnostics
function terra.diagnostics:errorlist()
return self._errors[#self._errors]
end
function terra.diagnostics:printsource(anchor)
if not anchor.offset then
return
end
local filename = anchor.filename
local filetext = self.filecache[filename]
if not filetext then
local file = io.open(filename,"r")
if file then
filetext = file:read("*all")
self.filecache[filename] = filetext
file:close()
end
end
if filetext then --if the code did not come from a file then we don't print the carrot, since we cannot (easily) find the text
local begin,finish = anchor.offset + 1,anchor.offset + 1
local TAB,NL = ("\t"):byte(),("\n"):byte()
while begin > 1 and filetext:byte(begin) ~= NL do
begin = begin - 1
end
if begin > 1 then
begin = begin + 1
end
while finish < filetext:len() and filetext:byte(finish + 1) ~= NL do
finish = finish + 1
end
local errlist = self:errorlist()
local line = filetext:sub(begin,finish)
errlist:insert(line)
errlist:insert("\n")
for i = begin,anchor.offset do
errlist:insert((filetext:byte(i) == TAB and "\t") or " ")
end
errlist:insert("^\n")
end
end
function terra.diagnostics:clearfilecache()
self.filecache = {}
end
terra.diagnostics.source = {}
function terra.diagnostics:reporterror(anchor,...)
if not anchor or not anchor.filename or not anchor.linenumber then
print(debug.traceback())
print(terralib.tree.printraw(anchor))
error("nil anchor")
end
local errlist = self:errorlist()
errlist:insert(anchor.filename..":"..anchor.linenumber..": ")
local printedsource = false
local function printsource()
errlist:insert("\n")
self:printsource(anchor)
printedsource = true
end
for _,v in ipairs({...}) do
if v == self.source then
printsource()
else
errlist:insert(tostring(v))
end
end
if not printedsource then
printsource()
end
end
function terra.diagnostics:haserrors()
return #self._errors[#self._errors] > 0
end
function terra.diagnostics:begin()
table.insert(self._errors,terra.newlist())
end
function terra.diagnostics:finish()
local olderrors = table.remove(self._errors)
local haderrors = #olderrors > 0
if haderrors then
self._errors[#self._errors]:insert(olderrors)
end
return haderrors
end
function terra.diagnostics:finishandabortiferrors(msg,depth)
local errors = table.remove(self._errors)
if #errors > 0 then
local flatlist = {msg,"\n"}
local function insert(l)
if type(l) == "table" then
for i,e in ipairs(l) do
insert(e)
end
else
table.insert(flatlist,l)
end
end
insert(errors)
self:clearfilecache()
error(table.concat(flatlist),depth+1)
end
end
function terra.newdiagnostics()
return setmetatable({ filecache = {}, _errors = { terra.newlist() } },terra.diagnostics)
end
-- END DIAGNOSTICS
-- FUNCVARIANT
-- a function definition is an implementation of a function for a particular set of arguments
-- functions themselves are overloadable. Each potential implementation is its own function definition
-- with its own compile state, type, AST, etc.
terra.funcdefinition = {} --metatable for all function types
terra.funcdefinition.__index = terra.funcdefinition
function terra.funcdefinition:peektype() --look at the type but don't compile the function (if possible)
--this will return success, <type if success == true>
if self.type then
return true,self.type
end
if not self.untypedtree.returntype then
return false, terra.types.error
end
local params = self.untypedtree.parameters:map(function(entry) return entry.type end)
local ret = self.untypedtree.returntype
self.type = terra.types.functype(params,ret) --for future calls
return true, self.type
end
function terra.funcdefinition:gettype(cont,anchorduringcompilation)
local ctx = terra.getcompilecontext()
local apicall = not anchorduringcompilation -- this was called by the user, not the compiler
local anchor = anchorduringcompilation or assert(self.untypedtree)
local diag = ctx.diagnostics
if apicall then diag:begin() end
if "untyped" == self.state then
ctx:begin(self)
self:typecheckbody()
ctx:finish(self.untypedtree or anchor)
if not apicall then ctx:min(self.lowlink) end
elseif "typechecking" == self.state then
if not apicall then
ctx:min(self.compileindex)
local success, typ = self:peektype()
if not success then
diag:reporterror(anchor,"recursively called function needs an explicit return type.")
diag:reporterror(self.untypedtree,"definition of recursively called function is here.")
end
elseif not cont then
diag:reporterror(anchor,"attempting to compile a function that is already being compiled.")
end
if type(cont) == "function" then
terra.getcompilecontext():oncompletion(self,cont) --register callback to fire when typechecking is done
cont = nil
end
elseif "error" == self.state then
if not diag:haserrors() then
diag:reporterror(anchor,"referencing a function which failed to compile.")
if not apicall then
diag:reporterror(self.untypedtree,"definition of function which failed to compile.")
end
end
end
if apicall then diag:finishandabortiferrors("Errors reported during compilation.",2) end
if type(cont) == "function" then
cont(self)
end
return self.type or terra.types.error
end
local weakkeys = { __mode = "k" }
local function newweakkeytable()
return setmetatable({},weakkeys)
end
local function totargetoptions(to)
if type(to) == "table" then
if to.Triple then
to.CPU = to.CPU or ""
to.Features = to.Features or ""
end
return to
elseif to == nil then return {}
else error("expected a table for target options") end
end
local compilationunit = {}
compilationunit.__index = compilationunit
function terra.newcompilationunit(opt,to)
return setmetatable({ symbols = newweakkeytable(), livefunctions = opt and newweakkeytable() or nil, llvm_cu = terra.initcompilationunit(opt,totargetoptions(to)) },compilationunit) -- mapping from Types,Functions,Globals,Constants -> llvm value associated with them for this compilation
end
function compilationunit:addvalue(k,v)
if type(k) ~= "string" then k,v = nil,k end
local t = v:gettype()
if terra.isglobalvar(v) then t:complete() end
return terra.compilationunitaddvalue(self,k,v)
end
function compilationunit:jitvalue(v)
local gv = self:addvalue(v)
return terra.jit(self.llvm_cu,gv)
end
function compilationunit:free()
assert(not self.livefunctions, "cannot explicitly release a compilation unit with auto-delete functions")
terra.freecompilationunit(self.llvm_cu)
end
terra.jitcompilationunit = terra.newcompilationunit(true) -- compilation unit used for JIT compilation, will eventually specify the native architecture
function terra.funcdefinition:jit(checknocont)
assert(checknocont == nil, "compile no longer supports deferred action, use :gettype instead")
if not self.rawjitptr then
self.rawjitptr,self.stats.jit = terra.jitcompilationunit:jitvalue(self)
end
return self.rawjitptr
end
terra.funcdefinition.compile = terra.funcdefinition.jit
function terra.funcdefinition:__call(...)
local ffiwrapper = self:getpointer()
return ffiwrapper(...)
end
function terra.funcdefinition:getpointer()
if not self.ffiwrapper then
local rawptr = self:jit()
self.ffiwrapper = ffi.cast(terra.types.pointer(self.type):cstring(),rawptr)
end
return self.ffiwrapper
end
function terra.funcdefinition:setinlined(v)
if self.state ~= "untyped" then
error("inlining state can only be changed before typechecking",2)
end
self.alwaysinline = v
end
function terra.funcdefinition:disas()
print("definition ", self:gettype())
terra.disassemble(terra.jitcompilationunit:addvalue(self),self:jit())
end
function terra.funcdefinition:printstats()
print("definition ", self:gettype())
for k,v in pairs(self.stats) do
print("",k,v)
end
end
terra.llvm_gcdebugmetatable = { __gc = function(obj)
print("GC IS CALLED")
end }
function terra.isfunctiondefinition(obj)
return getmetatable(obj) == terra.funcdefinition
end
--END FUNCDEFINITION
-- FUNCTION
-- a function is a list of possible function definitions that can be invoked
-- it is implemented this way to support function overloading, where the same symbol
-- may have different definitions
terra.func = {} --metatable for all function types
terra.func.__index = function(self,idx)
local r = terra.func[idx]
if r then return r end
return function(self,...)
local ND = #self.definitions
if ND == 1 then --faster path, avoid creating a table of arguments
local dfn = self.definitions[1]
return dfn[idx](dfn,...)
elseif ND == 0 then
error("attempting to call "..idx.." on undefined function",2)
end
local results
for i,dfn in ipairs(self.definitions) do
local r = { dfn[idx](dfn,...) }
results = results or r
end
return unpack(results)
end
end
function terra.func:__call(...)
if rawget(self,"fastcall") then
return self.fastcall(...)
end
if #self.definitions == 1 then --generate fast path for the non-overloaded case
local defn = self.definitions[1]
local ptr = defn:getpointer() --forces compilation
self.fastcall = ptr
return self.fastcall(...)
end
local results
for i,v in ipairs(self.definitions) do
--TODO: this is very inefficient, we should have a routine which
--figures out which function to call based on argument types
results = {pcall(v.__call,v,...)}
if results[1] == true then
table.remove(results,1)
return unpack(results)
end
end
--none of the definitions worked, remove the final error
error(results[2])
end
function terra.func:adddefinition(v)
v.name = self.name --propagate function name to definition
--this will be used as the name for llvm debugging, etc.
self.fastcall = nil
self.definitions:insert(v)
end
function terra.func:getdefinitions()
return self.definitions
end
function terra.func:getname() return self.name end
function terra.func:setname(name)
self.name = tostring(name)
for i,d in ipairs(self.definitions) do
d.name = self.name
end
return self
end
function terra.isfunction(obj)
return getmetatable(obj) == terra.func
end
-- END FUNCTION
-- GLOBALVAR
terra.globalvar = {} --metatable for all global variables
terra.globalvar.__index = terra.globalvar
function terra.isglobalvar(obj)
return getmetatable(obj) == terra.globalvar
end
function terra.globalvar:gettype()
return self.type
end
--terra.createglobal provided by tcompiler.cpp
function terra.global(typ,c, name, isextern, addressspace)
if not terra.types.istype(typ) then
c,name,isextern,addressspace = typ,c,name,isextern --shift arguments right
c = terra.constant(c)
typ = c.type
elseif c ~= nil then
c = terra.constant(typ,c)
end
local gbl = setmetatable({type = typ, isglobal = true, symbol = terra.newsymbol(name or "<global>"), initializer = c, name = name, isextern = isextern or false, addressspace = tonumber(addressspace) or 0},terra.globalvar)
if c then --if we have an initializer we know that the type is not opaque and we can create the variable
--we need to call this now because it is possible for the initializer's underlying cdata object to change value
--in later code
gbl:getpointer()
end
return gbl
end
function terra.globalvar:getpointer()
if not self.cdata_ptr then
local rawptr = terra.jitcompilationunit:jitvalue(self)
self.cdata_ptr = terra.cast(terra.types.pointer(self.type),rawptr)
end
return self.cdata_ptr
end
function terra.globalvar:get()
local ptr = self:getpointer()
return ptr[0]
end
function terra.globalvar:set(v)
local ptr = self:getpointer()
ptr[0] = v
end
-- END GLOBALVAR
-- MACRO
terra.macro = {}
terra.macro.__index = terra.macro
terra.macro.__call = function(self,...)
if not self.fromlua then
error("macros must be called from inside terra code",2)
end
return self.fromlua(...)
end
function terra.macro:run(ctx,tree,...)
if self._internal then
return self.fromterra(ctx,tree,...)
else
return self.fromterra(...)
end
end
function terra.ismacro(t)
return getmetatable(t) == terra.macro
end
function terra.createmacro(fromterra,fromlua)
return setmetatable({fromterra = fromterra,fromlua = fromlua}, terra.macro)
end
function terra.internalmacro(...)
local m = terra.createmacro(...)
m._internal = true
return m
end
_G["macro"] = terra.createmacro --introduce macro intrinsic into global namespace
-- END MACRO
function terra.israwlist(l)
if terra.islist(l) then
return true
elseif type(l) == "table" and not getmetatable(l) then
local sz = #l
local i = 0
for k,v in pairs(l) do
i = i + 1
end
return i == sz --table only has integer keys and no other keys, we treat it as a list
end
return false
end
-- QUOTE
terra.quote = {}
terra.quote.__index = terra.quote
function terra.isquote(t)
return getmetatable(t) == terra.quote
end
function terra.quote:astype()
if not self.tree:is "typedexpression" or not self.tree.expression:is "luaobject" or not terra.types.istype(self.tree.expression.value) then
error("quoted value is not a type")
end
return self.tree.expression.value
end
function terra.quote:istyped()
return self.tree:is "typedexpression" and not self.tree.expression:is "luaobject"
end
function terra.quote:gettype()
if not self:istyped() then
error("not a typed quote")
end
return self.tree.expression.type
end
function terra.quote:islvalue()
if not self:istyped() then
error("not a typed quote")
end
return self.tree.expression.lvalue
end
function terra.quote:asvalue()
local function getvalue(e)
if e:is "literal" then
if type(e.value) == "userdata" then
return tonumber(ffi.cast("uint64_t *",e.value)[0])
else
return e.value
end
elseif e:is "constant" then
return tonumber(e.value.object) or e.value.object
elseif e:is "constructor" then
local t,typ = {},e.type
for i,r in ipairs(typ:getentries()) do
local v,e = getvalue(e.expressions[i])
if e then return nil,e end
local key = typ.convertible == "tuple" and i or r.field
t[key] = v
end
return t
elseif e:is "typedexpression" then
return getvalue(e.expression)
elseif e:is "operator" and e.operator == terra.kinds["-"] and #e.operands == 1 then
local v,er = getvalue(e.operands[1])
return type(v) == "number" and -v, er
elseif e:is "var" and terra.issymbol(e.value) then
return e.value
else
return nil, "not a constant value (note: :asvalue() isn't implement for all constants yet)"
end
end
return getvalue(self.tree)
end
function terra.newquote(tree)
return setmetatable({ tree = tree }, terra.quote)
end
-- END QUOTE
-- SYMBOL
terra.symbol = {}
terra.symbol.__index = terra.symbol
function terra.issymbol(s)
return getmetatable(s) == terra.symbol
end
terra.symbol.count = 0
function terra.newsymbol(typ,displayname)
if typ and not terra.types.istype(typ) then
if type(typ) == "string" and displayname == nil then
displayname = typ
typ = nil
else
error("argument is not a type",2)
end
end
local self = setmetatable({
id = terra.symbol.count,
type = typ,
displayname = displayname
},terra.symbol)
terra.symbol.count = terra.symbol.count + 1
return self
end
function terra.symbol:__tostring()
return "$"..(self.displayname or tostring(self.id))
end
function terra.symbol:tocname() return "__symbol"..tostring(self.id) end
_G["symbol"] = terra.newsymbol
-- INTRINSIC
function terra.intrinsic(str, typ)
local typefn
if typ == nil and type(str) == "function" then
typefn = str
elseif type(str) == "string" and terra.types.istype(typ) then
typefn = function() return str,typ end
else
error("expected a name and type or a function providing a name and type but found "..tostring(str) .. ", " .. tostring(typ))
end
local function intrinsiccall(diag,e,...)
local args = terra.newlist {...}
local types = args:map("gettype")
local name,intrinsictype = typefn(types)
if type(name) ~= "string" then
diag:reporterror(e,"expected an intrinsic name but found ",terra.type(name))
name = "<unknownintrinsic>"
elseif intrinsictype == terra.types.error then
diag:reporterror(e,"intrinsic ",name," does not support arguments: ",unpack(types))
intrinsictype = terra.types.funcpointer(types,{})
elseif not terra.types.istype(intrinsictype) or not intrinsictype:ispointertofunction() then
diag:reporterror(e,"expected intrinsic to resolve to a function type but found ",terra.type(intrinsictype))
intrinsictype = terra.types.funcpointer(types,{})
end
local fn = terralib.externfunction(name,intrinsictype,nil,e)
local literal = terra.createterraexpression(diag,e,fn)
local rawargs = args:map("tree")
return terra.newtree(e, { kind = terra.kinds.apply, value = literal, arguments = rawargs })
end
return terra.internalmacro(intrinsiccall)
end
terra.asm = terra.internalmacro(function(diag,tree,returntype, asm, constraints,volatile,...)
local args = terra.newlist({...}):map(function(e) return e.tree end)
return terra.newtree(tree, { kind = terra.kinds.inlineasm, type = returntype:astype(), asm = tostring(asm:asvalue()), volatile = not not volatile:asvalue(), constraints = tostring(constraints:asvalue()), arguments = args })
end)
-- CONSTRUCTORS
do --constructor functions for terra functions and variables
local name_count = 0
local function newfunctiondefinition(newtree,env,reciever)
local obj = { untypedtree = newtree, filename = newtree.filename, state = "untyped", stats = {} }
local fn = setmetatable(obj,terra.funcdefinition)
--handle desugaring of methods defintions by adding an implicit self argument
if reciever ~= nil then
local pointerto = terra.types.pointer
local addressof = terra.newtree(newtree, { kind = terra.kinds.luaexpression, expression = function() return pointerto(reciever) end })
local sym = terra.newtree(newtree, { kind = terra.kinds.symbol, name = "self"})
local implicitparam = terra.newtree(newtree, { kind = terra.kinds.entry, name = sym, type = addressof })
--add the implicit parameter to the parameter list
local newparameters = terra.newlist{implicitparam}
for _,p in ipairs(newtree.parameters) do
newparameters:insert(p)
end
fn.untypedtree = newtree:copy { parameters = newparameters}
end
local starttime = terra.currenttimeinseconds()
fn.untypedtree = terra.specialize(fn.untypedtree,env,3)
fn.stats.specialize = terra.currenttimeinseconds() - starttime
return fn
end
local function mkfunction(name)
assert(name and type(name) == "string")
return setmetatable({definitions = terra.newlist(), name = name},terra.func)
end
local function layoutstruct(st,tree,env)
local diag = terra.newdiagnostics()
diag:begin()
if st.tree then
diag:reporterror(tree,"attempting to redefine struct")
diag:reporterror(st.tree,"previous definition was here")
end
st.undefined = nil
local function getstructentry(v)
local success,resolvedtype = terra.evalluaexpression(diag,env,v.type)
if not success then return end
if not terra.types.istype(resolvedtype) then
diag:reporterror(v,"lua expression is not a terra type but ", terra.type(resolvedtype))
return terra.types.error
end
return { field = v.key, type = resolvedtype }
end
local function getrecords(records)
return records:map(function(v)
if terra.islist(v) then
return getrecords(v)
else
return getstructentry(v)
end
end)
end
local success,metatype
if tree.metatype then
success,metatype = terra.evalluaexpression(diag,env,tree.metatype)
end
st.entries = getrecords(tree.records)
st.tree = tree --to track whether the struct has already beend defined
--we keep the tree to improve error reporting
st.anchor = tree --replace the anchor generated by newstruct with this struct definition
--this will cause errors on the type to be reported at the definition
if success then
local success,err = pcall(metatype,st)