/
plop_core.t
1963 lines (1735 loc) · 60.3 KB
/
plop_core.t
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
--[[
plop - A Small Langauge for abstracting over byte-by-byte details of
physical layout
See interface description at the end of this file for more information
by Gilbert Bernstein
March 2016
See LICENSE
--]]
import 'adt'
local Exports = {}
package.loaded["plop_core"] = Exports
--local C = terralib.includecstring [[ #include <stdio.h> ]]
local newlist = terralib.newlist
--local function clone_list(xs)
-- return newlist{ unpack(xs) }
--end
--local function clone_tbl(xs)
-- local cp = {}
-- for k,v in pairs(xs) do cp[k] = v end
-- return cp
--end
local function printtbl(xs)
for k,v in pairs(xs) do print(k,v) end
end
--local function sorted_pairs(xs)
-- local ps = newlist()
-- for k,v in pairs(xs) do ps:insert{k,v} end
-- ps:sort(function(a,b) return a[1]<b[1] end)
-- local i=0
-- return function()
-- i = i+1
-- local p = ps[i]
-- if p then return p[1],p[2]
-- else return nil end
-- end
--end
local niltoken = {}
local lookuptoken = {}
local function nilconvert(val) return val==nil and niltoken or val end
-- function must return exactly one value
-- function must take at least idx_arguments
local function memoize_from(idx,f)
local cache = {}
local function memoization_wrapper(...)
local args = {select(idx,...)}
local subcache = cache
for i=1,#args do
local sub = subcache[nilconvert(args[i])]
if not sub then
sub = {}
subcache[nilconvert(args[i])] = sub
end
subcache = sub
end
local lookup = subcache[lookuptoken]
if not lookup then
lookup = f(...)
subcache[lookuptoken] = lookup
end
return lookup
end
return memoization_wrapper
end
local function memoize(f)
return memoize_from(1,f)
end
local memolist
do
local memolist_helper = memoize(function(...)
return newlist{...}
end)
memolist = function(xs) return memolist_helper(unpack(xs)) end
end
-------------------------------------------------------------------------------
-- Data Types (ASTs etc.) along with pretty printing
-------------------------------------------------------------------------------
local function is_uint(obj)
return type(obj) == 'number' and obj%1 == 0 and obj >= 0
end
local function is_id_str(obj)
return type(obj) == 'string' and string.match(obj,'^[%a_][%w_]*$')
end
local function is_anon_str(obj)
return type(obj) == 'string' and string.match(obj,'^%d+_%d+$')
end
local function is_var_str(obj) return is_id_str(obj) or is_anon_str(obj) end
---------------------------------------
-- AST-style stuff --
---------------------------------------
local ADT A
Decl = Array { sizevar : symbol?, sizetype : Prim?,
sizeval : uint?, typ : Decl }
| Struct { entries : Rec* }
| Ptr { typ : Decl }
| DPrim { prim : Prim }
attributes { linenumber : uint?,
offset : uint?,
filename : string? }
Rec = Def { name : id_str, typ : Decl }
| Const { name : id_str, val : uint }
| Chunk { name : id_str, numerator : id_str, denominator : id_str }
attributes { linenumber : uint?,
offset : uint?,
filename : string? }
Prim = SIZE
| UINT
| INT
| BOOL
| FLOAT
| SIZE8 | SIZE16 | SIZE32 | SIZE64
| UINT8 | UINT16 | UINT32 | UINT64
| INT8 | INT16 | INT32 | INT64
| FLOAT32 | FLOAT64
extern uint is_uint
extern symbol is_var_str
extern id_str is_id_str
end
local string_to_primitive = {
[ "size"] = A.SIZE,
[ "uint"] = A.UINT,
[ "int"] = A.INT,
[ "bool"] = A.BOOL,
[ "float"] = A.FLOAT,
[ "size8"] = A.SIZE8,
[ "size16"] = A.SIZE16,
[ "size32"] = A.SIZE32,
[ "size64"] = A.SIZE64,
[ "uint8"] = A.UINT8,
[ "uint16"] = A.UINT16,
[ "uint32"] = A.UINT32,
[ "uint64"] = A.UINT64,
[ "int8"] = A.INT8,
[ "int16"] = A.INT16,
[ "int32"] = A.INT32,
[ "int64"] = A.INT64,
["float32"] = A.FLOAT32,
["float64"] = A.FLOAT64,
[ "byte"] = A.UINT8,
}
local all_primitives = newlist()
for n,prim in pairs(string_to_primitive) do
if n ~= 'byte' then all_primitives:insert(prim) end
end
-- define ugly and pretty strings and set pretty as default
-- ugly may be useful for internal debugging...
for _,T in pairs(A) do T.uglystr = T.__tostring end
for s,p in pairs(string_to_primitive) do
if s ~= 'byte' then getmetatable(p).__tostring = function() return s end end
end
function A.Array:prettystr(indent)
local size = self.sizevar and self.sizevar or self.sizeval
return '['..tostring(size)..']'..self.typ:prettystr(indent)
end
function A.Ptr:prettystr(indent)
return '*'..self.typ:prettystr(indent)
end
function A.Struct:prettystr(indent)
indent = (indent or '')
local substrs = newlist()
for _,r in ipairs(self.entries) do
substrs:insert( r:prettystr(indent..' ') )
end
return '{\n'..substrs:concat('\n')..'\n'..indent..'}'
end
function A.Def:prettystr(indent)
indent = indent or ''
return indent..tostring(self.name)..' : '..self.typ:prettystr(indent)
end
function A.Const:prettystr(indent)
indent = indent or ''
return indent..tostring(self.name)..' = '..tostring(self.val)
end
function A.Chunk:prettystr(indent)
indent = indent or ''
return indent..tostring(self.name)..' = '..tostring(self.numerator)..
' / '..tostring(self.denominator)
end
function A.DPrim:prettystr(indent)
return tostring(self.prim)
end
A.Array.__tostring = A.Array.prettystr
A.Struct.__tostring = A.Struct.prettystr
A.Ptr.__tostring = A.Ptr.prettystr
A.DPrim.__tostring = A.DPrim.prettystr
A.Def.__tostring = A.Def.prettystr
A.Const.__tostring = A.Const.prettystr
A.Chunk.__tostring = A.Chunk.prettystr
function A.Decl:prettyprint() print(self:prettystr()) end
function A.Decl:uglyprint() print(self:uglystr()) end
function A.Rec:prettyprint() print(self:prettystr()) end
function A.Rec:uglyprint() print(self:uglystr()) end
local size_prim_table = {
[ A.SIZE ] = true,
[ A.SIZE8 ] = true,
[ A.SIZE16 ] = true,
[ A.SIZE32 ] = true,
[ A.SIZE64 ] = true,
}
local physical_prim_table = {
[ A.SIZE8 ] = true,
[ A.SIZE16 ] = true,
[ A.SIZE32 ] = true,
[ A.SIZE64 ] = true,
[ A.UINT8 ] = true,
[ A.UINT16 ] = true,
[ A.UINT32 ] = true,
[ A.UINT64 ] = true,
[ A.INT8 ] = true,
[ A.INT16 ] = true,
[ A.INT32 ] = true,
[ A.INT64 ] = true,
[ A.FLOAT32 ] = true,
[ A.FLOAT64 ] = true,
}
local function is_size_prim(prim) return size_prim_table[prim] ~= nil end
local function is_phys_prim(prim) return physical_prim_table[prim] ~= nil end
local is_prim = A.Prim.check
local is_dprim = A.DPrim.check
local is_ptr = A.Ptr.check
local is_array = A.Array.check
local is_struct = A.Struct.check
local is_decl = A.Decl.check
local is_def = A.Def.check
local is_const = A.Const.check
local is_chunk = A.Chunk.check
local is_rec = A.Rec.check
---------------------------------------
-- Path IR --
---------------------------------------
local ADT P
Token = DeRef
| Field { name : symbol }
| Index { name : symbol }
Path = { tokens : Token*, terminal : type_or_const }
extern symbol is_var_str
extern type_or_const function(obj) return is_prim(obj) or is_uint(obj) end
end
getmetatable(P.DeRef).__tostring = function() return '()' end
function P.Field:__tostring() return '.'..tostring(self.name) end
function P.Index:__tostring() return '['..tostring(self.name)..']' end
function P.Path:__tostring()
local subs = newlist()
for _,p in ipairs(self.tokens) do subs:insert(tostring(p)) end
return subs:concat('')..':'..tostring(self.terminal)
end
local size_num_bound_table = {
[ A.SIZE ] = math.huge,
[ A.SIZE8 ] = math.pow(2,8),
[ A.SIZE16 ] = math.pow(2,16),
[ A.SIZE32 ] = math.pow(2,32),
[ A.SIZE64 ] = math.huge,
}
local function size_bound_of_num(num)
if num < math.pow(2,8) then return A.SIZE8
elseif num < math.pow(2,16) then return A.SIZE16
elseif num < math.pow(2,32) then return A.SIZE32
else return A.SIZE64 end
end
---------------------------------------
-- Expression IR --
---------------------------------------
local ADT E
Expr = DeRef { expr : Expr, prim : Prim? }
| Add { const : uint, exprs : Expr* }
| Mul { const : uint, exprs : Expr* }
| Var { name : symbol, type : SizePrim? }
| Idx { name : symbol, type : SizePrim? }
| Const { val : uint }
| Ptr
extern uint is_uint
extern symbol is_var_str
extern Prim is_prim
extern SizePrim is_size_prim
end
-- memoize all expression constructors
local NewE = {}
for _,n in ipairs{'DeRef', 'Add', 'Mul', 'Var', 'Idx', 'Const'} do
local e = E[n]
if n=='Add' or n=='Mul' then
local memed = memoize(e)
NewE[n] = function(c, xs) return memed(c, memolist(xs)) end
else
NewE[n] = memoize(e)
end
end
local PtrVar = E.Ptr
function E.DeRef:__tostring()
local typstr = self.prim and '[&'..tostring(self.prim)..']' or ''
return '@'..typstr..'('..tostring(self.expr)..')'
end
function E.Add:__tostring()
local estrs = self.exprs:map(tostring):concat('+')
local conststr = self.const == 0 and "" or tostring(self.const)..'+'
return conststr..estrs
end
function E.Mul:__tostring()
local estrs = self.exprs:map(function(e)
local str = tostring(e)
if E.Add.check(e) then return '('..str..')' else return str end
end):concat('*')
local conststr = self.const == 1 and "" or tostring(self.const)..'*'
return conststr..estrs
end
function E.Var:__tostring()
return self.type
and '('..tostring(self.name).. ':'..tostring(self.type)..')'
or tostring(self.name)
end
function E.Idx:__tostring()
return self.type
and '('..tostring(self.name).. ':'..tostring(self.type)..')'
or tostring(self.name)
end
function E.Const:__tostring() return self.val end
local is_econst = E.Const.check
local is_evar = E.Var.check
local is_eidx = E.Idx.check
local is_emul = E.Mul.check
local is_eadd = E.Add.check
local is_ederef = E.DeRef.check
-------------------------------------------------------------------------------
-- Parsing from a Terra DSL
-------------------------------------------------------------------------------
-- example syntax:
-- local plop physical Triangles2 {
-- n_tri : uint32
-- _ : [4]byte
-- {
-- v : *[ti:n_tri][vi:3]uint32
-- n : *[ti:n_tri][ni:3]float64
-- c : *[ti:n_tri]float64
-- }
-- }
-- assumes physical tag and name have already been lexed out
local function terra_decl_parser(lexer)
local parseDecl
local function parseConst()
local const = lexer:expect(lexer.number).value
if not is_uint(const) or const <= 0 then
lexer:error('expected positive integer')
end
return const
end
local function parseIdStr()
local id = lexer:expect(lexer.name).value
if not is_id_str(id) then
lexer:error('expected valid identifier string') end
return id
end
local function get_loc()
-- linenumber, offset, filename
return { lexer:cur().linenumber, lexer:cur().offset, lexer.source }
end
local function parsePrim()
local loc = get_loc()
local primname = lexer:expect(lexer.name).value
local prim = string_to_primitive[primname]
if not prim then
lexer:error("primitive type name '"..primname.."' was unrecognized")
end
return A.DPrim(prim, unpack(loc))
end
local function parseRec()
local loc = get_loc()
local name = parseIdStr()
if lexer:nextif(':') then
return A.Def( name, parseDecl(), unpack(loc) )
else
lexer:expect('=')
if lexer:matches(lexer.number) then
return A.Const( name, parseConst(), unpack(loc) )
else
local numerator, _, denominator = parseIdStr(),
lexer:expect('/'),
parseIdStr()
return A.Chunk( name, numerator, denominator, unpack(loc) )
end
end
end
local function parseStruct()
local loc = get_loc()
local openline = lexer:expect('{').linenumber
local recs = newlist()
repeat
recs:insert( parseRec() )
-- skip optional comma or semicolon delimiters
if lexer:nextif(',') then
elseif lexer:nextif(';') then end
until lexer:matches('}')
lexer:expectmatch('}','{',openline)
return A.Struct(recs, unpack(loc))
end
local function parsePtr()
local loc = get_loc()
lexer:expect('*')
return A.Ptr(parseDecl(), unpack(loc))
end
local function parseArray()
local loc = get_loc()
local openline = lexer:expect('[').linenumber
local sz_name, sz_val
-- constant sugar
if lexer:matches(lexer.number) then
sz_val = parseConst()
else
sz_name = parseIdStr()
end
lexer:expectmatch(']','[',openline)
return A.Array(sz_name,nil,sz_val, parseDecl(), unpack(loc))
end
function parseDecl()
if lexer:matches('[') then return parseArray()
elseif lexer:matches('*') then return parsePtr()
elseif lexer:matches('{') then return parseStruct()
else return parsePrim() end
end
local decl = parseStruct()
return decl
end
-------------------------------------------------------------------------------
-- Programmatic Construction API
-------------------------------------------------------------------------------
local PreLayout = {}
PreLayout.__index = PreLayout
local function is_pre_layout(obj) return getmetatable(obj) == PreLayout end
Exports.is_pre_layout = is_pre_layout
function NewPreDecl(decl)
return setmetatable({ _hidden_decl=decl },PreLayout)
end
function NewPreRec(rec)
return setmetatable({ _hidden_rec=rec },PreLayout)
end
local function is_pre_decl(obj)
return is_pre_layout(obj) and obj._hidden_decl end
local function is_pre_rec(obj)
return is_pre_layout(obj) and obj._hidden_rec end
-- to ensure the declarations form a tree proper
local null_loc = { 0, 0, 'no_src' }
local function clone_decl(decl)
if is_const(decl) then
return A.Const( decl.name, decl.val, unpack(null_loc) )
elseif is_chunk(decl) then
return A.Chunk( decl.name, decl.numerator,
decl.denominator, unpack(null_loc) )
elseif is_def(decl) then
return A.Def( decl.name, clone_decl(decl.typ), unpack(null_loc) )
elseif is_dprim(decl) then
return A.DPrim( decl.prim, unpack(null_loc) )
elseif is_ptr(decl) then
return A.Ptr( clone_decl(decl.typ), unpack(null_loc) )
elseif is_array(decl) then
return A.Array( decl.sizevar, decl.sizetype, decl.sizeval,
clone_decl(decl.typ), unpack(null_loc) )
else -- is_struct(decl) then
return A.Struct( decl.entries:map(function(r) return clone_decl(r) end),
unpack(null_loc) )
end
end
function Exports.ArrayOf(size, decl)
local sizevar = is_id_str(size) and size or nil
local sizeval = is_uint(size) and size or nil
if not sizeval and not sizevar then
error('first argument must be either a variable name or uint', 2)
end
if not is_pre_decl(decl) then
error('second argument must be a type declaration', 2)
end
return NewPreDecl(A.Array(sizevar, nil, sizeval, decl._hidden_decl))
end
function Exports.PtrOf(decl)
if not is_pre_decl(decl) then
error('argument must be a type declaration', 2)
end
return NewPreDecl(A.Ptr(decl._hidden_decl))
end
function Exports.PrimOf(str)
local prim = string_to_primitive[str]
if not prim then
error('did not recognize primitive type "'..tostring(str)..'"', 2)
end
return NewPreDecl(A.DPrim(prim))
end
function Exports.DefOf(name, decl)
if not is_id_str(name) then
error('first argument must be a variable name', 2)
end
if not is_pre_decl(decl) then
error('second argument must be a type declaration', 2)
end
return NewPreRec(A.Def( name, decl._hidden_decl ))
end
function Exports.ConstOf(name, val)
if not is_id_str(name) then
error('first argument must be a variable name', 2)
end
if not is_uint(val) then
error('second argument must be a uint', 2)
end
return NewPreRec(A.Const( name, val ))
end
function Exports.ChunkOf(name, numerator, denominator)
if not is_id_str(name) then
error('first argument must be a variable name', 2) end
if not is_id_str(numerator) then
error('second argument must be a variable name', 2) end
if not is_id_str(denominator) then
error('third argument must be a variable name', 2) end
return NewPreRec(A.Chunk( name, numerator, denominator ))
end
function Exports.StructOf(...)
local entries = newlist()
for i=1,select('#',...) do
local rec = select(i,...)
if not is_pre_rec(rec) then
error('argument #'..i..' was not a struct entry', 2)
end
entries:insert(rec._hidden_rec)
end
return NewPreDecl(A.Struct(entries))
end
-------------------------------------------------------------------------------
-- Path Normalization
-------------------------------------------------------------------------------
local function insert_raw_name(xs, x)
xs:insert( tostring(x) )
end
function P.Path:normalized_seqs()
if self._norm_faseq then return self._norm_faseq, self._norm_aiseq end
local faseq, aiseq = newlist(), newlist()
for _,tkn in ipairs(self.tokens) do
if P.Field.check(tkn) then insert_raw_name(faseq, tkn.name)
elseif P.Index.check(tkn) then insert_raw_name(aiseq, tkn.name)
end
end
table.sort(faseq)
table.sort(aiseq)
self._norm_faseq, self._norm_aiseq = memolist(faseq), memolist(aiseq)
return self._norm_faseq, self._norm_aiseq
end
function P.Path:normalized_key() -- key for normalized seq.
if self._norm_key then return self._norm_key end
self._norm_key = memolist({ self:normalized_seqs() })
return self._norm_key
end
function P.Path:subpathof(rhs)
local fa1, ai1 = self:normalized_seqs()
local fa2, ai2 = rhs:normalized_seqs()
-- is fa1 a subseq of fa2?
--print('fa1', unpack(fa1))
--print('fa2', unpack(fa2))
local i1,i2 = 1,1
while i1 <= #fa1 and i2 <= #fa2 do
if fa1[i1] == fa2[i2] then i1 = i1 + 1 end
i2 = i2 + 1
end
--print('','decide', i1,i2, not(i1 <= #fa1))
if i1 <= #fa1 then return false end
-- and is ai1 a subseq of ai2
--i1,i2 = 1,1
--while i1 <= #ai1 and i2 <= #ai2 do
-- if ai1[i1] == ai2[i2] then i1 = i1 + 1 end
-- i2 = i2 + 1
--end
--if i1 <= #ai1 then return false end
return true
end
local function incr_set_count(set,key)
local val = set[key] or 0
set[key] = val + 1
end
function P.Path:normalized_sets()
if self._fa_norm_set then return self._fa_norm_set, self._ai_norm_set end
local faset, aiset = {}, {}
for _,tkn in ipairs(self.tokens) do
if P.Field.check(tkn) then incr_set_count(faset, tkn.name)
elseif P.Index.check(tkn) then incr_set_count(aiset, tkn.name) end
end
self._fa_norm_set, self._ai_norm_set = faset, aiset
return faset, aiset
end
-------------------------------------------------------------------------------
-- Path Sets (built by the typechecking pass)
-------------------------------------------------------------------------------
-- holds PathSet objects keyed on A.Decl objects
local allpaths_weak_cache = setmetatable({},{__mode = "k"})
local varpaths_weak_cache = setmetatable({},{__mode = "k"})
local PathSet = {}
PathSet.__index = PathSet
local function newPathSet()
return setmetatable({ paths={} },PathSet)
end
function PathSet:prepend(token)
local set = newPathSet()
for path,_ in pairs(self.paths) do
local newpath = P.Path( newlist{ token, unpack(path.tokens) },
path.terminal )
set.paths[newpath] = true
end
return set
end
function PathSet:addpath(sym, terminal)
local tkns = sym and newlist{ P.Field(sym) } or newlist()
self.paths[P.Path(tkns, terminal)] = true
end
function PathSet:addpaths(set)
for path,_ in pairs(set.paths) do self.paths[path] = true end
end
function PathSet:is_ambiguous()
-- this could be substantially more efficient...
for p1,_ in pairs(self.paths) do
for p2,_ in pairs(self.paths) do
if p1 ~= p2 and p1:subpathof(p2) then
return true, "The path "..tostring(p1).." is a sub-path of "..
tostring(p2)..", meaning that if the paths are "..
"re-ordered, then there could be an ambiguity "..
"about whether data or a sub-structure is being "..
"referred to."
end
end
end
return false
end
-------------------------------------------------------------------------------
-- Logical Sub-Typing of Decls
-------------------------------------------------------------------------------
-- returns a set keyed by normalized path-sequence objects
local weak_norm_path_cache = setmetatable({},{__mode = "k"})
local function normalized_paths(decl)
--function A.Decl:normalized_paths()
if weak_norm_path_cache[decl] then return weak_norm_path_cache[decl] end
local nkp = {}
for path,_ in pairs(allpaths_weak_cache[decl].paths) do
local normkey = path:normalized_key()
nkp[normkey] = path
end
weak_norm_path_cache[decl] = nkp
return nkp
end
local prim_supertype_table = {
[ A.SIZE ] = A.SIZE,
[ A.UINT ] = A.UINT,
[ A.INT ] = A.INT,
[ A.BOOL ] = A.BOOL,
[ A.FLOAT ] = A.FLOAT,
[ A.SIZE8 ] = A.SIZE,
[ A.SIZE16 ] = A.SIZE,
[ A.SIZE32 ] = A.SIZE,
[ A.SIZE64 ] = A.SIZE,
[ A.UINT8 ] = A.UINT,
[ A.UINT16 ] = A.UINT,
[ A.UINT32 ] = A.UINT,
[ A.UINT64 ] = A.UINT,
[ A.INT8 ] = A.INT,
[ A.INT16 ] = A.INT,
[ A.INT32 ] = A.INT,
[ A.INT64 ] = A.INT,
[ A.FLOAT32] = A.FLOAT,
[ A.FLOAT64] = A.FLOAT,
}
local function prim_subtype(lhp, rhp)
return lhp == rhp -- simple case
or prim_supertype_table[lhp] == rhp
or (rhp == A.BOOL and prim_supertype_table[lhp] == A.UINT)
end
local function terminal_subtype(lpath, rpath)
local lht, rht = lpath.terminal, rpath.terminal
local lnum = type(lht) == 'number' and lht
local rnum = type(rht) == 'number' and rht
if lnum then
if rnum then return lnum == rnum end
-- otherwise, does this number fit in the specified bits?
local bd = size_num_bound_table[rht]
return bd and lnum < bd
else
if rnum then return false end
return prim_subtype(lht, rht)
end
end
function A.Decl:logical_subtype_of(rhdecl)
local lhdecl = self
-- true if the set of normalized paths on the right is a subset of
-- the normalized paths on the left.
-- WITH the added caveat that the terminals must be subtypes
local lNP = normalized_paths(lhdecl)
local rNP = normalized_paths(rhdecl)
for k,rpath in pairs(rNP) do
local lpath = lNP[k]
if not lpath or not terminal_subtype(lpath, rpath) then return false end
end
return true
end
function A.Decl:logical_equal_of(rhdecl)
local lhdecl = self
-- true if the set of normalized paths on the right is the same as
-- the normalized paths on the left.
-- WITH the added caveat that the terminals must match exactly
local lNP = normalized_paths(lhdecl)
local rNP = normalized_paths(rhdecl)
for k,lpath in pairs(lNP) do -- check inclusion one way
if not rNP[k] then return false end
end
for k,rpath in pairs(rNP) do -- check inclusion and prim match the other
local lpath = lNP[k]
if not lpath or lpath.terminal ~= rpath.terminal then return false end
end
return true
end
-------------------------------------------------------------------------------
-- Typechecking
-------------------------------------------------------------------------------
-- Typechecking ensures that names don't alias improperly, are in scope,
-- and are well-defined.
-- Typechecking also extracts useful information in the form of paths.
local TypingContext = {}
TypingContext.__index = TypingContext
local function new_typing_context()
return setmetatable({
_env = terralib.newenvironment(),
_var_defs = {},
_diag = terralib.newdiagnostics(),
}, TypingContext)
end
function TypingContext:env() return self._env:localenv() end
function TypingContext:pushscope() self._env:enterblock() end
function TypingContext:popscope() self._env:leaveblock() end
function TypingContext:error(node, ...)
self._diag:reporterror(node, ...)
end
function TypingContext:begin()
end
function TypingContext:finish(decl,depth)
depth = depth or 1
if self._diag:haserrors() and decl.filename == 'no_src' then
print('This Layout had typing errors')
print(decl)
end
self._diag:finishandabortiferrors(
"Errors found in plop definition", depth+1)
end
local typechecking_pass
local max_int32_val = math.pow(2,31)-1
--function A.Array:typecheck(ctxt)
local function typechecking_array(self, ctxt)
-- determine type and or const value
if self.sizeval then -- had a constant annotation
-- append an identifier distinguishing successive array lookups
local lookup = ctxt:env()[self.sizeval]
lookup = lookup and (lookup+1) or 0
self.sizevar = tostring(self.sizeval)..'_'..lookup
ctxt:env()[self.sizeval] = lookup
self.sizetype = (self.sizeval < max_int32_val) and A.SIZE32 or A.SIZE64
else
local symname = tostring(self.sizevar)
local lookup = ctxt:env()[symname]
if not lookup or lookup.errtyp then
if lookup and lookup.errtyp then
ctxt:error(self,"tried to use variable '"..tostring(self.sizevar)..
"', which has type "..tostring(lookup.errtyp)..
". Did you mean to give it size type?")
else
ctxt:error(self,"variable '"..tostring(self.sizevar)..
"' used here was undefined.")
end
else
self.sizevar = lookup.sym
self.sizeval = lookup.val -- one of these will be nil
self.sizetype = lookup.typ -- one of these will be nil
self.size_num = lookup.numerator
self.size_denom = lookup.denominator
end
end
local vars, paths = typechecking_pass( self.typ, ctxt )
return vars:prepend(P.Index(self.sizevar)),
paths:prepend(P.Index(self.sizevar))
end
--function A.Struct:typecheck(ctxt)
local function typechecking_struct(self, ctxt)
local varpaths, allpaths = newPathSet(), newPathSet()
ctxt:pushscope()
self._lookup_fields = {}
local function addlookup(name,idx,rec)
if self._lookup_fields[name] then
ctxt:error(rec,"cannot have two entries with the same name: '"..
name.."'") end
self._lookup_fields[name] = idx
end
for i_rec,rec in ipairs(self.entries) do
local namestr = tostring(rec.name)
if is_const(rec) then
if namestr == '_' then
ctxt:error(self,"cannot assign a constant value to "..
"the special no-name character '_'")
end
addlookup(namestr, i_rec, rec)
ctxt:env()[namestr] = { sym=rec.name, val=rec.val }
--local size_typ = size_bound_of_num(rec.val)
allpaths:addpath(rec.name, rec.val)
elseif is_chunk(rec) then
if namestr == '_' then
ctxt:error(self,"cannot assign a chunked value to "..
"the special no-name character '_'")
end
local env = ctxt:env()
local num, denom = rec.numerator, rec.denominator
local numrec, denomrec = env[num], env[denom]
if not denomrec or not denomrec.val then
ctxt:error(self,"denominator in chunked expression must be "..
"a constant variable") end
if not numrec or not numrec.typ then
ctxt:error(self,"numerator in chunked expression must be "..
"a size variable")
else
addlookup(namestr, i_rec, rec)
env[namestr] = { sym=rec.name, typ = numrec.typ,
numerator=num, denominator=denomrec.val }
allpaths:addpath(rec.name, numrec.typ)
end
else -- A.Def
if is_dprim(rec.typ) then
-- add all variables to the allpaths; only size variables
-- to the variable store
if namestr ~= '_' then
addlookup(namestr, i_rec, rec)
allpaths:addpath(rec.name, rec.typ.prim)
end
if is_size_prim(rec.typ.prim) then
ctxt:env()[namestr] = { sym=rec.name, typ=rec.typ.prim }
varpaths:addpath(rec.name, rec.typ.prim)
else
ctxt:env()[namestr] = { errtyp=rec.typ.prim }
end
else
local vars, paths = typechecking_pass(rec.typ, ctxt)
if namestr ~= '_' then
addlookup(namestr, i_rec, rec)
allpaths:addpaths( paths:prepend(P.Field(rec.name)) )
end
varpaths:addpaths( vars:prepend(P.Field(rec.name)) )
end
end
end
ctxt:popscope()
return varpaths, allpaths
end
function typechecking_pass(decl, ctxt)
local varpaths, allpaths
if is_dprim(decl) then
varpaths = newPathSet()
allpaths = newPathSet()
allpaths:addpath(nil,decl.prim)
elseif is_ptr(decl) then
local vars, paths = typechecking_pass(decl.typ, ctxt)
allpaths = paths:prepend(P.DeRef)
varpaths = vars:prepend(P.DeRef)
elseif is_array(decl) then
varpaths, allpaths = typechecking_array(decl, ctxt)
else --is_struct(decl) then
varpaths, allpaths = typechecking_struct(decl, ctxt)
end
varpaths_weak_cache[decl] = varpaths
allpaths_weak_cache[decl] = allpaths
return varpaths, allpaths
end
local function typecheck_decl(decl)
local ctxt = new_typing_context()
ctxt:begin()
typechecking_pass(decl,ctxt) --decl:typecheck(ctxt)
ctxt:finish(decl,3)
local is_err, errmsg = allpaths_weak_cache[decl]:is_ambiguous()
if is_err then
error('This plop definition contains ambiguous paths\n'..errmsg, 3)
end
return decl
end
function A.Struct:find_entry(name)
return self._lookup_fields[name]
end
-------------------------------------------------------------------------------
-- Logical vs. Physical Layouts
-------------------------------------------------------------------------------
do
-- lattice values (logical, physical, top, bottom)
local L,P, T,B = {},{},{},{}
local lp_meet = {
[T]={ [T] = T, [L] = L, [P] = P, [B] = B },
[L]={ [T] = L, [L] = L, [P] = B, [B] = B },
[P]={ [T] = P, [L] = B, [P] = P, [B] = B },
[B]={ [T] = B, [L] = B, [P] = B, [B] = B },
}
local lp_weak_cache = setmetatable({},{__mode = "k"})
local function lp_analysis(decl)
if lp_weak_cache[decl] then return lp_weak_cache[decl] end
local lp = T
if is_dprim(decl) then
lp = physical_prim_table[decl.prim] and T or L
elseif is_array(decl) then
lp = lp_analysis(decl.typ)
elseif is_struct(decl) then