-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpreproc.lua
More file actions
1694 lines (1537 loc) · 46 KB
/
preproc.lua
File metadata and controls
1694 lines (1537 loc) · 46 KB
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
--[[
I'm currently breaking everything
1) merge the preproic expr prarser with the noew entre preproc parser
2) dont use its ast, instead eval as you go and replace the preproc parser stack values
3) replace the foundIncompleteMacroLine line with just keep the parser parsing
4) hoepfully handle #'s and ##'s while parsing
5) parse parse parse parse parse
--]]
local assert = require 'ext.assert'
local string = require 'ext.string'
local table = require 'ext.table'
local tolua = require 'ext.tolua'
local path = require 'ext.path'
local class = require 'ext.class'
local bit = require 'bit' -- either luajit's, or my vanilla Lua compat wrapper lib ...
local function isvalidsymbol(s)
return not not s:match('^[_%a][_%w]*$')
end
-- largest to smalleste
local cSymbols = table{
'...',
'&&',
'||',
'==',
'>=',
'<=',
'!=',
'<<',
'>>',
'->',
'##',
'++',
'--',
'>',
'<',
'!',
'&',
'|',
'+',
'-',
'*',
'/',
'%',
'^',
'~',
'(',
')',
'?',
':', -- is there a need to parse :: separately? for C++? nah, not for the preprocessor's expressions.
',',
'=',
';',
'#',
'.',
'[',
']',
'{',
'}',
}:sort(function(a,b) return #a > #b end)
local cSymbolSet = cSymbols:mapi(function(c) return true, c end):setmetatable(nil)
local cSymbolEscs = cSymbols:mapi(function(c) return '^'..string.patescape(c) end)
local function gettokentype(s, i)
i = i or 1
local tokentype, ti1, ti2
if s:find('^[_%a]', i) then
-- if we start as a word then read a word
ti1, ti2 = s:find('^[_%a][_%w]*', i)
tokentype = 'name'
elseif s:find('^%d', i) then
-- TODO combine these suffixes with the ones on string parsing ...
-- TODO if you find a digit then go on to handle any suffix and then validate it later
if not ti1 then
ti1, ti2 = s:find('^0[Xx]%x+[Uu][Ll][Ll]', i) -- ULL hex
end
if not ti1 then
ti1, ti2 = s:find('^%d+[Uu][Ll][Ll]', i) -- ULL dec
end
if not ti1 then
ti1, ti2 = s:find('^0[Xx]%x+[Uu][Ll]', i) -- UL hex
end
if not ti1 then
ti1, ti2 = s:find('^%d+[Uu][Ll]', i) -- UL dec
end
if not ti1 then
ti1, ti2 = s:find('^0[Xx]%x+[Ll][Ll]', i) -- LL hex
end
if not ti1 then
ti1, ti2 = s:find('^%d+[Ll][Ll]', i) -- LL dec
end
if not ti1 then
ti1, ti2 = s:find('^0[Xx]%x+[LlUu]?', i) -- U/L hex
end
if not ti1 then
ti1, ti2 = s:find('^%d+[LlUu]?', i) -- U/L dec
end
-- how about floats and [eE]+ stuff?
--ti1, ti2 = s:find('^%d[%w]*', i) -- if we start as a number then read numbers
tokentype = 'number'
elseif s:find("^'", i) then
ti1 = i
ti2 = ti1 + 1
if s:sub(ti2, ti2) == '\\' then ti2 = ti2 + 1 end
ti2 = ti2 + 1
assert.eq(s:sub(ti2, ti2), "'", 'at line '..s)
tokentype = 'char'
elseif s:find('^"', i) then
-- read string ... ugly
ti1 = i
ti2 = i
while true do
ti2 = ti2 + 1
if s:sub(ti2, ti2) == '\\' then
ti2 = ti2 + 1
elseif s:sub(ti2, ti2) == '"' then
break
end
end
tokentype = 'string'
else
-- see if it's a symbol, searching biggest to smallest
for k,esc in ipairs(cSymbolEscs) do
ti1, ti2 = s:find(esc, i)
if ti1 then break end
end
if not ti1 then error("gettokentype failed with: "..tolua(s:sub(i, i+20))) end
tokentype = 'symbol'
end
return tokentype, ti1, ti2
end
local Reader = class()
function Reader:init(data)
self:resetData(data)
end
function Reader:resetData(data)
self.stack = setmetatable({}, {
__index = function(t,k)
if type(k) == 'number' and k < 0 then
k = k + #t + 1
end
local v = rawget(t, k)
if v == nil then v = table[k] end
return v
end,
__newindex = function(t,k,v)
if type(k) == 'number' and k < 0 then
k = k + #t + 1
end
rawset(t, k, v)
end,
})
-- each entry holds .token, .type, .space
self:setData(data)
end
function Reader:setData(data)
-- I might regret this but here's me erasing spaces on the rhs
data = data:match'^(.-)%s*$'
self.data = data
self.index = 1
self:next() -- prep next symbol as top
end
function Reader:next()
--DEBUG:print('Reader:next() index='..self.index..', #self.data='..#self.data)
if self.index > #self.data then
if #self.stack == 0
or self.stack:last().type ~= 'done'
then
--DEBUG:print'Reader:next ...inserting type=done'
self.stack:insert{token='', type='done', space=''}
end
--DEBUG:print'Reader:next ...done'
return '', 'done', ''
end
local si1, si2 = self.data:find('^%s*', self.index)
assert(si1)
local space = self.data:sub(si1, si2)
self.index = si2 + 1
local tokentype, ti1, ti2 = gettokentype(self.data, self.index)
if not ti1 then error("failed to match at "..self.data:sub(self.index, self.index+20)) end
local token = self.data:sub(ti1, ti2)
self.index = ti2 + 1
self.stack:insert{token=token, type=tokentype, space=space}
--DEBUG:print('Reader:next ...next got', tolua{token=token, type=tokentype, space=space})
return token, tokentype, space
end
function Reader:canbe(token)
local last = self.stack:last()
if token == last.token then
self:next()
return last.token
end
end
function Reader:mustbe(token)
return assert(self:canbe(token))
end
function Reader:canbetype(tokentype)
--DEBUG:print('Reader:canbetype', self, tokentype)
--DEBUG:print('Reader:canbetype self.stack', self.stack)
local last = self.stack:last()
--DEBUG:print('Reader:canbetype last', last)
if tokentype == last.type then
self:next()
--DEBUG:print('Reader:canbetype returning', last.token)
return last.token
end
end
function Reader:mustbetype(tokentype)
--DEBUG:print('Reader:mustbetype', self, tokentype)
local result = self:canbetype(tokentype)
or error("expected token type "..tolua(tokentype).." but found "..tolua(self.stack:last()))
--DEBUG:print('Reader:mustbetype got', result)
return result
end
-- concats the currently-unprocessed top-of-stack with the rest of the data
function Reader:whatsLeft()
return self.stack:last().token..self.data:sub(self.index)
end
local function determineSpace(prevEntry, thisEntry)
local space = ''
if prevEntry then
if (thisEntry.type == 'name' or thisEntry.type == 'number')
and (prevEntry.type == 'name' or prevEntry.type == 'number')
then
-- if the neighboring token types don't play well then put a space
space = ' '
else
-- if merging makes another valid token then put a space
if cSymbolSet[prevEntry.token..thisEntry.token] then
space = ' '
end
end
end
return space
end
-- lastToken = stack[] entry underneath where it's going
-- determines token type and determines what kind of space to use
function makeTokenEntry(token, lastTokenStackEntry)
assert.type(token, 'string')
if lastTokenStackEntry ~= nil then assert.type(lastTokenStackEntry, 'table') end
local tokentype = gettokentype(token)
local newStackEntry = {token=token, type=tokentype}
newStackEntry.space = determineSpace(lastTokenStackEntry, newStackEntry)
return newStackEntry
end
function Reader:setStackToken(loc, token)
assert.type(loc, 'number')
assert.type(token, 'string')
--[[ TODO. This isn't working. but I need it to work to remove spaces between symbols and numbers etc.
local thisEntry = makeTokenEntry(token, self.stack[loc-1])
self.stack[loc] = thisEntry
local nextEntry = self.stack[loc+1]
if nextEntry then
nextEntry.space = determineSpace(thisEntry, nextEntry)
end
--]]
-- [[ works but extra space
assert.ge(loc, 1)
assert.le(loc, #self.stack+1)
self.stack[loc] = {token=token, type='name', space=' '}
--]]
end
function Reader:replaceStack(startPos, endPos, ...)
if startPos < 0 then startPos = startPos + 1 + #self.stack end
if endPos < 0 then endPos = endPos + 1 + #self.stack end
local removed = self.stack:sub(startPos, endPos)
for i=startPos,endPos do
assert.le(1, startPos)
assert.le(startPos, #self.stack)
assert(self.stack:remove(startPos))
end
-- insert left to right, in order (not reversed), so that each token can see its predecessor in the stack
for i=1,select('#',...) do
local insloc = startPos+i-1
assert.ge(insloc, 1)
assert.le(insloc, #self.stack+1)
self.stack:insert(insloc, makeTokenEntry(select(i, ...), self.stack[insloc-1]))
end
return removed:unpack()
end
function Reader:removeStack(loc)
return self:replaceStack(loc, loc)
end
function Reader:insertStack(loc, ...)
return self:replaceStack(loc, loc-1, ...)
end
function Reader:stackToString()
--DEBUG:print('Reader:stackToString stack='..tolua(self.stack))
return self.stack:mapi(function(entry) return entry.space..entry.token end):concat()
end
local Preproc = class()
--static method
function Preproc.removeCommentsAndApplyContinuations(code)
-- dos -> unix file format ... always?
-- what about just \r's?
code = code:gsub('\r\n', '\n')
-- should line continuations \ affect single-line comments?
-- if so then do this here
-- or should they not? then do this after.
repeat
local i, j = code:find('\\\n')
if not i then break end
--DEBUG(removeCommentsAndApplyContinuations): print('was', tolua(code))
code = code:sub(1,i-1)..' '..code:sub(j+1)
--DEBUG(removeCommentsAndApplyContinuations): print('is', tolua(code))
until false
-- remove all /* */ blocks first
repeat
local i = code:find('/*',1,true)
if not i then break end
local j = code:find('*/',i+2,true)
if not j then
error("found /* with no */")
end
--DEBUG(removeCommentsAndApplyContinuations): print('was', tolua(code))
code = code:sub(1,i-1)..code:sub(j+2)
--DEBUG(removeCommentsAndApplyContinuations): print('is', tolua(code))
until false
-- [[ remove all // \n blocks first
repeat
local i = code:find('//',1,true)
if not i then break end
local j = code:find('\n',i+2,true) or #code
--DEBUG(removeCommentsAndApplyContinuations): print('was', tolua(code))
code = code:sub(1,i-1)..code:sub(j)
--DEBUG(removeCommentsAndApplyContinuations): print('is', tolua(code))
until false
--]]
return code
end
-- whether, as a final pass, we combine non-semicolon lines
Preproc.joinNonSemicolonLines = true
--[[
Preproc(code)
Preproc(args)
args = table of:
code = code to use
sysIncludeDirs = include directories to use for <>
userIncludeDirs = include directories to use for ""
macros = macros to use
--]]
function Preproc:init(args)
self.macros = {}
self.alreadyIncludedFiles = {}
self.sysIncludeDirs = table()
self.userIncludeDirs = table()
-- builtin/default macros?
-- here's some for gcc:
-- TODO move these to outside preproc?
self:setMacros{
__restrict = '',
__restrict__ = '',
}
-- the INCLUDE env var is for <> and not "", right?
-- not showing up at all in linux 'g++ -xc++ -E -v - < /dev/null' ...
-- maybe it's just for make?
-- yup, and make puts INCLUDE as a <> search folder
local incenv = os.getenv'INCLUDE'
if incenv then
self:addIncludeDirs(string.split(incenv, ';'), true)
end
if args ~= nil and (type(args) == 'string' or args.code) then
self(args)
end
end
function Preproc:getIncludeFileCode(fn, search, sys)
-- at position i, insert the file
return assert(path(fn):read(), "couldn't find file "..(
sys and ('<'..fn..'>') or ('"'..fn..'"')
))
end
function Preproc:getDefineCode(k, v, l)
--DEBUG(Preproc:getDefineCode): print('getDefineCode setting '..k..' to '..tolua(v))
self.macros[k] = v
return ''
end
-- external API. internal should use 'getDefineCode' for codegen
function Preproc:setMacros(args)
--[[
for k,v in pairs(args) do
--]]
-- [[
for _,k in ipairs(table.keys(args):sort()) do
local v = args[k]
--]]
--DEBUG(Preproc:setMacros): print('setMacros setting '..k..' to '..tolua(v))
self.macros[k] = v
end
end
function Preproc:addIncludeDir(dir, sys)
-- should I fix paths of the user-provided userIncludeDirs? or just INCLUDE?
dir = dir:gsub('\\', '/')
if sys then
self.sysIncludeDirs:insert(dir)
else
self.userIncludeDirs:insert(dir)
end
end
function Preproc:addIncludeDirs(dirs, ...)
for _,dir in ipairs(dirs) do
self:addIncludeDir(dir, ...)
end
end
function Preproc:searchForInclude(fn, sys, startHere)
local includeDirs = sys
and self.sysIncludeDirs
--[[
seems "" searches also check <> search paths
but do <> searches also search "" search paths?
why even use different search folders?
--]]
--or self.userIncludeDirs
or table():append(self.userIncludeDirs, self.sysIncludeDirs)
local startIndex
if startHere then
--DEBUG(Preproc:searchForInclude): print('searching '..tolua(includeDirs))
--DEBUG(Preproc:searchForInclude): print('search starting '..tostring(startHere))
startHere = startHere:match'^(.-)/*$' -- remove trailing /'s
for i=1,#includeDirs do
local dir = includeDirs[i]:match'^(.-)/*$'
--DEBUG(Preproc:searchForInclude): print("does "..tostring(startHere).." match "..tostring(dir).." ? "..tostring(dir == startHere))
if dir == startHere then
startIndex = i+1
break
end
end
--DEBUG(Preproc:searchForInclude): print('startIndex '..tostring(startIndex))
-- if we couldn't find startHere then ... is that good? do we just fallback on default? or do we error?
-- startHere is set when we are already in a file of a matching name, so we should be finding something, right?
if not startIndex then
error'here'
end
end
startIndex = startIndex or 1
for i=startIndex,#includeDirs do
d = includeDirs[i]
local p = d..'/'..fn
p = p:gsub('//+', '/')
if path(p):exists() then
return p
end
end
end
local function cLiteralIntegerToNumber(x)
if type(x) == 'string' then
-- remove C number suffixes
x = x:match'^(.*)[UuLlZz][UuLl]?[Ll]?$' or x
end
-- ok Lua tonumber hack ...
-- tonumber'0x10' converts from base 16 ..
-- tonumber'010' converts from base 10 *NOT* base 8 ...
-- and because now i'm using macro-evaluation to convert my #define's into enum {} 's ...
-- it's important here
local n = tonumber(x)
if not n then return nil end
-- if it's really base 8 then lua will interpret it (successfully) as base-10
if type(x) == 'string'
and x:match'^0%d'
then
n = tonumber(x, 8)
end
return n
end
local function castnumber(x)
if x == nil then return 0 end
if x == false then return 0 end
if x == true then return 1 end
local n = cLiteralIntegerToNumber(x)
if not n then error("couldn't cast to number: "..tolua(x)) end
return n
end
--[[
Uses parenthesis-balancing to parse the macro arguments.
args:
paramStr = macro arg, of '(' + comma-sep args + ')'
vparams = list of macro params: {'a', 'b', 'c'} etc, found in macros[name].params
returns:
map from vparams' strings as keys to values found in paramStr
with maybe an extra '...' key to any varargs
--]]
function Preproc:parseMacroArgs(paramStr, vparams)
--DEBUG:print('Preproc:parseMacroArgs', tolua{paramStr=paramStr, vparams=vparams})
local paramIndex = 0
local paramMap = {}
if not paramStr:match'^%s*$' then
local parcount = 0
local last = 1
local i = 1
while i <= #paramStr do
local ch = paramStr:sub(i,i)
if ch == '(' then
parcount = parcount + 1
elseif ch == ')' then
parcount = parcount - 1
elseif ch == '"' then
-- skip to the end of the quote
i = i + 1
while paramStr:sub(i,i) ~= '"' do
if paramStr:sub(i,i) == '\\' then
i = i + 1
end
i = i + 1
end
elseif ch == ',' then
if parcount == 0 then
local paramvalue = paramStr:sub(last, i-1)
paramIndex = paramIndex + 1
if #vparams == 1 and vparams[1] == '...' then
-- varargs ... use ... indexes? numbers? strings?
paramMap[paramIndex] = paramvalue
else
if not vparams[paramIndex] then
error('failed to find paramIndex '..tostring(paramIndex)..'\n'
..' vparams='..require'ext.tolua'(vparams)..'\n' -- macro arguments
--..' paramStr='..tostring(paramStr)..'\n'
..' paramvalue='..tostring(paramvalue)..'\n'
..' l='..tostring(l)..'\n' -- line we are replacing
..' paramMap='..tolua(paramMap)..'\n'
)
end
paramMap[vparams[paramIndex]] = paramvalue
end
last = i + 1
end
end
i = i + 1
end
assert.eq(parcount, 0, "macro mismatched ()'s")
local paramvalue = paramStr:sub(last)
paramIndex = paramIndex + 1
if #vparams == 1 and vparams[1] == '...' then
-- varargs
paramMap[paramIndex] = paramvalue
else
local macrokey = vparams[paramIndex]
if not macrokey then
error("failed to find index "..tolua(paramIndex).." of vparams "..tolua(vparams))
end
--DEBUG(Preproc:parseMacroArgs): print('substituting the '..paramIndex..'th macro from key '..tostring(macrokey)..' to value '..paramvalue)
paramMap[macrokey] = paramvalue
end
end
-- if we were vararg matching this whole time ... should I replace it with a single-arg and concat the values?
if #vparams == 1 and vparams[1] == '...' then
paramMap = {['...'] = table.mapi(paramMap, function(v) return tostring(v) end):concat', '}
else
assert.eq(paramIndex, #vparams, "expanding macro, expected "..#vparams.." "..tolua(vparams).." params but found "..paramIndex..": "..tolua(paramMap))
end
--DEBUG:print('Preproc:parseMacroArgs got', tolua(paramMap))
return paramMap
end
--[[
try to evaluate the token at the top
this is used by level13, but unlike it this doesn't fail if it can't evaluate it
this is also used by normal-line macro-expansion with evaluatingPlainCode=true
evaluatingPlainCode tells it not to call back into the :level*() functions for expression-evaluation, just macro-replacement.
--]]
function Preproc:tryToEval(r, evaluatingPlainCode)
--DEBUG:print('Preproc:tryToEval', tolua(r.stack[-1]))
local top = #r.stack
local origline = r:whatsLeft()
if r:canbetype'name' then
-- stack: {..., name, next}
local k = r.stack[-2].token
local kspace = r.stack[-2].space -- space before this entry
local v = self.macros[k]
--DEBUG:print('...handling named macro: '..tolua(k)..' = '..tolua(v))
if type(v) == 'string' then
--DEBUG:print('... macro is direct replacement')
assert.eq(r:removeStack(-2).token, k)
-- stack: {..., next}
-- then we need to wedge our string into the to-be-parsed content ...
-- throw out the old altogether?
local rest = r:whatsLeft()
r:removeStack(-1)
-- stack: {...}
r:setData(kspace..v..' '..rest)
-- stack: {..., next}
if not evaluatingPlainCode then
self:level1(r) -- when inserting macros, what level do I start at?
else
-- to pass the test at the end we should insert ''
-- but that will mess things up later
-- so just return now
return true
end
-- stack: {..., result, next}
elseif type(v) == 'table' then
--DEBUG:print('... macro has arguments')
assert.eq(r:removeStack(-2).token, k)
-- stack: {..., next}
-- if I try to separately parse further then I have to parse whtas inside the macro args, which would involve () balancing, and only for the sake of () balancing
-- otherwise I can just () balance regex and then insert it all into the current reader
local paramStr, rest
rest = string.trim(r:whatsLeft())
r:removeStack(-1)
-- stack: {...}
paramStr, rest = rest:match'^(%b())%s*(.*)$'
-- now we have to count () balance ourselves to find our where the right commas go ...
assert(paramStr, "macro expected arguments")
-- TODO ()-balancing and comma-separation for the arguments in 'paramStr' ...
paramStr = paramStr:sub(2,-2) -- strip outer ()'s
-- then use those for values associatd with variables in `v.params`
local paramMap = self:parseMacroArgs(paramStr, v.params)
-- then replace all occurrences of those variables found within the stack of `v.def`
-- then copy that stack onto the top, underneath the current next-token.
local eval = table()
for _,e in ipairs(v.def) do
eval:insert(e.space)
local replArg = paramMap[e.token]
if replArg then
eval:insert(replArg)
else
eval:insert(e.token)
end
end
eval = eval:concat()
--DEBUG:print('evalated to', eval)
-- then we need to wedge our def into the to-be-parsed content with macro args replaced ...
r:setData(kspace..eval..' '..rest)
-- stack: {..., next}
-- when inserting macros, what level do I start at?
-- to handle scope, lets wrap in ( ) and use level13's ( ) evaluation
if not evaluatingPlainCode then
self:level1(r)
else
-- to pass the test at the end we should insert ''
-- but that will mess things up later
-- so just return now
return true
end
-- stack: {..., result, next}
elseif type(v) == 'nil' then
--DEBUG:print('... macro was not defined')
-- any unknown/remaining macro variable is going to evaluate to 0
if not evaluatingPlainCode then
if r:canbe'(' then
error("function-like macro "..tolua(k).." is not defined")
end
-- if we're in a macro-eval then replace with a 0
r:replaceStack(-2, -2, '0')
-- stack: {..., "0", next}
else
-- if we're not in a macro-eval then leave it as is
-- stack: {..., name, next}
end
end
else
--DEBUG:print("...couldn't handle "..tolua(origline))
--DEBUG:print("The stack better not have changed.")
assert.len(r.stack, top)
return false
end
--DEBUG:print("...handled, so the stack better be +1")
assert.len(r.stack, top+1)
return true
end
function Preproc:level13(r)
local top = #r.stack
local rest = r:whatsLeft()
if r:canbetype'number' then
local prev = r.stack[-2].token
-- stack: {prev, next}
-- remove L/U suffix:
local val = cLiteralIntegerToNumber(prev)
or error("expected number. found "..tolua(prev)) -- decimal number
-- put it back
-- or better would be (TODO) just operate on 64bit ints or whatever preprocessor spec says it handles
r:replaceStack(-2, -2, tostring(val))
elseif r:canbe'(' then
self:level1(r)
r:mustbe')'
-- stack: {'(', prev, ')', next}
r:removeStack(-4)
r:removeStack(-2)
-- stack: {prev, next}
-- what does this even do?
elseif r:canbe'_Pragma' then
--DEBUG:print'...handling _Pragma'
-- stack: {..., "_Pragma", next)
assert.eq(r:removeStack(-2).token, '_Pragma')
-- stack: {..., next)
-- here we want to eliminate the contents of the ()
-- so just reset the data and remove the %b()
local rest = string.trim(r:whatsLeft())
local par, rest = rest:match'^(%b())%s*(.*)$'
assert(par)
r:removeStack(-1)
-- stack: {...}
r:setData(rest)
-- stack: {..., next}
r:insertStack(-1, '0')
-- stack: {..., "0", next}
elseif r:canbe'__has_include'
or r:canbe'__has_include_next'
then
local prev = r.stack[-2].token
--DEBUG:print('...handling '..prev)
assert(prev == '__has_include' or prev == '__has_include_next')
-- stack: {..., prev, next}
assert.eq(r:removeStack(-2).token, prev)
-- stack: {..., next}
r:mustbe'('
-- stack: {..., "(", next}
assert.eq(r:removeStack(-2).token, '(')
-- stack: {..., next}
local rest = string.trim(r:whatsLeft())
local fn, sys
if rest:match'^"' then
fn, rest = rest:match'^(%b"")%s*(.*)$'
elseif rest:match'^<' then
fn, rest = rest:match'^(%b<>)%s*(.*)$'
sys = true
else
error('expected <> or ""')
end
local repl
if prev == '__has_include' then
repl = self:searchForInclude(fn, sys) and '1' or '0'
elseif prev == '__has_include_next' then
local foundPrevIncludeDir
for i=#self.includeStack,1,-1 do
local includeNextFile = self.includeStack[i]
local dir, prevfn = path(includeNextFile):getdir()
if prevfn.path == fn then
foundPrevIncludeDir = dir.path
break
end
end
repl = self:searchForInclude(fn, sys, foundPrevIncludeDir) and '1' or '0'
end
r:removeStack(-1)
-- stack: {...}
r:setData(rest) -- set new data, pushes next token on the stack
-- stack: {..., next}
r:insertStack(-1, repl)
-- stack: {..., repl, next}
r:mustbe')'
-- stack: {..., repl, ")", next}
assert.eq(r:removeStack(-2).token, ')')
-- stack: {..., repl, next}
elseif r:canbe'defined' then
-- stack: {'defined', next}
assert.eq(r:removeStack(-2).token, 'defined')
-- stack: {next}
local par = r:canbe'('
if par then
-- stack: {'(', next}
assert.eq(r:removeStack(-2).token, '(')
end
-- stack: {next}
local name = r:mustbetype'name'
--DEBUG:print('evaluating defined('..tolua(name)..')')
if par then
r:mustbe')'
-- stack: {name, ')', next}
assert.eq(r:removeStack(-2).token, ')')
-- stack: {name, next}
end
-- stack: {name, next}
assert.eq(r.stack[-2].token, name)
r:replaceStack(-2, -2, self.macros[name] and '1' or '0')
else
-- do 'tryToEval' last to catch all other names we didn't just handle above
if not self:tryToEval(r) then
error("failed to parse expression: "..rest)
end
end
assert.len(r.stack, top+1)
end
function Preproc:level12(r)
local top = #r.stack
if r:canbe'+'
or r:canbe'-'
or r:canbe'!'
or r:canbe'~'
-- prefix ++ and -- go here in C, but I'm betting not in C preprocessor ...
then
self:level13(r)
local op = r.stack[-3].token
-- stack: {'+'|'-'|'!'|'~', a, next}
assert.ge(#r.stack, 3)
assert(op == '+' or op == '-' or op == '!' or op == '~')
local a = castnumber(r.stack[-2].token)
local result
if op == '+' then
result = a
elseif op == '-' then
result = -a
elseif op == '!' then
result = a == 0 and 1 or 0
elseif op == '~' then
result = bit.bnot(a)
else
error'here'
end
r:replaceStack(-3, -2, tostring(result))
else
self:level13(r)
end
assert.len(r.stack, top+1)
end
function Preproc:level11(r)
local top = #r.stack
self:level12(r)
if r:canbe'*' or r:canbe'/' or r:canbe'%' then
self:level11(r)
local op = r.stack[-3].token
-- stack: {a, '*'|'/'|'%', b, next}
assert.ge(#r.stack, 4)
assert(op == '*' or op == '/' or op == '%')
local a = castnumber(r.stack[-4].token)
local b = castnumber(r.stack[-2].token)
local result
if op == '*' then
result = a * b
elseif op == '/' then
result = a / b -- always integer division?
elseif op == '%' then
result = a % b
else
error'here'
end
r:replaceStack(-4, -2, tostring(result))
end
assert.len(r.stack, top+1)
end
function Preproc:level10(r)
local top = #r.stack
self:level11(r)
if r:canbe'+' or r:canbe'-' then
self:level10(r)
local op = r.stack[-3].token
-- stack: {a, '+'|'-', b, next}
assert.ge(#r.stack, 4)
assert(op == '+' or op == '-')
local a = castnumber(r.stack[-4].token)
local b = castnumber(r.stack[-2].token)
local result
if op == '+' then
result = a + b
elseif op == '-' then
result = a - b
else
error'here'
end
r:replaceStack(-4, -2, tostring(result))
end
assert.len(r.stack, top+1)
end
function Preproc:level9(r)
local top = #r.stack
self:level10(r)
if r:canbe'>>' or r:canbe'<<' then
self:level9(r)
local op = r.stack[-3].token
-- stack: {a, '>>'|'<<', b, next}
assert.ge(#r.stack, 4)
assert(op == '>>' or op == '<<')
local a = castnumber(r.stack[-4].token)
local b = castnumber(r.stack[-2].token)
local result
if op == '>>' then
result = bit.rshift(a, b)
elseif op == '<<' then
result = bit.lshift(a, b)
else
error'here'
end
r:replaceStack(-4, -2, tostring(result))
end
assert.len(r.stack, top+1)
end
function Preproc:level8(r)
local top = #r.stack
self:level9(r)
if r:canbe'>='
or r:canbe'<='
or r:canbe'>'
or r:canbe'<'
then
self:level8(r)
local op = r.stack[-3].token
-- stack: {a, '>='|'<='|'>'|'<', b, next}
assert.ge(#r.stack, 4)
assert(op == '>=' or op == '<=' or op == '>' or op == '<')
local a = castnumber(r.stack[-4].token)
local b = castnumber(r.stack[-2].token)
local result
if op == '>=' then
result = a >= b and '1' or '0'
elseif op == '<=' then
result = a <= b and '1' or '0'
elseif op == '>' then
result = a > b and '1' or '0'
elseif op == '<' then
result = a < b and '1' or '0'
else
error'here'
end
r:replaceStack(-4, -2, result)
end
assert.len(r.stack, top+1)
end
function Preproc:level7(r)