-
Notifications
You must be signed in to change notification settings - Fork 26
/
Lust.lua
1403 lines (1189 loc) · 31.8 KB
/
Lust.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
--[[
Given a template, generate a generator.
MIT license.
--]]
local concat = table.concat
local format = string.format
-- util:
local
function tree_dump_helper(t, p, strlimit, ignorekeys)
if type(t) == "table" then
local terms = { "{" }
local p1 = p .. " "
for k, v in pairs(t) do
if not ignorekeys[k] then
local key
if type(k) == "number" then
key = tostring(k)
else
key = format("%q", k)
end
terms[#terms+1] = format("[%s] = %s,", key, tree_dump_helper(v, p1, strlimit-2, ignorekeys))
end
end
return format("%s\n%s}", concat(terms, "\n"..p1), p)
elseif type(t) == "number" then
return tostring(t)
elseif type(t) == "string" and #t > strlimit then
return format("%q...", t:sub(1, strlimit))
else
return format("%q", t)
end
end
local
function tree_dump(t, strlimit, ignorekeys)
print(tree_dump_helper(t, "", strlimit and strlimit or 80, ignorekeys or {}))
end
local
function qesc(str)
local len = str:len()
if(str:sub(1, 1) == '"' and str:sub(len, len) == '"') then
local s = str:sub(2, len-1)
if(s:sub(1, 1) == "\n") then
s = "\n"..s
end
return format("[===[%s]===]", s)
else
return str
end
end
local
function printlines(s, from, to)
from = from or 0
to = to or 100000000
local l = 1
for w in s:gmatch("(.-)\r?\n") do
if l >= from and l <= to then print(l, w) end
l = l + 1
end
end
local gensym = (function()
local id = 0
return function(s)
id = id + 1
local pre = s or "v"
return format("%s%d", pre, id)
end
end)()
--------------------------------------------------------------------------------
-- Code accumulator (like a rope)
--------------------------------------------------------------------------------
local writer = {}
writer.__index = writer
function writer.create(prefix, indent)
local s = {
level = 0,
prefix = prefix or "",
indent = indent or " ",
stack = {},
}
s.current = s
return setmetatable(s, writer)
end
function writer:write(s)
self.current[#self.current+1] = s
return self
end
writer.__call = writer.write
function writer:format(s, ...)
self.current[#self.current+1] = format(s, ...)
return self
end
function writer:comment(s, ...)
self.current[#self.current+1] = "-- " .. format(s, ...)
return self
end
-- indentation:
function writer:push()
local w1 = writer.create(self.indent)
self.current[#self.current+1] = w1
self.stack[#self.stack+1] = self.current
self.current = w1
return self
end
function writer:pop()
if #self.stack > 0 then
self.current = self.stack[#self.stack]
self.stack[#self.stack] = nil
else
error("too many pops")
end
return self
end
function writer:concat(sep)
sep = sep or ""
sep = sep .. self.prefix
for i = 1, #self do
local v = self[i]
if type(v) == "table" then
if v.concat then
self[i] = v:concat(sep)
else
self[i] = concat(v, sep)
end
end
end
return self.prefix .. concat(self, sep)
end
--------------------------------------------------------------------------------
-- Template definition grammar
--------------------------------------------------------------------------------
local lpeg = require "lpeg"
local P = lpeg.P
local C = lpeg.C
local Carg = lpeg.Carg
local Cc = lpeg.Cc
local Cg = lpeg.Cg
local Ct = lpeg.Ct
local Cp = lpeg.Cp
local V = lpeg.V
-- utils:
local
function left_binop(x, pos1, op, y, pos2, ...)
--print("left_binop", op, x, y, ...)
return op and left_binop({x, y, rule="binop", op=op, start=pos1, finish=pos2 }, pos1, ...) or x
end
local
function left_unop(start, op, x, finish, chained, ...)
if finish then
if chained then
x = left_unop(x, finish, chained, ...)
finish = x.finish
end
return {
x,
rule="unop",
op=op,
start=start,
finish=finish
}
else
return start
end
end
local function delimited(patt)
return patt * C((1-patt)^0) * patt
end
-- basic patterns:
-- numerics:
local digit = lpeg.R("09")
local integer = digit^1
local quoted_integer = P'"' * C(integer) * P'"'
local newline = lpeg.S"\n\r"
-- optional white space:
local space = lpeg.S" \t"
local _ = space^0
-- pure alphabetic words:
local alpha = lpeg.R"az" + lpeg.R"AZ"
local symbol = alpha * (alpha)^0
local literal = delimited(P"'") + delimited(P'"')
-- typical C-like variable names:
local name = (alpha + P"_") * (alpha + integer + P"_")^0
-- the patten to pick up the global state:
local g = Carg(1)
-- General rule constructors:
local function Rule(patt, name)
return Ct(
Cg(Cp(), "start") *
patt *
Cg(Cp(), "finish") *
Cg(Cc(name), "rule")
)
end
-- constructors for left-recursive operator rules:
-- O is the operator, B is the next pattern to try
function BinRule(O, B)
-- matches B
-- matches B op B
-- matches B op B op B etc.
return (B * Cp() * (_ * O *_* B * Cp())^0) / left_binop
end
-- O is the operator, B is the next pattern to try
function UnRule(O, B)
-- matches op B
-- matches op op B
-- else matches B
return (((Cp() * O * _)^1 * B * Cp()) / left_unop) + B
end
-- the grammar:
local grammar = P{
-- start symbol (grammar entry point):
Rule(V"firstinsert"^-1 * (V"insert" + V"anything")^0, "main"),
-- anything that isn't an insertion point:
anything = Rule(
C((P(1) - V"insert")^1),
"anything"
),
-- all the insertion points are wrapped in an indentation detector:
indent = Cg(C(space^1), "indent"),
-- special rule if an insertion appears before an 'anything' rule
-- because the initial newline anchor is not needed
-- and the generated code will also omit this newline
firstinsert = Rule(
(Cg(Cc"true", "first") * V"indent")^-1 *
V"insertbody",
"insert"
),
-- subsequent insertions must be anchored by a newline for indent to work:
insert = Rule(
(newline * V"indent")^-1 *
V"insertbody",
"insert"
),
insertbody = Rule(
P"@if" * V"cond",
"cond"
)
+ Rule(
P"@iter" * V"iter_env" * P":" * V"iter_body",
"iter"
)
+ Rule(
P"@" * (C"map" + C"rest" + C"first" + C"last") *
(V"env_dict" + V"env") * P":" * V"iter_body",
"map"
)
+ Rule(
(
(P"@<" * V"apply_body" * P">")
+ (P"@" * V"apply_body")
),
"apply"
)
+ Rule(
(
(P"$<" * V"index" * P">")
+ (P"$" * V"index")
),
"substitute"
),
-- main applications:
apply_env_nil = V"path_nil",
apply_env = (V"env" * P":")
+ (V"path" * P":"),
-- dynamic template path:
-- e.g. a.(b.c).d
apply_eval_term = V"eval"
+ C(name),
apply_eval_path = Rule(
C"#"^-1 * V"apply_eval_term" * (P"." * V"apply_eval_term")^0,
"apply_eval_path"
),
apply_body_env = Rule(V"apply_env" * V"apply_eval_path", "apply_eval")
+ Rule(V"apply_env" * V"inline", "apply_inline"),
apply_body_no_env = Rule(V"apply_env_nil" * V"apply_eval_path", "apply_eval")
+ Rule(V"apply_env_nil" * V"inline", "apply_inline"),
apply_body = V"apply_body_env"
+ V"apply_body_no_env",
iter_range_term = Rule(quoted_integer, "quoted")
+ Rule(V"path", "len"),
iter_range = Rule(
P"[" *_* V"iter_range_term"
*_* "," *_* V"iter_range_term" *_* P"]",
"iter_range"
)
+ V"iter_range_term",
iter_env = Rule(
P"{" *_* V"iter_range" *_*
(P"," *_* V"env_separator")^-1
*_* P"}",
"iter_env"
),
iter_body = Rule(V"apply_eval_path", "iter_eval")
+ Rule(V"inline", "iter_inline"),
cond = P"(" * V"cmp7" * P")<" * V"apply_body_no_env" * P">"
* (P"else<" * V"apply_body_no_env" * P">")^-1,
-- environment indexing:
path_term = V"eval"
+ C(name)
+ (integer / tonumber),
path_nil = Rule(
Cc".",
"path_nil"
),
path_current = Rule(
C".",
"path_current"
),
path = V"path_current"
+ Rule(
V"path_term" * (P"." * V"path_term")^0,
"path"
),
index = Rule(P"#" * V"path", "len")
+ V"path",
-- environments:
env_term_value = V"apply_body_env"
+ V"env"
+ V"env_array"
+ Rule(literal, "literal")
+ V"index",
env_separator = Rule(
((P"_separator" + P"_") *_* P"=" *_* V"env_term_value"),
"separator"
),
env_tuple = V"env_separator"
+ Rule(
C(name) *_* P"=" *_* V"env_term_value",
"tuple"
),
env_term = V"env_tuple" + V"env_term_value",
env_term_list = (V"env_term" * (_ * P"," *_* V"env_term")^0 *_* P","^-1),
env_array = Rule(
P"[" *_* V"env_term_list" *_* P"]",
"env_array"
),
env = Rule(
P"{" *_* V"env_term_list" *_* P"}",
"env"
),
-- like env, but only allows tuples:
env_tuple_list = (V"env_tuple" * (_ * P"," *_* V"env_tuple")^0 *_* P","^-1),
env_dict = Rule(
P"{" *_* V"env_tuple_list" *_* P"}",
"env_dict"
),
-- application bodies:
eval = P"(" * V"path" * P")",
inline_term = V"insert"
+ Rule(C((P(1) - (P"}}" + V"insert"))^1), "inline_text"),
inline = P"{{"
* Rule(
V"inline_term"^0,
"inline"
)
* P"}}",
-- conditionals:
cmp0 = Rule(P"?(" *_* V"path" *_* P")", "exists")
+ Rule(V"eval", "lookup")
+ Rule(quoted_integer, "quoted")
+ Rule(C(literal), "quoted")
+ V"index",
cmp1 = UnRule(
C"^",
V"cmp0"
),
cmp2 = Rule( -- legacy length{x} operator:
Cg(Cc"#", "op") * P"length{" *_* V"cmp0" *_* P"}",
"unop"
)
+ UnRule(
C"not" + C"#" + C"-",
V"cmp1"
),
cmp3 = BinRule(
C"*" + C"/" + C"%",
V"cmp2"
),
cmp4 = BinRule(
C"+" + C"-",
V"cmp3"
),
cmp5 = BinRule(
C"==" + C"~=" + C"!=" + C">=" + C"<=" + C"<" + C">",
V"cmp4"
),
cmp6 = BinRule(
C"and",
V"cmp5"
),
cmp7 = BinRule(
C"or",
V"cmp6"
),
}
--------------------------------------------------------------------------------
-- Generator generator
--------------------------------------------------------------------------------
-- a table to store the semantic actions for the grammar
-- i.e. the routines to generate the code generator code
local action = {}
-- NOTE: the 'self' argument to these actions is not an 'action', but
-- actually a 'gen' object, as defined below.
-- all actions take two arguments:
-- @node: the parse tree node to evaluate
-- @out: an array of strings to append to
function action:main(node, out)
out("local out = {}")
for i, v in ipairs(node) do
out( self:dispatch(v, out) )
end
out("local result = concat(out)")
out("return result")
end
function action:anything(node, out)
return format("out[#out+1] = %q", node[1])
end
function action:insert(node, out)
local indent = node.indent
-- write the first line indentation:
if indent and indent ~= "" then
-- generate the body:
out:comment("rule insert (child)")
out:write("local indented = {}")
out:write("do"):push()
out:comment("accumulate locally into indented:")
out:write("local out = indented")
-- everything in this dispatch should be indented:
out:write(self:dispatch(node[1], out))
out:pop():write("end")
-- mix sub back into parent:
out:comment("apply insert indentation:")
if not node.first then
out:write("out[#out+1] = newline")
end
out:format("out[#out+1] = %q", indent)
out:format("out[#out+1] = concat(indented):gsub('\\n', %q)", '\n' .. indent)
else
out:write(self:dispatch(node[1], out))
end
end
function action:path(node, out)
-- TODO: check if this has already been indexed in this scope
local name = gensym(env) --"env_"..concat(node, "_")
local env = "env"
local vname = "''"
local nterms = #node
for i = 1, nterms do
local v = node[i]
local term
if type(v) == "table" then
local value = self:dispatch(v, out)
term = format("%s[%s]", env, value)
--out:format("print('value', %s, %s)", value, term)
vname = gensym("env")
else
if type(v) == "number" then
term = format("%s[%d]", env, v)
elseif type(v) == "string" then
term = format("%s[%q]", env, v)
else
error("bad path")
end
vname = format("%s_%s", env, v)
end
out:format("local %s = (type(%s) == 'table') and %s or nil", vname, env, term)
env = vname
end
return vname
end
function action:separator(node, out)
return node[1]
end
function action:len(node, out)
local path = self:dispatch(node[1], out)
return format("len(%s)", path)
end
function action:path_current(node, out)
return "env"
end
function action:path_nil(node, out)
return action.path_current(self, node, out)
end
function action:substitute(node, out)
local content = assert(node[1])
local text = self:dispatch(content, out)
return format("out[#out+1] = %s", text)
end
function action:apply(node, out)
local text = self:dispatch(node[1], out)
if text then
return format("out[#out+1] = %s", text)
end
end
function action:loop_helper(body, out, it, start, len, terms, mt, sep, parent)
local insep = sep
-- start loop:
out:format("for %s = %s, %s do", it, start, len)
:push()
-- the dynamic env:
out("local env = setmetatable({")
:push()
:format("i1 = %s,", it)
:format("i0 = %s - 1,", it)
if terms then
for i, v in ipairs(terms) do
-- TODO: only index if type is table!
out(v)
end
end
out:pop()
:format("}, %s)", mt)
if parent then
out:format([[if(type(parent[%s]) == "table") then]], it)
:push()
:format("for k, v in pairs(parent[%s]) do", it)
:push()
:write("env[k] = v")
:pop()
:write("end")
:pop()
:write("else")
:push()
:format("env[1] = parent[%s]", it)
:pop()
:write("end")
end
-- the body:
local result = self:dispatch(body, out)
out:format("out[#out+1] = %s", result)
-- the separator:
if insep then
out:comment("separator:")
out:format("if %s < %s then", it, len)
:push()
:format("out[#out+1] = %s", qesc(insep))
:pop()
:write("end")
end
-- end of loop:
out:pop()
:write("end")
return ""
end
function action:iter(node, out)
local env, body = node[1], node[2]
local sep
local start = "1"
local len
assert(env.rule == "iter_env", "malformed iter env")
local range = assert(env[1], "missing iter range")
local v = env[2] -- optional
if v then
assert(v.rule == "separator", "second @iter term must be a separator")
sep = self:dispatch(v[1], out)
end
--out:comment("range " .. range.rule)
if range.rule == "iter_range" then
-- explicit range
if #range > 1 then
start = gensym("s")
out:format("local %s = %s", start, self:dispatch(range[1], out))
len = gensym("len")
out:format("local %s = %s", len, self:dispatch(range[2], out))
else
len = gensym("len")
out:format("local %s = %s", len, self:dispatch(range[1], out))
end
else
len = gensym("len")
out:format("local %s = %s", len, self:dispatch(range, out))
end
local it = gensym("it")
-- an environment to inherit:
local mt = gensym("mt")
out:format("local %s = { __index=env }", mt)
return action.loop_helper(self, body, out, it, start, len, terms, mt, sep)
end
function action:map(node, out)
--tree_dump(node)
local ty, env, body = node[1], node[2], node[3]
-- loop boundaries:
local it = gensym("it")
local start
local len = gensym("len")
-- loop separator:
local sep
-- loop environment terms:
local terms = {}
local parent
local idx = 1
out:comment("%s over %s", ty, env.rule)
-- the environment to inherit:
local mt
if env.rule == "env_dict" then
-- tuple-only iterator
-- each tuple value is indexed during iteration
-- len will be derived according to max length of each item
-- default zero is needed
out:format("local %s = 0", len)
for i, v in ipairs(env) do
-- detect & lift out separator:
if v.rule == "separator" then
sep = self:dispatch(v[1], out)
break
end
-- parse each item:
local k, s
if v.rule == "tuple" then
k = format("%q", self:dispatch(v[1], out))
v = v[2]
else
k = idx
idx = idx + 1
end
s = self:dispatch(v, out)
if v.rule == "literal"
or v.rule == "len"
or v.rule == "apply_template" then
-- these rules only return strings:
terms[i] = format("[%s] = %s,", k, s)
elseif v.rule == "env_array" then
-- these rules only return arrays:
terms[i] = format("[%s] = %s[%s] or '',", k, s, it)
out:format("%s = max(len(%s), %s)", len, s, len)
else
-- these rules might be strings or tables, need to index safely:
local b = gensym("b")
out:format("local %s = type(%s) == 'table'", b, s)
out:format("if %s then", b):push()
out:format("%s = max(len(%s), %s)", len, s, len)
out:pop()
out("end")
--out:format("print('loop', '%s', %s)", len, len)
terms[i] = format("[%s] = %s and (%s[%s] or '') or %s,", k, b, s, it, s)
end
end
-- but meta-environment is always the same:
mt = gensym("mt")
out:format("local %s = { __index=env }", mt)
elseif env.rule == "env" then
-- list iterator
assert(#env > 0, "missing item to iterate")
-- only the first array item is iterated
for i, v in ipairs(env) do
if v.rule == "separator" then
sep = self:dispatch(v[1], out)
break
elseif v.rule == "tuple" then
-- copy evaluted dict items into the env:
local k = format("%q", self:dispatch(v[1], out))
local s = self:dispatch(v[2], out)
terms[#terms+1] = format("[%s] = %s,", k, s)
else
-- the array portion is copied in element by element:
local s = self:dispatch(v, out)
out:format("local parent = %s", s)
:format("local %s = (type(parent) == 'table') and #parent or 0", len, s, s)
mt = "getmetatable(parent)"
parent = true
end
end
else
error("malformed map env")
end
if ty == "rest" then
start = "2"
elseif ty == "first" then
start = "1"
len = string.format("math.min(1, %s)", len)
elseif ty == "last" then
start = len
else -- map
start = "1"
end
return action.loop_helper(self, body, out, it, start, len, terms, mt, sep, parent)
end
function action:apply_helper(tmp, env, out)
out:comment("apply helper")
local name = gensym("apply")
out:format("local %s = ''", name)
out:format("if %s then", tmp)
:push()
out:format("%s = %s(%s)", name, tmp, env)
out:pop()
:write("end")
return name
end
function action:apply_template(node, out)
local env = self:dispatch(node[1], out)
return action.apply_template_helper(self, node[2], env, out)
end
function action:iter_template(node, out)
return action.apply_template_helper(self, node[1], "env", out)
end
function action:lookup_helper(rule, out)
local ctx = self.ctx
local ctxlen = #ctx
-- construct the candidate rules:
local candidates = {}
for i = ctxlen, 1, -1 do
candidates[#candidates+1] = format("rules[%q .. %s]", concat(ctx, ".", 1, i) .. ".", rule)
end
candidates[#candidates+1] = format("rules[%s]", rule)
local tmp = gensym("tmp")
out:format("local %s = %s", tmp, concat(candidates, " or "))
--[==[
out:format([[if(tem__ == 'unit.self.coordinates.norm') then
print("rule", %s)
end
]], tmp)
--]==]
return tmp
end
function action:lookup(node, out)
local rule = action.path(self, node[1], out)
return action.lookup_helper(self, rule, out)
end
function action:apply_template_helper(body, env, out)
out:comment("template application:")
local rule = self:dispatch(body, out)
return action.apply_helper(self, rule, env, out)
end
-- OK too much special casing here
-- also, #rooted paths are not being handed for the dynamic case
function action:apply_eval_path(node, out)
local terms = {}
local sterms = {}
local isdynamic = false
local isabsolute = false
for i, v in ipairs(node) do
if v == "#" then
isabsolute = true
else
if type(v) ~= "string" then
-- instead, we could break here and just
-- return tailcall to the dynamic method
isdynamic = true
local term = self:dispatch(v, out)
terms[#terms+1] = term
else
local term = v
sterms[#sterms+1] = term
terms[#terms+1] = format("%q", term)
end
end
end
if isdynamic then
out:comment("dynamic application")
local evaluated = concat(terms, ", ")
--out:format([[print("dynamic path", %s)]], evaluated)
local rule = gensym("rule")
out:format([[local %s = concat({%s}, ".")]], rule, evaluated)
--[==[
out:format([[
if(tem__ == 'unit.self.coordinates.norm') then
print("%s", %s)
end
]], rule, rule)
--]==]
return action.lookup_helper(self, rule, out)
else
out:comment("static application")
-- absolute or relative?
local ctx = self.ctx
local ctxlen = #ctx
local pathname = concat(sterms, ".")
--print("pathname", pathname)
if isabsolute or ctxlen == 0 then
-- we are at root level, just use the absolute version:
return self:reify(pathname)
end
-- this is the template name we are looking for:
--print("looking for", pathname)
--print("in context", unpack(self.ctx))
-- we are in a sub-namepsace context
-- keep trying options by moving up the namespace:
local ok, rulename
for i = ctxlen, 1, -1 do
-- generate a candidate template name
-- by prepending segments of the current namepace:
local candidate = format("%s.%s", concat(ctx, ".", 1, i), pathname)
ok, rulename = pcall(self.reify, self, candidate)
if ok then
-- found a match, break here:
return rulename
end
end
-- try at the root level:
local ok, rulename = pcall(self.reify, self, pathname)
if ok then
-- found a match!
return rulename
end
-- if we got here, we didn't find a match:
-- should this really be an error, or just return a null template?
for k, v in pairs(self.definitions) do print("defined", k) end
error(format("could not resolve template %s (%s) in context %s",
pathname, rulename, concat(ctx, ".")
))
end
end
-- env, apply_eval
-- apply_eval e.g. a.(x).c
function action:apply_eval(node, out)
local env = self:dispatch(node[1], out)
local tmp = self:dispatch(node[2], out)
return action.apply_helper(self, tmp, env, out)
end
function action:iter_eval(node, out)
local env = "env"
local tmp = self:dispatch(node[1], out)
return action.apply_helper(self, tmp, env, out)
end
function action:apply_inline_helper(body, env, out)
local name = gensym("apply")
out:comment("inline application:")
out:format("local %s", name)
:write("--- test")
:write("do")
:push()
:format("local env = %s", env)
:write("local out = {}")
local rule = self:dispatch(body, out)
out:format("%s = concat(out)", name)
:pop()
:write("end")
return name
end
function action:apply_inline(node, out)
local env = self:dispatch(node[1], out)
return action.apply_inline_helper(self, node[2], env, out)
end
function action:iter_inline(node, out)
return action.apply_inline_helper(self, node[1], "env", out)
end
function action:cond(node, out)
local c = self:dispatch(node[1], out)
--[==[
if(c == "env_formatted") then
out:write("local tem__ = (type(env) == 'table') and env.template")
out:write([[if(tem__ == 'unit.self.coordinates.norm') then
print('THIS IS A unit.self.coordinates.norm')
print("env_formatted", env_formatted)
print("TEMPLATE:", env["template"])
end]])
end
--]==]
out:format("if %s then", c):push()
local t = self:dispatch(node[2], out)
if t then
out:format("out[#out+1] = %s", t)