-
Notifications
You must be signed in to change notification settings - Fork 1
/
macro_require.lua
2135 lines (1927 loc) · 68.1 KB
/
macro_require.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
tokenizer=require 'simple_tokenizer'
--comment out to have debugging autostart
started_debugging=true
if not started_debugging then
started_debugging = true
require('mobdebug').start()
end
--local serpent = require("serpent")
--require 'class'
--forward references
local strip_tokens_from_list,apply_macros,add_macro,nullp,cdr,car,cadr,cddr,caddr,cdddr,macros,validate_params
local optional_read_match_to,read_match_to,read_match_to_no_commas,sublist_to_list,concat_cons,scan_head_forward,add_token_keys,nthcar
local my_err,cons,list_to_array,copy_list, copy_list_and_object,simple_copy,render,output_render, last_cell,reverse_list_in_place,reverse_list,cons_tostring,Nil,list_append_in_place,process,list_to_stripped_array,add_tokens
local token_metatable = {__tostring=
function(self)
if self.token and self.macro_token~=self.token.value then
if self.type == 'String' then return self.token.value end
return self.token.value .. '-as-' .. self.macro_token
end
return self.macro_token
end
}
local filename2sections = {}
local function insure_subtable_exists(original_table,field)
if not original_table[field] then original_table[field]={} end
end
-- table_path_get(t,'a','b','c') is t.a.b.c returning nil if any level does not exist
local function table_path_get(r, ...)
local len=select('#',...)
for i = 1, len do
if not r then return nil end
local selector=select(i,...)
r=r[selector]
end
return r
end
codemap = {}
local function fill_codemap(filename, tokens,m)
filename='@'..filename
insure_subtable_exists(codemap,filename)
local t=tokens
local ti=1
local di=1
local cmap=codemap[filename]
while not nullp(t) do
local token = car(t)
if token.token and token.token.from_line then
di=(token.token.from_line+1)*m
end
while #cmap<ti do table.insert(cmap,di) end
-- cmap[ti]=di
if cmap[ti]<di then cmap[ti]=di end
ti=ti+1
t=cdr(t)
end
end
local function my_loadstring(string, filename,tokens,output_string)
output_string=output_string or string
fill_codemap(filename,tokens,1)
if not filename then filename = 'macro_temp.lua' end
local output_filename = filename .. '.temp.lua'
local file=io.open(output_filename,"w")
-- file:write('return((')
file:write(output_string ) --output_render(tokens))
-- file:write(')())')
file:close()
local function my_hander(err)
print('in handler '..tostring(err))
local token_number,error_text=string.match(tostring(err),":(%d+):(.*)")
if not token_number then
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
else
token_number = tonumber(token_number)
print ('error at token '..token_number.. ' error message: "'..error_text..'"')
if tokens then
my_err(nthcar( token_number,tokens), error_text)
else
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
end
end
end
local ret
local status --= xpcall(my_do,my_hander)
local function my_do(...)
local s=table.pack(pcall(status,...))
if not s[1] then my_hander(s[2]) end
table.remove(s,1)
return table.unpack(s,s.n-1)
end
if not started_debugging then
started_debugging = true
require('mobdebug').start()
end
--editor.autoactivate=true
status,ret=loadstring(string,"@"..filename)
if not status then my_hander(ret) end
-- print ('the status is "' .. tostring(status) ..'"')
return my_do
end
local function my_dostring(string, filename, tokens)
--print('my_dostring 「', string,'」')
if not filename then filename = 'macro_temp.lua' end
fill_codemap(filename,tokens,-1)
-- local file=io.open(filename,"w")
-- file:write(string)
-- file:close()
local function my_hander(err)
-- print('in handler '..tostring(err))
local token_number,error_text=string.match(tostring(err),":(%d+):(.*)")
if not token_number then
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
else
token_number = tonumber(token_number)
-- print ('error at token '..token_number.. ' error message: "'..error_text..'"')
if tokens then
my_err(nthcar(tokens, token_number), error_text)
else
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
end
end
return true
end
local ret
local function my_do()
-- ret=dofile(filename)
ret=assert(loadstring(string,'@'..filename))()
end
local status = xpcall(my_do,my_hander)
-- print ('the status is "' .. tostring(status) ..'"')
return ret
end
local function array_to_set_table(a)
if type(a)~='table' then return a end
local t={}
for _,v in ipairs(a) do
t[v]=true
end
return t
end
simple_translate = setmetatable(
{ ['[|']='function (',
['{|']='coroutine.wrap(function (',
['|']=')',
['@']='return',
['y@']='coroutine.yield',
['Y@']='coroutine.yield',
['|]']='end',
['|}']='end)',
['$#']='select("#",...)',
['$1']='select(1,...)',
['$2']='select(2,...)',
['$3']='select(3,...)',
['$4']='select(4,...)',
['$5']='select(5,...)',
['$6']='select(6,...)',
}, { __index = function(_,v) return v end })
local function pp_null_fn(lines, line_number) return line_number+1 end
local function file_path(mtoken)
return table_path_get(mtoken,'token','filename') or '¯\\_(ツ)_/¯'
end
my_err= function (mtoken,err)
local line=' '
err=err or 'error'
if not nullp(mtoken) then
if mtoken.token then
print('token '.. mtoken.macro_token .. ' filename ' .. tostring(mtoken.token.filename) .. ' line '.. tostring(mtoken.token.from_line) )
else
print('macro token '.. tostring(mtoken) )
end
end
if mtoken and mtoken.token then line= ':'..tostring(mtoken.token.from_line+1)..':'..tostring(mtoken.token.from_x+1)..':' end
io.stderr:write(file_path(mtoken).. line .. err .. '\n')
os.exit(1)
end
--from is cut, to is cut
local function cut_out_lines(lines,from_line,to_line)
-- print ("delete lines from "..from_line.." to "..to_line)
while lines[1+from_line]==0 do from_line=from_line+1 end
while lines[2+to_line]==0 do to_line=to_line+1 end
if to_line<from_line or not lines[1+from_line] then return end
--print ("adjusted delete lines from "..from_line.." to "..to_line)
local at_start=lines[from_line+1]
local before_start=at_start[1]
local after_end=lines[to_line+2]
local at_end
if after_end then
at_end=after_end[1]
else
after_end=Nil
end
if before_start ~= 'Cons' then
before_start[3]=after_end
if after_end~= Nil then after_end[1]=before_start end
else
at_start[3]=after_end
if after_end~= Nil then after_end[1]=at_start end
at_start[2].macro_token=''
end
for j=from_line+1,to_line+1 do lines[j]=0 end
end
local function cut_out_lines_saved(lines,saved)
cut_out_lines(lines,saved[1],saved[2])
return saved;
end
local cut_out_if_lines = {}
local if_state = {}
local function redo_if_statements(lines)
while #cut_out_if_lines>0 do cut_out_lines_saved(lines,table.remove(cut_out_if_lines)) end
end
local if_special_lines = {
['@endif']=true,
['@else']=true,
['@elseif']=true,
['@if']=true
}
local if_skip_lines = {
['@endif']=true,
['@if']=true
}
local function skip_if(lines, curline, line_number)
::search_more::
repeat
curline=curline+1
until not lines[1+curline] or if_skip_lines[car(lines[1+curline]).macro_token]
if not lines[1+curline] then
my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number))
end
if token == '@if' then
curline=skip_if(lines, curline, line_number)
goto search_more
end -- token == '@endif'
return curline
end
local function pp_endif(lines,line_number,filename, skipping)
if skipping then
my_err(cadr(start),'internal error. @endifs should be culled before second pass')
end
if #if_state==0 then
my_err(cadr(start),'@endif without matching @if')
end
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,line_number}))
table.remove(if_state)
return line_number+1
end
local function pp_else(lines,line_number,filename, skipping)
local start = lines[line_number+1]
if #if_state==0 then
my_err(cadr(start),'@else without matching @if')
end
table.remove(if_state)
local curline=line_number
::search_more::
repeat
curline=curline+1
until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token])
if not lines[1+curline] then
my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number))
end
local token = car(lines[1+curline]).macro_token
if token == '@if' then
curline=skip_if(lines, curline, line_number)
goto search_more
elseif token == '@endif' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline}))
return curline+1
elseif token == '@else' then
my_err(cadr(start),'second @else ' )
elseif token == '@elseif' then
my_err(cadr(start),'@elseif after @else ' )
end
end
local function pp_elseif(lines,line_number,filename, skipping)
local start = lines[line_number+1]
if #if_state==0 then
my_err(cadr(start),'@elseif without matching @if')
end
local curline=line_number
::search_more::
repeat
curline=curline+1
until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token])
if not lines[1+curline] then
my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number))
end
local token = car(lines[1+curline]).macro_token
if token == '@if' then
curline=skip_if(lines, curline, line_number)
goto search_more
elseif token == '@endif' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline}))
return curline+1
elseif token == '@else' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline-1}))
return pp_else(lines,curline,filename, skipping)
elseif token == '@elseif' then
goto search_more
end
table.remove(if_state)
end
local function pp_if(lines,line_number,filename, skipping)
local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1
if skipping then
my_err(cadr(start),'internal error. @ifs should be culled before second pass')
end
local function my_handler(err)
local token_number,error_text=string.match(tostring(err),":(%d+):(.*)")
if not token_number then
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
else
token_number = tonumber(token_number)+2
if not nullp(cdr(start)) then
my_err(nthcar( token_number,cdr(start)), error_text)
else
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
end
end
end
local function do_conditional_expression(line_number)
local start = lines[line_number+1]
local exp_start=cdr(lines[line_number+1])
local exp_end=exp_start
while not nullp(cadr(exp_end)) and cadr(exp_end).token.from_line == line_number do exp_end=cdr(exp_end) end
local ret= sublist_to_list({exp_start,exp_end},0)
if not filename and car(start).token then filename = car(start).token.filename end
if not skipping then
if ret then
ret=process(ret,filename,'no render')
end
local cond = my_dostring('return ('.. render(ret).. ')', filename, cdr(start));
-- if not cond then my_err(car(start), 'syntax error in @if or @elseif conditional expression') end
-- local _success,_err,result= xpcall(cond,my_handler)
-- print('if result',_success,_err,result)
return cond
end
end
if do_conditional_expression(line_number) then
-- print('if succeeded')
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,line_number}))
table.insert(if_state, 'if')
return line_number+1
else
-- print('if failed')
local curline=line_number
::search_more::
repeat
curline=curline+1
until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token])
if not lines[1+curline] then
my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number))
end
local token = car(lines[1+curline]).macro_token
if token == '@if' then
curline=skip_if(lines, curline, line_number)
goto search_more
elseif token == '@endif' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline}))
return curline+1
elseif token == '@else' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline}))
table.insert(if_state, 'else')
return curline+1
elseif token == '@elseif' then
table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline-1}))
return pp_if(lines,curline, filename, skipping)
end
end
end
local function pp_section(lines,line_number,filename, skipping)
local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1
if not filename and car(start).token then filename = car(start).token.filename end
local splice_first = start[1] -- can be 'Cons' on the first element
if cadr(start).type ~= 'String' then
my_err(cadr(start),'name of a section expected after @section, " or \' expected')
end--{}{}{}
local nl = cdr(start)
car(start).macro_token=''
cadr(start).macro_token=''
if skipping then
insure_subtable_exists(filename2sections,filename)
if filename2sections[filename][cadr(start).token.processed] then
my_err(cadr(start),'section '..cadr(start).token.processed..' in file '..filename..' already exists.')
end
filename2sections[filename][cadr(start).token.processed]= {insertion_point = start}
end
-- car(start).section = { filename=filename, section_name=cadr(start).token.processed }
--table.insert(filename2sections[filename],cadr(start).token.processed)
return car(nl).token.from_line+1
end
local function process_sections(filename)
local empty
if not filename2sections[filename] then return end
repeat
empty = true
for k,v in pairs(filename2sections[filename]) do
macro_list = Nil
for i=1,#v do
if not nullp(v[i]) then macro_list = list_append_in_place(v[i],macro_list) end
empty=false
end
for i=1,#v do table.remove(v) end
if macro_list then
macro_list=process(macro_list,filename,'no render')
end
if v.processed_macros then
v.processed_macros = list_append_in_place(v.processed_macros,macro_list)
else
v.processed_macros = macro_list
end
end
until empty
for k,v in pairs(filename2sections[filename]) do
--insert processed now
if not nullp(v.processed_macros) then
v.insertion_point[3] = list_append_in_place(v.processed_macros,v.insertion_point[3])
end
end
end
local function section_object_from_token(token)
if not token.section then return nil end
return filename2sections[token.section.filename][token.section.section_name]
end
local function pp_require(lines,line_number,filename,skipping)
local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1
local splice_first = start[1] -- can be 'Cons' on the first element
if cadr(start).type ~= 'String' then
my_err(cadr(start),'name of a file expected after @require, " or \' expected')
end--{}{}{}
local nl = cdr(start)
if not skipping then require(cadr(start).token.processed) end
if splice_first~= 'Cons' then
splice_first[3]=cdr(nl)
cdr(nl)[1]=splice_first
else
start[3]=cdr(nl)
cdr(nl)[1]=start
car(start).macro_token=''
end
return car(nl).token.from_line+1
end
local function pp_macro(lines,line_number,filename,skipping)
local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1
local splice_first = start[1] -- can be 'Cons' on the first element
if cadr(start).macro_token ~= '{' then
my_err(cadr(start),'struct of macro expected after @macro, { expected')
end
local s,nl
s,nl=optional_read_match_to(cddr(start),'}')
if not s or nullp(nl) or car(nl).macro_token ~='}' then
my_err(start,'struct of macro expected after @macro, } expected')
end
local ret = sublist_to_list( {cdr(start),nl} )
-- local filename = nil
if not filename and car(start).token then filename = car(start).token.filename end
local macro = my_dostring('return('..render(ret)..')', filename, cdr(start));
if not macro then my_err(car(start), 'syntax error in table definition for macro') end
if not skipping then
print("adding macro:",macro.head)
print(macro.new_tokens)
add_macro(macro,macros, filename,car(start).token.from_line)
end
if splice_first~= 'Cons' then
splice_first[3]=cdr(nl)
cdr(nl)[1]=splice_first
else
start[3]=cdr(nl)
cdr(nl)[1]=start
car(start).macro_token=''
end
return car(nl).token.from_line+1
end
local function pp_start(lines,line_number,filename,skipping)
local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1
local splice_first = start[1] -- can be 'Cons' on the first element
local s,nl
s,nl=optional_read_match_to(cddr(start),'@end')
if not s or nullp(nl) or car(nl).macro_token ~='@end' then
my_err(start,'@end expected after @start')
end
local ret = sublist_to_list( {cdr(start),nl},1 )
-- local filename = nil
if not filename and car(start).token then filename = car(start).token.filename end
if not skipping then
if ret then
ret=process(ret,filename,'no render')
end
local macro = my_dostring('return function () '.. render(ret)..' end', filename, cdr(start));
if not macro then my_err(car(start), 'syntax error @start/@end block') end
local function my_handler(err)
local token_number,error_text=string.match(tostring(err),":(%d+):(.*)")
if not token_number then
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
else
token_number = tonumber(token_number)+2
if not nullp(cdr(start)) then
my_err(nthcar( token_number,cdr(start)), error_text)
else
my_err(nil,"can't determine token for error \""..tostring(err)..'"')
end
end
end
xpcall(macro,my_handler)
end
if splice_first~= 'Cons' then
splice_first[3]=cdr(nl)
cdr(nl)[1]=splice_first
else
start[3]=cdr(nl)
cdr(nl)[1]=start
car(start).macro_token=''
end
return car(nl).token.from_line+1
end
--turn list back to normal cons cells after first stage of preprocessing
local function strip_back_links(list)
local n=list
while not nullp(n) do
n[1]='Cons'
n=n[3]
end
while list.macro_token == '' do list=list[3] end
return list
end
preprocessor_tokens = setmetatable({
['@start']=pp_start,
-- ['@end']=pp_null_fn,
--['@define']=pp_null_fn,
['@if']=pp_if,
['@elseif']=pp_elseif,
['@else']=pp_else,
['@endif']=pp_endif,
['@section']=pp_section,
--['@fileout']=pp_null_fn,
['@require']=pp_require,
['@macro']=pp_macro,
}, { __index = function (_,v) return pp_null_fn end})
--macros as first class at expand time
--[==[
@macro{
new_tokens={'WHILE','DO','END','BREAK','CONTINUE'},
head='WHILE ?()...exp DO ?,...statements END',
body=[[
local function %loop()
if ?exp then
@apply({{head='BREAK',body='return("__*done*__")'},
{head='CONTINUE',body='return %loop()'},}, ?statements)
return %loop()
end
return '__*done*__'
end
local %save=table.pack(%loop())
if %save[1]~='__*done*__' then return table.unpack(%save,%save.n) end
local fn,err= loadstring(process([[
local i,j
i=1
WHILE i<=6 DO
j=10
if i==3 then CONTINUE end
if i==5 then BREAK end
WHILE j<=60 DO
if j==30 then CONTINUE end
if j==50 then BREAK end
print(i,j)
--I should test return too
j=j+10
END
i=i+1
END
]]))
fn()
}
--]==]
add_token_keys= function(t)
for k,_ in pairs(t) do
tokenizer.add_special_token(k)
end
end
add_tokens= function(t)
if not t then return end
for _,v in ipairs(t) do
tokenizer.add_special_token(v)
end
end
add_token_keys(simple_translate)
local function no_source_token(t)
return setmetatable({macro_token=t},token_metatable)
end
local function string_to_source_array(str,filename,err_handler)
local error_pos, source, meaningful =tokenizer.tokenize_all(str,filename,err_handler)
--{}{}{} process needs to ignore token errors on the first pass
-- but the rest of the program???
-- if not error_pos then
local flatten={}
local prevx,prevy,indent=0,0,0
for a = 1,#meaningful do
local ttype = source[meaningful[a]].type
local value
local token=source[meaningful[a]]
-- if ttype=='String' then
--we don't want to find escape sequences in our strings, so we use the processed version
-- value='[=======['..source[meaningful[a]].processed..']=======]'
-- else
value=source[meaningful[a]].value
-- end
local dy=token.from_line-prevy
prevy=token.to_line
local dx,first
if dy ~= 0 then
dx=token.from_x
indent = dx
first=true
else
dx=token.from_x-prevx
first=false
end
prevx=token.to_x
table.insert(flatten, setmetatable( {first = first,macro_token=simple_translate[value],type=ttype,token=token,dx=dx,dy=dy,indent=indent, splice=false, indent_delta=0},token_metatable))
-- print('y = '..tostring( flatten[#flatten].token.from_line )..'\t x = '.. tostring( flatten[#flatten].token.from_x))
end
return flatten
-- end
end
local function splice_simple(original_head_list, new_head_array, concat_list)
if not new_head_array then
error("internal")
end
if #new_head_array == 0 then return concat_list end
local indent
local indent_delta
if nullp(original_head_list) then
indent = (new_head_array[1].indent or car(concat_list).indent or 0)
indent_delta = 0
else
indent =car(original_head_list).indent+car(original_head_list).indent_delta
indent_delta = indent-((new_head_array[1].indent or 0) + (new_head_array[1].indent_delta or 0))
end
local l=concat_list or Nil
if new_head_array then
for i=#new_head_array,1,-1 do
-- if not new_head_array[i].indent then
-- print 'wat'
-- end
assert (new_head_array[i].indent)
new_head_array[i].indent_delta=(new_head_array[i].indent_delta or 0)+indent_delta
l=cons(new_head_array[i],l)
end
car(l).splice=true
car(l).first=true
car(l).dy=1
car(l).dx=car(l).indent
if concat_list and not concat_list[1].first then
car(concat_list).splice=true
car(concat_list).first=true
car(concat_list).dy=1
car(concat_list).dx=car(concat_list).indent
end
end
return l
end
local function splice(original_head_list, new_head_array, section, filename)
--Note, in the first case "section" is the concat list not the section
if not filename then return splice_simple(original_head_list, new_head_array, section) end
if not filename2sections[filename] then
my_err(Nil,'No sections in file '..filename..' have been found.')
end
local section_table = filename2sections[filename][section]
if not section_table then
my_err(Nil,'no section '..section..' in file '..filename..' found.')
end
local sp= splice_simple(original_head_list, new_head_array)
table.insert(section_table,sp)
return sp
end
simple_copy = function (obj)
if type(obj) ~= 'table' then return obj end
local copy={}
for i,v in pairs(obj) do copy[i]=v end
return setmetatable(copy,getmetatable(obj))
end
--[[
New syntax
?name
?...name
?,...name
?()...name
]]
local macro_params={
--input paramsk
['?1']='param',
--input matches till
['?...']='param until',
--input matches till next, also matches () {} [] - stops for comma
--if the expected next is a comma then that matches
--if the expected next is not a comma and it finds one, that's a failure
['?']='param match until',
--in matches any number of elements including commas
['?,']='params',
['??,']='optional params',--generate var
['%']='generate var',
-- ['%external-load:']='global load', -- also need a 4th entry for saving
['@apply']='apply macros',
}
add_token_keys(preprocessor_tokens)
tokenizer.add_special_token('@apply')
tokenizer.add_special_token('@@') --needs a global macro with a function body
tokenizer.add_special_token('@tostring') --needs a global macro with a function body
tokenizer.add_special_token('@end')
local function skip_one(l)
if not nullp(l) then return cdr(l) end
return l
end
local function skip_apply(l, store, filename)
l=cdr(l)
if car(l).macro_token ~='(' then my_err(car(l), '( expected after @apply ') end
l=cdr(l)
local ret
local where_struct_goes = l
if (store) then
if car(l).macro_token ~='{' or cadr(l).macro_token ~='{' then my_err(car(l), 'array of macros expected after @apply ( got: '..car(l).macro_token .." ".. cadr(l).macro_token) end
local s,nl
s,nl=optional_read_match_to(l,',')
if not s then my_err(car(l), 'array of macros expected after @apply (') end
if nullp(nl) then
my_err(car(l) ', expected after @apply({macros...} ')
end
if car(nl).macro_token ~=',' then
my_err(car(nl) ', expected after @apply({macros...} ')
end
--{}{}{} could use formatting
ret = sublist_to_list( {l,nl},1 )
local tokens = l
l=cdr(nl);
--concat_cons(ret,' ');
where_struct_goes[2]={}
local filename=nil
if l.token then filename=l.token.filename end
local temp_macros = my_dostring('return('..render(ret)..')', filename, tokens);
if not temp_macros then my_err(car(nl), 'syntax error in table definition for macro for @apply') end
for i = 1,#temp_macros do
add_macro(temp_macros[i],where_struct_goes[2],filename) --
end
where_struct_goes[3]=l
else
l=cdr(l)
end
if nullp(l) or not macro_params[car(l).macro_token] then my_err(car(l),'parameter expected after @apply({macros...}, got '.. car(l).macro_token ..' instead') end
l=cdr(l)
if nullp(l) or car(l).type~='Id' then my_err (car(l),'Id expected after @apply({macros...}, got '.. car(l).macro_token..' type = "'.. tostring( car(l).type) ..'" instead') end
l=cdr(l)
if nullp(l) or car(l).macro_token ~=')' then my_err(car(l), ') expected after @apply({macros...},?Id') end
return cdr(l),where_struct_goes[2],caddr(where_struct_goes)
end
local skip_param_tokens={
['param']=skip_one,
--input matches till
['param until']=skip_one,
--input matches till next, also matches () {} [] - stops for comma
--if the expected next is a comma then that matches
--if the expected next is not a comma and it finds one, that's a failure
['param match until']=skip_one,
--in matches any number of elements including commas
['params']=skip_one,
['optional params']=skip_one,
--generate var
['generate var']=skip_one,
-- ['%external-load:']='global load', -- also need a 4th entry for saving
['apply macros']=skip_apply,
}
add_token_keys(macro_params)
local match=
{
['(']=')',
['{']='}',
['[']=']',
['do']='end',
['for']='do', --special cased to go for 'end' after 'do'
['while']='do', --special cased to go for 'end' after 'do'
['if']='end',
['function']='end',
['repeat']='until', --really needs to be until exp
}
local starts=
{
['for']=true,
['while']=true,
['if']=true,
['function']=true,
['repeat']=true,
['local']=true,
['return']=true,
}
local separators=
{
[',']=true,
[';']=true,
}
local ends={
['end']=true
}
--[[
so here, car is [2]
cdr is [3]
--]]
nullp= function(l) return l==Nil end
local function listp(n)
return type(n)=='table' and 'Cons' == n[1]
end
local function pairp(n)
return (not nullp(n)) and listp(n)
end
last_cell=function(l)
while pairp(cdr(l)) do
l=cdr(l)
end
return l
end
car=function(n)
if n==nil then
error('car on lua nil')
end
return n[2]
end
cadr=function(n)
if n==nil then
error('cadr on lua nil')
end
return n[3][2]
end
caddr=function(n)
if n==nil then
error('caddr on lua nil')
end
return n[3][3][2]
end
cdddr=function(n)
if n==nil then
error('cdddr on lua nil')
end
return n[3][3][3]
end
cddr=function(n)
if n==nil then
error('cddr on lua nil')
end
return n[3][3]
end
cdr= function(n)
if n==nil then
error('cdr on lua nil')
end
return n[3]
end
cons = function (first, rest)
return setmetatable({'Cons',first,rest},
{__tostring = cons_tostring,
__concat= function(op1,op2) return tostring(op1) .. tostring(op2) end,
__len=function(self)
if nullp(self) then return 0
elseif nullp(self[3]) then return 1
elseif not listp(self[3]) then return 1.5
end
return 1+ #(self[3])
end
})
end
local function reverse_transfer_one_in_place(dest,source)
if source==nil then
print 'wat'
end
if not nullp(source) then
dest,source,source[3] = source,source[3],dest
end
return dest,source
end
reverse_list_in_place= function (l,concat)
local d=concat or Nil
while not nullp(l) do
l,d,l[3]=l[3],l,d
end
return d
end
--otherwise known as nconc
list_append_in_place = function(l,concat)
local r=l
while r[3]~=Nil do r=r[3] end
r[3]=concat
return l
end
reverse_list= function (l,concat)
local d=concat or Nil
while not nullp(l) do
d=cons(l[2],d)
l=l[3]
end
return d
end
local function array_to_list(a, concat)
local l=concat or Nil
if a then