-
Notifications
You must be signed in to change notification settings - Fork 203
/
terralib.lua
4909 lines (4565 loc) · 194 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")
local asdl = require("asdl")
local List = asdl.List
-- 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:match("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
setmetatable(terra.kinds, { __index = function(self,idx)
error("unknown kind accessed: "..tostring(idx))
end })
local T = asdl.NewContext()
T:Extern("TypeOrLuaExpression", function(t) return T.Type:isclassof(t) or T.luaexpression:isclassof(t) end)
T:Define [[
ident = escapedident(luaexpression expression) # removed during specialization
| namedident(string value)
| labelident(Label value)
field = recfield(ident key, tree value)
| listfield(tree value)
structbody = structentry(string key, luaexpression type)
| structlist(structbody* entries)
param = unevaluatedparam(ident name, luaexpression? type)
| concreteparam(Type? type, string name, Symbol symbol,boolean isnamed)
structdef = (luaexpression? metatype, structlist records)
attr = (boolean nontemporal, number? alignment, boolean isvolatile)
fenceattr = (string? syncscope, string ordering)
cmpxchgattr = (string? syncscope, string success_ordering, string failure_ordering, number? alignment, boolean isvolatile, boolean isweak)
atomicattr = (string? syncscope, string ordering, number? alignment, boolean isvolatile)
Symbol = (Type type, string displayname, number id)
Label = (string displayname, number id)
tree =
# trees that are introduced in parsing and are ...
# removed during specialization
luaexpression(function expression, boolean isexpression)
# removed during typechecking
| constructoru(field* records) #untyped version
| selectu(tree value, ident field) #untyped version
| method(tree value,ident name,tree* arguments)
| statlist(tree* statements)
| fornumu(param variable, tree initial, tree limit, tree? step,block body) #untyped version
| defvar(param* variables, boolean hasinit, tree* initializers)
| forlist(param* variables, tree iterator, block body)
| functiondefu(param* parameters, boolean is_varargs, TypeOrLuaExpression? returntype, block body)
# introduced temporarily during specialization/typing, but removed after typing
| luaobject(any value)
| setteru(function setter) # temporary node introduced and removed during typechecking to handle __update and __setfield
| quote(tree tree)
# trees that exist after typechecking and handled by the backend:
| var(string name, Symbol? symbol) #symbol is added during specialization
| literal(any? value, Type type)
| index(tree value,tree index)
| apply(tree value, tree* arguments)
| letin(tree* statements, tree* expressions, boolean hasstatements)
| operator(string operator, tree* operands)
| block(tree* statements)
| assignment(tree* lhs,tree* rhs)
| gotostat(ident label)
| breakstat()
| label(ident label)
| whilestat(tree condition, block body)
| repeatstat(tree* statements, tree condition)
| fornum(allocvar variable, tree initial, tree limit, tree? step, block body)
| ifstat(ifbranch* branches, block? orelse)
| switchstat(tree condition, tree* cases, block? ordefault)
| defer(tree expression)
| select(tree value, number index, string fieldname) # typed version, fieldname for debugging
| globalvalueref(string name, globalvalue value)
| constant(cdata value, Type type)
| attrstore(tree address, tree value, attr attrs)
| attrload(tree address, attr attrs)
| fence(fenceattr attrs)
| cmpxchg(tree address, tree cmp, tree new, cmpxchgattr attrs)
| atomicrmw(string operator, tree address, tree value, atomicattr attrs)
| debuginfo(string customfilename, number customlinenumber)
| arrayconstructor(Type? oftype,tree* expressions)
| vectorconstructor(Type? oftype,tree* expressions)
| sizeof(Type oftype)
| inlineasm(Type type, string asm, boolean volatile, string constraints, tree* arguments)
| cast(Type to, tree expression)
| allocvar(string name, Symbol symbol)
| structcast(allocvar structvariable, tree expression, storelocation* entries)
| constructor(tree* expressions)
| returnstat(tree expression)
| setter(allocvar rhs, tree setter) # handles custom assignment behavior, real rhs is first stored in 'rhs' and then the 'setter' expression uses it
# special purpose nodes, they only occur in specific locations, but are considered trees because they can contain typed trees
| ifbranch(tree condition, block body)
| switchcase(tree condition, block body)
| storelocation(number index, tree value) # for struct cast, value uses structvariable
Type = primitive(string type, number bytes, boolean signed)
| pointer(Type type, number addressspace) unique
| vector(Type type, number N) unique
| array(Type type, number N) unique
| functype(Type* parameters, Type returntype, boolean isvararg) unique
| struct(string name)
| niltype #the type of the singleton nil (implicitly convertable to any pointer type)
| opaque #an type of unknown layout used with a pointer (&opaque) to point to data of an unknown type (i.e. void*)
| error #used in compiler to squelch errors
| luaobjecttype #type of expressions that hold temporary luaobjects in the compiler, removed during typechecking
labelstate = undefinedlabel(gotostat * gotos, table* positions) #undefined label with gotos pointing to it
| definedlabel(table position, label label) #defined label with position and label object defining it
definition = functiondef(string? name, functype type, allocvar* parameters, boolean is_varargs, block body, table labeldepths, globalvalue* globalsused)
| functionextern(string? name, functype type)
globalvalue = terrafunction(definition? definition)
| globalvariable(tree? initializer, number addressspace, boolean extern, boolean constant)
attributes(string name, Type type, table anchor)
overloadedterrafunction = (string name, terrafunction* definitions)
]]
terra.irtypes = T
T.var.lvalue = true
function T.allocvar:settype(typ)
assert(T.Type:isclassof(typ))
self.type, self.symbol.type = typ,typ
end
-- temporary until we replace with asdl
local tokens = setmetatable({},{__index = function(self,idx) return idx 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
terra.printraw(obj)
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
function T.tree:is(value)
return self.kind == value
end
function terra.printraw(self)
local function header(t)
local mt = getmetatable(t)
if type(t) == "table" and mt and type(mt.__fields) == "table" then
return t.kind or tostring(mt)
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) then
return --don't print the entire nested function...
end
parents[t] = true
depth = depth + 1
for k,v in pairs(t) do
local prefix
if type(k) == "table" and not terra.issymbol(k) then
prefix = ("<table (mt = %s)>"):format(tostring(getmetatable(k)))
else
prefix = tostring(k)
end
if k ~= "kind" and k ~= "offset" then
prefix = spacing..prefix..": "
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(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(self))
if type(self) == "table" then
printElem(self," ")
end
end
local prettystring --like printraw, but with syntax formatting rather than as raw lsits
local function newobject(ref,ctor,...) -- create a new object, copying the line/file info from the reference
assert(ref.linenumber and ref.filename, "not a anchored object?")
local r = ctor(...)
r.linenumber,r.filename,r.offset = ref.linenumber,ref.filename,ref.offset
return r
end
local function copyobject(ref,newfields) -- copy an object, extracting any new replacement fields from newfields table
local class = getmetatable(ref)
local fields = class.__fields
assert(fields,"not a asdl object?")
local function handlefield(i,...) -- need to do this with tail recursion rather than a loop to handle nil values
if i == 0 then
return newobject(ref,class,...)
else
local f = fields[i]
local a = newfields[f.name] or ref[f.name]
newfields[f.name] = nil
return handlefield(i-1,a,...)
end
end
local r = handlefield(#fields)
for k,v in pairs(newfields) do
error("unused field in copy: "..tostring(k))
end
return r
end
T.tree.copy = copyobject --support :copy directly on objects
function T.tree:aserror() -- a copy of this tree with an error type, used when unable to return a real value
return self:copy{}:withtype(terra.types.error)
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 T.tree:isclassof(v)
end
-- END TREE
local function mkstring(self,begin,sep,finish)
return begin..table.concat(self:map(tostring),sep)..finish
end
terra.newlist = List
function terra.islist(l) return List:isclassof(l) end
-- 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
local diagcache = setmetatable({},{ __mode = "v" })
local function formaterror(anchor,...)
if not anchor or not anchor.filename or not anchor.linenumber then
error("nil anchor")
end
local errlist = List()
errlist:insert(anchor.filename..":"..anchor.linenumber..": ")
for i = 1,select("#",...) do errlist:insert(tostring(select(i,...))) end
errlist:insert("\n")
if not anchor.offset then
return errlist:concat()
end
local filename = anchor.filename
local filetext = diagcache[filename]
if not filetext then
local file = io.open(filename,"r")
if file then
filetext = file:read("*all")
diagcache[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 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
return errlist:concat()
end
local function erroratlocation(anchor,...)
error(formaterror(anchor,...),0)
end
terra.diagnostics.source = {}
function terra.diagnostics:reporterror(anchor,...)
--erroratlocation(anchor,...) -- early error for debugging
self.errors:insert(formaterror(anchor,...))
end
function terra.diagnostics:haserrors()
return #self.errors > 0
end
function terra.diagnostics:finishandabortiferrors(msg,depth)
if #self.errors > 0 then
error(msg.."\n"..self.errors:concat(),depth+1)
end
end
function terra.newdiagnostics()
return setmetatable({ errors = List() },terra.diagnostics)
end
-- END DIAGNOSTICS
-- CUSTOM TRACEBACK
local TRACEBACK_LEVELS1 = 12
local TRACEBACK_LEVELS2 = 10
local function findfirstnilstackframe() --because stack size is not exposed we binary search for it
local low,high = 1,1
while debug.getinfo(high,"") ~= nil do
low,high = high,high*2
end --invariant: low is non-nil frame, high is nil frame, range gets smaller each iteration
while low + 1 ~= high do
local m = math.floor((low+high)/2)
if debug.getinfo(m,"") ~= nil then
low = m
else
high = m
end
end
return high - 1 --don't count ourselves
end
--all calls to user-defined functions from the compiler go through this wrapper
local function invokeuserfunction(anchor, what, speculate, userfn, ...)
if not speculate then
local result = userfn(...)
-- invokeuserfunction is recognized by a customtraceback and we need to prevent the tail call
return result
end
local success,result = xpcall(userfn,debug.traceback,...)
-- same here
return success, result
end
terra.fulltrace = false
terra.slimtrace = false
-- override the lua traceback function to be aware of Terra compilation contexts
function debug.traceback(msg,level)
level = level or 1
level = level + 1 -- don't count ourselves
local lim = terra.fulltrace and math.huge or TRACEBACK_LEVELS1 + 1
local lines = List()
if msg then
local file,outsideline,insideline,rest = msg:match "^$terra$(.*)$terra$(%d+):(%d+):(.*)"
if file then
msg = ("%s:%d:%s"):format(file,outsideline+insideline-1,rest)
end
lines:insert(("%s\n"):format(msg))
end
lines:insert("stack traceback:")
while true do
local di = debug.getinfo(level,"Snlf")
if not di then break end
if di.func == invokeuserfunction then
local anchorname,anchor = debug.getlocal(level,1)
local whatname,what = debug.getlocal(level,2)
assert(anchorname == "anchor" and whatname == "what")
lines:insert("\n\t")
lines:insert(formaterror(anchor,"Errors reported during "..what):sub(1,-2))
else
local short_src,currentline,linedefined = di.short_src,di.currentline,di.linedefined
local file,outsideline = di.source:match("^@$terra$(.*)$terra$(%d+)$")
if not terra.slimtrace or di.source:match(".*terralib%.lua$") == nil then
if file then
short_src = file
currentline = currentline and (currentline + outsideline - 1)
linedefined = linedefined and (linedefined + outsideline - 1)
end
lines:insert(("\n\t%s:"):format(short_src))
if di.currentline and di.currentline >= 0 then
lines:insert(("%d:"):format(currentline))
end
if di.namewhat ~= "" then
lines:insert((" in function '%s'"):format(di.name))
elseif di.what == "main" then
lines:insert(" in main chunk")
elseif di.what == "C" then
lines:insert( (" at %s"):format(tostring(di.func)))
else
lines:insert((" in function <%s:%d>"):format(short_src,linedefined))
end
end
end
level = level + 1
if level == lim then
if debug.getinfo(level + TRACEBACK_LEVELS2,"") ~= nil then
lines:insert("\n\t...")
level = findfirstnilstackframe() - TRACEBACK_LEVELS2
end
lim = math.huge
end
end
return table.concat(lines)
end
-- GLOBALVALUE
function T.globalvalue:gettype() return self.type end
function T.globalvalue:getname() return self.name end
function T.globalvalue:setname(name) self.name = tostring(name) return self end
local function readytocompile(root)
local visited = {}
local function visit(gv)
if visited[gv] or gv.readytocompile then return end
visited[gv] = true
if gv.kind == "terrafunction" then
if not gv:isdefined() then
erroratlocation(gv.anchor,"function "..gv:getname().." is not defined.")
end
gv.type:completefunction()
if gv.definition.kind == "functiondef" then
for i,g in ipairs(gv.definition.globalsused) do
visit(g)
end
end
elseif gv.kind == "globalvariable" then
gv.type:complete()
else error("unknown gv:"..tostring(gv)) end
end
visit(root)
-- if we succeeded, we can mark all the globals we visited ready, so they don't have to recompute this
for g,_ in pairs(visited) do
g.readytocompile = true
end
end
function T.globalvalue:checkreadytocompile()
if not self.readytocompile then
readytocompile(self)
end
end
function T.globalvalue:compile()
if not self.rawjitptr then
self.stats = self.stats or {}
self.rawjitptr,self.stats.jit = terra.jitcompilationunit:jitvalue(self)
end
return self.rawjitptr
end
function T.globalvalue:getpointer()
if not self.ffiwrapper then
local rawptr = self:compile()
self.ffiwrapper = ffi.cast(terra.types.pointer(self.type):cstring(),rawptr)
end
return self.ffiwrapper
end
-- TERRAFUNCTION
function T.terrafunction:__call(...)
local ffiwrapper = self:getpointer()
return ffiwrapper(...)
end
function T.terrafunction:setinlined(v)
assert(self:isdefined(), "attempting to set the inlining state of an undefined function")
self.definition.alwaysinline = not not v
assert(not (self.definition.alwaysinline and self.definition.dontoptimize),
"setinlined(true) and setoptimized(false) are incompatible")
end
function T.terrafunction:setoptimized(v)
assert(self:isdefined(), "attempting to set the optimization state of an undefined function")
self.definition.dontoptimize = not v
assert(not (self.definition.alwaysinline and self.definition.dontoptimize),
"setinlined(true) and setoptimized(false) are incompatible")
end
function T.terrafunction:setcallingconv(v)
assert(self:isdefined(), "attempting to set the calling convention of an undefined function")
self.definition.callingconv = tostring(v)
end
function T.terrafunction:setnoreturn(v)
assert(self:isdefined(), "attempting to set the noreturn state of an undefined function")
self.definition.noreturn = not not v
end
function T.terrafunction:disas()
print("definition ", self:gettype())
terra.disassemble(terra.jitcompilationunit:addvalue(self),self:compile())
end
function T.terrafunction:printstats()
self:compile()
print("definition ", self:gettype())
for k,v in pairs(self.stats) do
print("",k,v)
end
end
function T.terrafunction:isextern() return self.definition and self.definition.kind == "functionextern" end
function T.terrafunction:isdefined() return self.definition ~= nil end
function T.terrafunction:setname(name)
self.name = tostring(name)
if self.definition then self.definition.name = name end
return self
end
function T.terrafunction:adddefinition(functiondef)
if self.definition then error("terra function "..self.name.." already defined") end
self:resetdefinition(functiondef)
end
function T.terrafunction:resetdefinition(functiondef)
if T.terrafunction:isclassof(functiondef) and functiondef:isdefined() then
functiondef = functiondef.definition
end
assert(T.definition:isclassof(functiondef), "expected a defined terra function")
if self.readytocompile then error("cannot reset a definition of function that has already been compiled",2) end
if self.type ~= functiondef.type and self.type ~= terra.types.placeholderfunction then
error(("attempting to define terra function declaration with type %s with a terra function definition of type %s"):format(tostring(self.type),tostring(functiondef.type)))
end
self.definition,self.type,functiondef.name = functiondef,functiondef.type,assert(self.name)
end
function T.terrafunction:gettype(nop)
assert(nop == nil, ":gettype no longer takes any callbacks for when a function is complete")
if self.type == terra.types.placeholderfunction then
error("function being recursively referenced needs an explicit return type, function defintion at: "..formaterror(self.anchor,""),2)
end
return self.type
end
function terra.isfunction(obj)
return T.terrafunction:isclassof(obj)
end
-- END FUNCTION
function terra.isoverloadedfunction(obj) return T.overloadedterrafunction:isclassof(obj) end
function T.overloadedterrafunction:adddefinition(d)
assert(T.terrafunction:isclassof(d),"expected a terra function")
d:setname(self.name)
self.definitions:insert(d)
return self
end
function T.overloadedterrafunction:getdefinitions() return self.definitions end
function terra.overloadedfunction(name, init)
init = init or {}
return T.overloadedterrafunction(name,List{unpack(init)})
end
-- GLOBALVAR
function terra.isglobalvar(obj)
return T.globalvariable:isclassof(obj)
end
function T.globalvariable:init()
self.symbol = terra.newsymbol(self.type,self.name)
end
function T.globalvariable:isextern() return self.extern end
function T.globalvariable:isconstant() return self.constant end
local typecheck
local function constantcheck(e,checklvalue)
local kind = e.kind
if "literal" == kind or "constant" == kind or "sizeof" == kind then -- trivially ok
elseif "index" == kind and checklvalue then
constantcheck(e.value,true)
constantcheck(e.index)
elseif "operator" == kind then
local op = e.operator
if "@" == op then
constantcheck(e.operands[1])
if not checklvalue then
erroratlocation(e,"non-constant result of dereference used as a constant initializer")
end
elseif "&" == op then
constantcheck(e.operands[1],true)
else
for _,ee in ipairs(e.operands) do constantcheck(ee) end
end
elseif "select" == kind then
constantcheck(e.value,checklvalue)
elseif "globalvalueref" == kind then
if e.value.kind == "globalvariable" and not (e.value:isconstant() or checklvalue) then
erroratlocation(e,"non-constant use of global variable used as a constant initializer")
end
elseif "arrayconstructor" == kind or "vectorconstructor" == kind then
for _,ee in ipairs(e.expressions) do constantcheck(ee) end
elseif "cast" == kind then
if e.expression.type:isarray() then
if checklvalue then
constantcheck(e.expression,true)
else
erroratlocation(e,"non-constant cast of array to pointer used as a constant initializer")
end
else constantcheck(e.expression) end
elseif "structcast" == kind then
constantcheck(e.expression)
elseif "constructor" == kind then
for _,ee in ipairs(e.expressions) do constantcheck(ee) end
else
erroratlocation(e,"non-constant expression being used as a constant initializer")
end
return e
end
local function createglobalinitializer(anchor, typ, c)
if not c then return nil end
if not T.quote:isclassof(c) then
local c_ = c
c = newobject(anchor,T.luaexpression,function() return c_ end,true)
end
if typ then
c = newobject(anchor, T.cast, typ, c)
end
return constantcheck(typecheck(c))
end
function terra.global(...)
local typ = select(1,...)
typ = terra.types.istype(typ) and typ or nil
local c,name,isextern,isconstant,addressspace = select(typ and 2 or 1,...)
local anchor = terra.newanchor(2)
c = createglobalinitializer(anchor,typ,c)
if not typ then --set type if not set
if not c then
error("type must be specified for globals without an initializer",2)
end
typ = c.type
end
return T.globalvariable(c,tonumber(addressspace) or 0, isextern or false, isconstant or false, name or "<global>", typ, anchor)
end
function T.globalvariable:setinitializer(init)
if self.readytocompile then error("cannot change global variable initializer after it has been compiled.",2) end
self.initializer = createglobalinitializer(self.anchor,self.type,init)
end
function T.globalvariable:get()
local ptr = self:getpointer()
return ptr[0]
end
function T.globalvariable:set(v)
local ptr = self:getpointer()
ptr[0] = v
end
function T.globalvariable:__tostring()
local kind = self:isconstant() and "constant" or "global"
local extern = self:isextern() and "extern " or ""
local r = ("%s%s %s : %s"):format(extern,kind,self.name,tostring(self.type))
if self.initializer then
r = ("%s = %s"):format(r,prettystring(self.initializer,false))
end
return r
end
-- END GLOBALVAR
-- TARGET
local weakkeys = { __mode = "k" }
local function newweakkeytable()
return setmetatable({},weakkeys)
end
local function cdatawithdestructor(ud,dest)
local cd = ffi.cast("void*",ud)
ffi.gc(cd,dest)
return cd
end
terra.target = {}
terra.target.__index = terra.target
function terra.istarget(a) return getmetatable(a) == terra.target end
function terra.newtarget(tbl)
if not type(tbl) == "table" then error("expected a table",2) end
local Triple,CPU,Features,FloatABIHard = tbl.Triple,tbl.CPU,tbl.Features,tbl.FloatABIHard
if Triple then
CPU = CPU or ""
Features = Features or ""
end
return setmetatable({ llvm_target = cdatawithdestructor(terra.inittarget(Triple,CPU,Features,FloatABIHard),terra.freetarget),
Triple = Triple,
cnametostruct = { general = {}, tagged = {}} --map from llvm_name -> terra type used to make c structs unique per llvm_name
},terra.target)
end
function terra.target:getorcreatecstruct(displayname,tagged)
local namespace
if displayname ~= "" then
namespace = tagged and self.cnametostruct.tagged or self.cnametostruct.general
end
local typ = namespace and namespace[displayname]
if not typ then
typ = terra.types.newstruct(displayname == "" and "anon" or displayname)
typ.undefined = true
if namespace then namespace[displayname] = typ end
end
return typ
end
local function createoptimizationprofile(profile)
if type(profile) ~= "table" then
error("expected optimization profile to be a table but found " .. type(profile))
end
-- Handle fastmath flag.
local fastmath = profile["fastmath"]
if fastmath == nil then
fastmath = {}
elseif type(fastmath) == "boolean" then
fastmath = fastmath and {"fast"} or {}
elseif type(fastmath) == "string" then
fastmath = {fastmath}
elseif type(fastmath) == "table" then
for _, v in ipairs(fastmath) do
if type(v) ~= "string" then
error("expected fastmath to be a string but found " .. type(v))
end
end
-- Ok, leave it alone.
else
error("expected fastmath to be a boolean or string but found " .. type(fastmath))
end
profile["fastmath"] = fastmath -- Write it back.
return profile
end
-- COMPILATION UNIT
local compilationunit = {}
compilationunit.__index = compilationunit
function terra.newcompilationunit(target,opt,profile)
assert(terra.istarget(target),"expected a target object")
profile = createoptimizationprofile(profile)
return setmetatable({ symbols = newweakkeytable(),
collectfunctions = opt,
llvm_cu = cdatawithdestructor(terra.initcompilationunit(target.llvm_target,opt,profile),terra.freecompilationunit) },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
v:checkreadytocompile()
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.collectfunctions, "cannot explicitly release a compilation unit with auto-delete functions")
ffi.gc(self.llvm_cu,nil) --unregister normal destructor object
terra.freecompilationunit(self.llvm_cu)
end
function compilationunit:dump() terra.dumpmodule(self.llvm_cu) end
terra.nativetarget = terra.newtarget {}
terra.jitcompilationunit = terra.newcompilationunit(terra.nativetarget,true,{fastmath=false}) -- compilation unit used for JIT compilation, will eventually specify the native architecture
terra.llvm_gcdebugmetatable = { __gc = function(obj)
print("GC IS CALLED")
end }
-- 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
function terra.isquote(t)
return T.quote:isclassof(t)
end
function T.quote:astype()
if not self.tree:is "luaobject" or not T.Type:isclassof(self.tree.value) then
error("quoted value is not a type")
end
return self.tree.value
end
function T.quote:isluaobject() return self.tree.type == T.luaobjecttype end
function T.quote:gettype() return self.tree.type end
function T.quote:islvalue() return not not self.tree.lvalue end
function T.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 "globalvalueref" then return e.value
elseif e:is "constant" then
return tonumber(e.value) or e.value or error("no value?")
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 "var" then return e.symbol
elseif e:is "luaobject" then
return e.value
else
local runconstantprop = function()
return terra.constant(self):get()
end
local status,value = pcall(runconstantprop)
if not status then
return nil, "not a constant value (note: :asvalue() isn't implement for all constants yet), error propagating constant was: "..tostring(value)
end
return value
end
end
return getvalue(self.tree)
end
function T.quote:init()
assert(T.Type:isclassof(self.tree.type), "quote tree must have a type")
end
function terra.newquote(tree) return newobject(tree,T.quote,tree) end
-- END QUOTE
local identcount = 0
-- SYMBOL
function terra.issymbol(s)
return T.Symbol:isclassof(s)
end
function terra.newsymbol(typ,displayname)
if not terra.types.istype(typ) then error("symbol requires a Terra type but found "..terra.type(typ).." (use label() for goto labels,method names, and field names)") end
displayname = displayname or tostring(identcount)
local r = T.Symbol(typ,displayname,identcount)
identcount = identcount + 1
return r
end
function T.Symbol:__tostring()
return "$"..self.displayname
end
function T.Symbol:tocname() return "__symbol"..tostring(self.id) end
_G["symbol"] = terra.newsymbol
-- LABEL
function terra.islabel(l) return T.Label:isclassof(l) end
function T.Label:__tostring() return "$"..self.displayname end
function terra.newlabel(displayname)
displayname = displayname or tostring(identcount)
local r = T.Label(displayname,identcount)
identcount = identcount + 1
return r
end
function T.Label:tocname() return "__label_"..tostring(self.id) end
_G["label"] = terra.newlabel
-- 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,{})