-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathlcpp.lua
executable file
·1961 lines (1814 loc) · 56.9 KB
/
lcpp.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
----------------------------------------------------------------------------
--## lcpp - a C-PreProcessor for Lua 5.1 and LuaJIT ffi integration
--
-- Copyright (C) 2012-2014 Michael Schmoock <[email protected]>
--
--### Links
-- * GitHub page: [http://github.com/willsteel/lcpp](http://github.com/willsteel/lcpp)
-- * Project page: [http://lcpp.schmoock.net](http://lcpp.schmoock.net)
-- * Lua: [http://www.lua.org](http://www.lua.org)
-- * LuaJIT: [http://luajit.org](http://luajit.org)
-- * Sponsored by: [http://mmbbq.org](http://mmbbq.org)
--
-- It can be used to pre-process LuaJIT ffi C header file input.
-- It can also be used to preprocess any other code (i.e. Lua itself)
--
-- git clone https://github.com/willsteel/lcpp.git
----------------------------------------------------------------------------
--## USAGE
-- -- load lcpp
-- local lcpp = require("lcpp")
--
-- -- use LuaJIT ffi and lcpp to parse cpp code
-- local ffi = require("ffi")
-- ffi.cdef("#include <your_header.h>")
--
-- -- use lcpp manually but add some predefines
-- local lcpp = require("lcpp");
-- local out = lcpp.compileFile("your_header.h", {UNICODE=1});
-- print(out);
--
-- -- compile some input manually
-- local out = lcpp.compile([[
-- #include "myheader.h"
-- #define MAXPATH 260
-- typedef struct somestruct_t {
-- void* base;
-- size_t size;
-- wchar_t path[MAXPATH];
-- } t_exe;
-- ]])
-- -- the result should be like this
-- out == [[
-- // <preprocessed content of file "myheader.h">
-- typedef struct somestruct_t {
-- void* base;
-- size_t size;
-- wchar_t path[260];
-- } t_exe;
-- ]]
--
-- -- access lcpp defines dynamically (i.e. if used with ffi)
-- local ffi = require("ffi")
-- local lcpp = require("lcpp")
-- ffi.cdef("#include <your_header.h>")
-- =ffi.lcpp_defs.YOUR_DEFINE
--
--
--## This CPPs BNF:
-- RULES:
-- CODE := {LINE}
-- LINE := {STUFF NEWML} STUFF NEWL
-- STUFF := DIRECTIVE | IGNORED_CONTENT
-- DIRECTIVE := OPTSPACES CMD OPTSPACES DIRECTIVE_NAME WHITESPACES DIRECTIVE_CONTENT WHITESPACES NEWL
--
-- LEAVES:
-- NEWL := "\n"
-- NEWL_ESC := "\\n"
-- WHITESPACES := "[ \t]+"
-- OPTSPACES := "[ \t]*"
-- COMMENT := "//(.-)$"
-- MLCOMMENT := "/[*](.-)[*]/"
-- IGNORED_CONTENT := "[^#].*"
-- CMD := "#"
-- DIRECTIVE_NAME := "include"|"define"|"undef"|"if"|"else"|"elif"|"else if"|"endif"|"ifdef"|"ifndef"|"pragma"
-- DIRECTIVE_CONTENT := ".*?"
--
--## TODOs:
-- - lcpp.LCPP_LUA for: load, loadfile
--
--## License (MIT)
-- -----------------------------------------------------------------------------
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- MIT license: http://www.opensource.org/licenses/mit-license.php
-- -----------------------------------------------------------------------------
--
-- @module lcpp
local lcpp = {}
-- check bit is avail or not
local ok, bit = pcall(require, 'bit')
if not ok then
bit = {
lshift = function (x, y)
if y < 0 then return bit.rshift(x,-y) end
return (x * 2^y) % (2^32)
end,
rshift = function (x, y)
if y < 0 then return bit.lshift(x,-y) end
return math.floor(x % (2^32) / (2^y))
end,
bxor = function (x, y)
-- from http://lua-users.org/wiki/BitUtils
local z = 0
for i = 0, 31 do
if (x % 2 == 0) then -- x had a '0' in bit i
if ( y % 2 == 1) then -- y had a '1' in bit i
y = y - 1
z = z + 2 ^ i -- set bit i of z to '1'
end
else -- x had a '1' in bit i
x = x - 1
if (y % 2 == 0) then -- y had a '0' in bit i
z = z + 2 ^ i -- set bit i of z to '1'
else
y = y - 1
end
end
y = y / 2
x = x / 2
end
return z
end,
bnot = function (x)
-- if word size is not defined, I think it better than 0xFFFFFFFF - x.
return -1 - x
end,
band = function (x, y)
return ((x + y) - bit.bxor(x, y)) / 2
end,
bor = function (x, y)
return bit.bnot(bit.band(bit.bnot(x), bit.bnot(y)))
end,
}
end
-- CONFIG
lcpp.LCPP_LUA = false -- whether to use lcpp to preprocess Lua code (load, loadfile, loadstring...)
lcpp.LCPP_FFI = true -- whether to use lcpp as LuaJIT ffi PreProcessor (if used in luaJIT)
lcpp.LCPP_TEST = false -- whether to run lcpp unit tests when loading lcpp module
lcpp.ENV = {} -- static predefines (env-like)
lcpp.FAST = false -- perf. tweaks when enabled. con: breaks minor stuff like __LINE__ macros
lcpp.DEBUG = false
-- PREDEFINES
local __FILE__ = "__FILE__"
local __LINE__ = "__LINE__"
local __DATE__ = "__DATE__"
local __TIME__ = "__TIME__"
local __LCPP_INDENT__ = "__LCPP_INDENT__"
-- BNF LEAVES
local ENDL = "$"
local STARTL = "^"
local NEWL = "\n"
local NEWL_BYTE = NEWL:byte(1)
local NEWL_ESC = "\\"
local NEWML = "\\\n"
local CMD = "#"
local CMD_BYTE = CMD:byte(1)
local COMMENT = "^(.-)//.-$"
local MLCOMMENT = "/[*].-[*]/"
local WHITESPACES = "%s+"
local OPTSPACES = "%s*"
local IDENTIFIER = "[_%a][_%w]*"
local NOIDENTIFIER = "[^%w_]+"
local FILENAME = "[0-9a-zA-Z.%-_/\\]+"
local TEXT = ".+"
local STRINGIFY = "#"
local STRINGIFY_BYTE = STRINGIFY:byte(1)
local STRING_LITERAL = ".*"
-- BNF WORDS
local _INCLUDE = "include"
local _INCLUDE_NEXT = "include_next"
local _DEFINE = "define"
local _IFDEF = "ifdef"
local _IFNDEF = "ifndef"
local _ENDIF = "endif"
local _UNDEF = "undef"
local _IF = "if"
local _ELSE = "else"
local _ELIF = "elif"
local _NOT = "!"
local _ERROR = "error"
local _WARNING = "warning"
local _PRAGMA = "pragma"
-- BNF RULES
local INCLUDE = STARTL.._INCLUDE..WHITESPACES.."[<]("..FILENAME..")[>]"..OPTSPACES..ENDL
local LOCAL_INCLUDE = STARTL.._INCLUDE..WHITESPACES.."[\"]("..FILENAME..")[\"]"..OPTSPACES..ENDL
local INCLUDE_NEXT = STARTL.._INCLUDE_NEXT..WHITESPACES.."[\"<]("..FILENAME..")[\">]"..OPTSPACES..ENDL
local DEFINE = STARTL.._DEFINE
local IFDEF = STARTL.._IFDEF..WHITESPACES.."("..IDENTIFIER..")"..OPTSPACES..ENDL
local IFNDEF = STARTL.._IFNDEF..WHITESPACES.."("..IDENTIFIER..")"..OPTSPACES..ENDL
local ENDIF = STARTL.._ENDIF..OPTSPACES..ENDL
local UNDEF = STARTL.._UNDEF..WHITESPACES.."("..IDENTIFIER..")"..OPTSPACES..ENDL
local IF = STARTL.._IF..WHITESPACES.."(.*)"..ENDL
local ELSE = STARTL.._ELSE..OPTSPACES..ENDL
local ELIF = STARTL.._ELIF..WHITESPACES.."(.*)"..ENDL
local ELSEIF = STARTL.._ELSE..WHITESPACES.._IF..WHITESPACES.."(.*)"..ENDL
local ERROR = STARTL.._ERROR..WHITESPACES.."("..TEXT..")"..OPTSPACES..ENDL
local WARNING = STARTL.._WARNING..WHITESPACES.."("..TEXT..")"..OPTSPACES..ENDL
local ERROR_NOTEXT = STARTL.._ERROR..OPTSPACES..ENDL --> not required when we have POSIX regex
local PRAGMA = STARTL.._PRAGMA
-- speedups
local TRUEMACRO = STARTL.."("..IDENTIFIER..")%s*$"
local REPLMACRO = STARTL.."("..IDENTIFIER..")"..WHITESPACES.."(.+)$"
local FUNCMACRO = STARTL.."("..IDENTIFIER..")%(([_%s%w,]*)%)%s*(.*)"
-- ------------
-- LOCAL UTILS
-- ------------
lcpp.STATE = {lineno = 0} -- current state for debugging the last operation
local function error(msg) _G.print(debug.traceback()); _G.error(string.format("lcpp ERR [%04i] %s", lcpp.STATE.lineno, msg)) end
local function print(msg) _G.print(string.format("lcpp INF [%04i] %s", lcpp.STATE.lineno, msg)) end
-- splits a string using a pattern into a table of substrings
local function gsplit(str, pat)
local function _split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)"..pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
coroutine.yield(cap)
end
last_end = e + 1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
coroutine.yield(cap)
end
end
return coroutine.wrap(function() _split(str, pat) end)
end
local function split(str, pat)
local t = {}
for str in gsplit(str, pat) do table.insert(t, str) end
return t
end
-- Checks whether a string starts with a given substring
-- offset is optional
local function strsw(str, pat, offset)
if not str then return false end
if not offset then offset = 0 end
return string.sub(str, 1+offset, string.len(pat)+offset) == pat
end
-- Checks whether a string ends with a given substring
local function strew(str, pat)
if not str then return false end
return pat=='' or string.sub(str,-string.len(pat)) == pat
end
-- string trim12 from lua wiki
local function trim(str)
local from = str:match"^%s*()"
return from > #str and "" or str:match(".*%S", from)
end
-- returns the number of string occurrences
local function findn(input, what)
local count = 0
local offset = 0
local _
while true do
_, offset = string.find(input, what, offset+1, true)
if not offset then return count end
count = count + 1
end
end
-- C literal string concatenation
local function concatStringLiteral(input)
-- screener does remove multiline definition, so just check ".*"%s*".*" pattern
return input:gsub("\"("..STRING_LITERAL..")\""..OPTSPACES.."\"("..STRING_LITERAL..")\"", "\"%1%2\"")
end
-- c style boolean check (thus, 0 will be false)
local function CBoolean(value)
return value and (value ~= 0)
end
-- eval with c style number parse (UL, LL, L)
local function CEval(expr)
local ok, r = pcall(loadstring, "return " .. parseCInteger(expr))
if ok and r then
return r()
else
error(r)
end
end
-- a lightweight and flexible tokenizer
local function _tokenizer(str, setup)
local defsetup = {
-- EXAMPLE patterns have to be pretended with "^" for the tokenizer
["identifier"] = '^[_%a][_%w]*',
["number"] = '^[%+%-]?%d+[%.]?%d*[UL]*',
["ignore"] = '^%s+',
["string"] = true,
["keywords"] = {
-- ["NAME"] = '^pattern',
-- ...
},
}
if not setup then
setup = defsetup
end
setup.identifier = setup.identifier or defsetup.identifier
setup.number = setup.number or defsetup.number
setup.ignore = setup.ignore or defsetup.ignore
if nil == setup.string then setup.string = true end
setup.keywords = setup.keywords or {}
local strlen = #str
local i = 1
local i1, i2
local keyword
local function find(pat)
i1, i2 = str:find(pat,i)
return i1 ~= nil
end
local function cut()
return str:sub(i, i2)
end
local findKeyword
if setup.keywords_order then
findKeyword = function ()
for _, name in ipairs(setup.keywords_order) do
assert(setup.keywords[name])
local pat = setup.keywords[name]
local result = find(pat)
if result then
keyword = name
return true
end
end
end
else
findKeyword = function ()
for name, pat in pairs(setup.keywords) do
local result = find(pat)
if result then
keyword = name
return true
end
end
end
end
while true do
if i > strlen then return 'eof', nil, strlen, strlen end
if findKeyword() then
coroutine.yield(keyword, cut(), i1, i2)
elseif find(setup.ignore) then
coroutine.yield("ignore", cut(), i1, i2)
elseif find(setup.number) then
coroutine.yield('number', tonumber(cut()), i1, i2)
elseif find(setup.identifier) then
coroutine.yield('identifier', cut(), i1, i2)
elseif setup.string and (find('^"[^"]*"') or find("^'[^']*'")) then
-- strip the quotes
coroutine.yield('string', cut():sub(2,-2), i1, i2)
else -- any other unknown character
i1 = i
i2 = i
coroutine.yield('unknown', cut(), i1, i2)
end
i = i2+1
end
end
local function tokenizer(str, setup)
return coroutine.wrap(function() _tokenizer(str, setup) end)
end
-- ------------
-- PARSER
-- ------------
local LCPP_TOKENIZE_COMMENT = {
string = false,
keywords = {
MLCOMMENT = "^/%*.-%*/",
SLCOMMENT = "^//.-\n",
STRING_LITERAL = '^"[^"]*"',
},
}
-- hint: LuaJIT ffi does not rely on us to remove the comments, but maybe other usecases
local function removeComments(input)
local out = {}
for k, v, start, end_ in tokenizer(input, LCPP_TOKENIZE_COMMENT) do
if k == "MLCOMMENT" then
local newlineCount = findn(input:sub(start, end_), "\n")
local newlines = string.rep("\n", newlineCount)
table.insert(out, newlines)
elseif k == "SLCOMMENT" then
table.insert(out, "\n")
else
table.insert(out, input:sub(start, end_))
end
end
return table.concat(out)
end
-- C style number parse (UL, LL, L) and (octet, hex, binary)
local LCPP_TOKENIZE_INTEGER = {
string = false,
keywords_order = {
"STRING_LITERAL",
"CHAR_LITERAL",
"HEX_LITERAL",
"BIN_LITERAL",
"OCT_LITERAL",
"FPNUM_LITERAL",
"NUMBER_LITERAL",
},
keywords = {
STRING_LITERAL = '^"[^"]*"',
CHAR_LITERAL = "^L'.*'",
HEX_LITERAL = '^[%+%-]?%s*0x[a-fA-F%d]+[UL]*',
BIN_LITERAL = '^[%+%-]?%s*0b%d+[UL]*',
OCT_LITERAL = '^[%+%-]?%s*0%d+[UL]*',
FPNUM_LITERAL = '^[%+%-]?%s*%d+[%.]?%d*e[%+%-]%d*',
NUMBER_LITERAL = '^[%+%-]?%s*%d+[%.]?%d*[UL]+',
},
}
local function parseCInteger(input)
-- print('parseCInteger:input:' .. input)
local out = {}
local unary
for k, v, start, end_ in tokenizer(input, LCPP_TOKENIZE_INTEGER) do
-- print('parseCInteger:' .. k .. "|" .. v)
if k == "CHAR_LITERAL" then
table.insert(out, tostring(string.byte(loadstring("return \"" .. v:gsub("^L%'(.+)%'", "%1") .. "\"")())))
elseif k == "HEX_LITERAL" then
unary, v = v:match('([%+%-]?)0x([a-fA-F%d]+)[UL]*')
local n = tonumber(v, 16)
table.insert(out, unary..tostring(n))
elseif k == "NUMBER_LITERAL" then
v = v:match('([^UL]+)[UL]+')
table.insert(out, v)
elseif k == "BIN_LITERAL" then
unary, v = v:match('([%+%-]?)0b([01]+)[UL]*')
local n = tonumber(v, 2)
table.insert(out, unary..tostring(n))
elseif k == "OCT_LITERAL" then
unary, v = v:match('([%+%-]?)(0%d+)[UL]*')
local n = tonumber(v, 8)
table.insert(out, unary..tostring(n))
else
table.insert(out, input:sub(start, end_))
end
end
local str = table.concat(out)
-- print('parseCInteger:result:'..str)
return str
end
-- screener: revmoce comments, trim, ml concat...
-- it only splits to cpp input lines and removes comments. it does not tokenize.
local function screener(input)
local function _screener(input)
input = removeComments(input)
-- concat mulit-line input.
local count = 1
while count > 0 do input, count = string.gsub(input, "^(.-)\\\n(.-)$", "%1 %2\n") end
-- trim and join blocks not starting with "#"
local buffer = {}
for line in gsplit(input, NEWL) do
--print('newline:'..line)
line = trim(line)
if #line > 0 then
if line:byte(1) == CMD_BYTE then
line = line:gsub("#%s*(.*)", "#%1") -- remove optinal whitespaces after "#". reduce triming later.
if #buffer > 0 then
coroutine.yield(table.concat(buffer, NEWL))
buffer = {}
end
coroutine.yield(line)
else
if lcpp.FAST then
table.insert(buffer, line)
else
coroutine.yield(line)
end
end
elseif not lcpp.FAST then
coroutine.yield(line)
end
end
if #buffer > 0 then
coroutine.yield(table.concat(buffer, NEWL))
end
end
return coroutine.wrap(function() _screener(input) end)
end
-- apply currently known macros to input (and returns it)
local LCPP_TOKENIZE_APPLY_MACRO = {
keywords = {
DEFINED = "^defined%s*%(%s*"..IDENTIFIER.."%s*%)" ,
},
}
local function apply(state, input)
while true do
local out = {}
local functions = {}
local expand
for k, v, start, end_ in tokenizer(input, LCPP_TOKENIZE_APPLY_MACRO) do
-- print('tokenize:'..tostring(k).."|"..tostring(v))
if k == "identifier" then
local repl = v
local macro = state.defines[v]
if macro then
if type(macro) == "boolean" then
repl = ""
expand = true
elseif type(macro) == "string" then
repl = macro
expand = (repl ~= v)
elseif type(macro) == "number" then
repl = tostring(macro)
expand = (repl ~= v)
elseif type(macro) == "function" then
local decl,cnt = input:sub(start):gsub("^[_%a][_%w]*%s*%b()", "%1")
-- print('matching:'..input.."|"..decl.."|"..cnt)
if cnt > 0 then
repl = macro(decl)
-- print("d&r:"..decl.."|"..repl)
expand = true
table.insert(out, repl)
table.insert(out, input:sub(end_ + #decl))
break
else
if input:sub(start):find("^[_%a][_%w]*%s*%(") then
-- that is part of functional macro declaration.
-- print(v ..': cannot replace:<'..input..'> read more line')
return input,true
else
-- on macro name is also used as the symbol of some C declaration
-- (e.g. /usr/include/spawn.h, /usr/include/sys/select.h on centos 6.4)
-- no need to preprocess.
print(v .. ': macro name but used as C declaration in:' .. input)
end
end
end
end
table.insert(out, repl)
elseif k == "DEFINED" then
table.insert(out, input:sub(start, end_))
else
table.insert(out, input:sub(start, end_))
end
end
input = table.concat(out)
if not expand then
break
end
end
-- C liberal string concatenation, processing U,L,UL,LL
return parseCInteger(concatStringLiteral(input)),false
end
-- processes an input line. called from lcpp doWork loop
local function processLine(state, line)
if not line or #line == 0 then return line end
local cmd = nil
if line:byte(1) == CMD_BYTE then cmd = line:sub(2) end
-- print("process:"..line)--.."|"..tostring(state:skip()))
--[[ IF/THEN/ELSE STRUCTURAL BLOCKS ]]--
if cmd then
local ifdef = cmd:match(IFDEF)
local ifexp = cmd:match(IF)
local ifndef = cmd:match(IFNDEF)
local elif = cmd:match(ELIF)
local elseif_ = cmd:match(ELSEIF)
local else_ = cmd:match(ELSE)
local endif = cmd:match(ENDIF)
local struct = ifdef or ifexp or ifndef or elif or elseif_ or else_ or endif
if struct then
local skip = state:skip()
if ifdef then state:openBlock(state:defined(ifdef)) end
-- if skipped, it may have undefined expression. so not parse them
if ifexp then state:openBlock(skip and true or CBoolean(state:parseExpr(ifexp))) end
if ifndef then state:openBlock(not state:defined(ifndef)) end
if elif then state:elseBlock((skip and skip < #state.stack) and true or CBoolean(state:parseExpr(elif))) end
if elseif_ then state:elseBlock((skip and skip < #state.stack) and true or CBoolean(state:parseExpr(elseif_))) end
if else_ then state:elseBlock(true) end
if endif then state:closeBlock() end
return -- remove structural directives
end
end
--[[ SKIPPING ]]--
if state:skip() then
-- print('skip:' .. line)
return
end
--[[ READ NEW DIRECTIVES ]]--
if cmd then
-- handle #undef ...
local key = cmd:match(UNDEF)
if type(key) == "string" then
state:undefine(key)
return
end
-- read "#define >FooBar...<" directives
if cmd:match(DEFINE) then
local define = trim(cmd:sub(DEFINE:len()+1))
local macroname, replacement
-- simple "true" defines
macroname = define:match(TRUEMACRO)
if macroname then
state:define(macroname, true)
else
-- replace macro defines
macroname, replacement = define:match(REPLMACRO)
if macroname and replacement then
state:define(macroname, replacement)
else
-- read functional macros
macroname, replacement, source = state:parseFunction(define)
if macroname and replacement then
-- add original text for definition to check identify
state:define(macroname, replacement, false, source)
end
end
end
return
end
-- handle #include ...
local filename = cmd:match(INCLUDE)
if filename then
return state:includeFile(filename)
end
local filename = cmd:match(LOCAL_INCLUDE)
if filename then
return state:includeFile(filename, false, true)
end
local filename = cmd:match(INCLUDE_NEXT)
if filename then
--print("include_next:"..filename)
return state:includeFile(filename, true)
end
-- ignore, because we dont have any pragma directives yet
if cmd:match(PRAGMA) then return end
-- handle #error
local errMsg = cmd:match(ERROR)
local errNoTxt = cmd:match(ERROR_NOTEXT)
local warnMsg = cmd:match(WARNING)
if errMsg then error(errMsg) end
if errNoTxt then error("<ERROR MESSAGE NOT SET>") end
if warnMsg then
print(warnMsg)
return
end
-- abort on unknown keywords
error("unknown directive: "..line)
end
if state.incompleteLine then
--print('merge with incompleteLine:'..state.incompleteLine)
line = (state.incompleteLine .. line)
state.incompleteLine = nil
end
--[[ APPLY MACROS ]]--
-- print(line)
local _line,more = state:apply(line);
-- print('endprocess:'.._line)
if more then
state.incompleteLine = line
return ""
else
return _line
end
return line
end
local function doWork(state)
local function _doWork(state)
if not state:defined(__FILE__) then state:define(__FILE__, "<USER_CHUNK>", true) end
local oldIndent = state:getIndent()
while true do
local input = state:getLine()
if not input then break end
local output = processLine(state, input)
if not lcpp.FAST and not output then output = "" end -- output empty skipped lines
if lcpp.DEBUG then output = output.." -- "..input end -- input as comment when DEBUG
if output then coroutine.yield(output) end
end
if (oldIndent ~= state:getIndent()) then error("indentation level must be balanced within a file. was:"..oldIndent.." is:"..state:getIndent()) end
end
return coroutine.wrap(function() _doWork(state) end)
end
local function includeFile(state, filename, next, _local)
local result, result_state = lcpp.compileFile(filename, state.defines, state.macro_sources, next, _local)
-- now, we take the define table of the sub file for further processing
state.defines = result_state.defines
-- and return the compiled result
return result
end
-- sets a global define
local function define(state, key, value, override, macro_source)
--print("define:"..key.." type:"..tostring(value).." value:"..tostring(pval))
if value and not override then
if type(value) == 'function' then
assert(macro_source, "macro source should specify to check identity")
local pval = state.macro_sources[key]
if pval and (pval ~= macro_source) then error("already defined: "..key) end
state.macro_sources[key] = macro_source
else
local pval = state.defines[key]
if pval and (pval ~= value) then error("already defined: "..key) end
end
end
state.defines[key] = state:prepareMacro(value)
end
-- parses CPP exressions
-- i.e.: #if !defined(_UNICODE) && !defined(UNICODE)
--
--BNF:
-- EXPR -> (BRACKET_OPEN)(EXPR)(BRACKET_CLOSE)
-- EXPR -> (EXPR)(OR)(EXPR)
-- EXPR -> (EXPR)(AND)(EXPR)
-- EXPR -> (NOT)(EXPR)
-- EXPR -> (FUNCTION)
-- FUNCTION -> (IDENTIFIER)(BRACKET_OPEN)(ARGS)(BRACKET_CLOSE)
-- ARGS -> ((IDENTIFIER)[(COMMA)(IDENTIFIER)])?
--LEAVES:
-- IGNORE -> " \t"
-- BRACKET_OPEN -> "("
-- BRACKET_CLOSE -> ")"
-- OR -> "||"
-- AND -> "&&"
-- NOT -> "!"
-- IDENTIFIER -> "[0-9a-zA-Z_]"
--
local LCPP_TOKENIZE_MACRO = {
string = true,
keywords_order = {
"CONCAT",
"SPACE",
},
keywords = {
CONCAT = "^%s*##%s*",
SPACE = "^%s",
},
}
local LCPP_TOKENIZE_MACRO_ARGS = {
string = true,
keywords_order = {
"STRING_LITERAL",
"PARENTHESE",
"FUNCTIONAL",
"ARGS",
"SINGLE_CHARACTER_ARGS",
"COMMA",
},
keywords = {
PARENTHESE = "^%s*%b()",
FUNCTIONAL = "^".. IDENTIFIER .. "%s*%b()",
STRING_LITERAL = '^"[^"]*"',
ARGS = "^[^,%s][^,]*[^,%s]",
SINGLE_CHARACTER_ARGS = "^[^,%s]",
COMMA = "^,",
},
}
local LCPP_TOKENIZE_EXPR = {
string = false,
keywords_order = {
"DEFINED",
"FUNCTIONAL_MACRO",
"BROPEN",
"BRCLOSE",
"TENARY_START",
"TENARY_MIDDLE",
-- binary operators
"EQUAL",
"NOT_EQUAL",
"AND",
"OR",
"BAND",
"BOR",
"BXOR",
"PLUS",
"MINUS",
"MULTIPLY",
"DIV",
"MOD",
"LTE",
"MTE",
"LSHIFT",
"RSHIFT",
"LT",
"MT",
-- unary operator
"NOT",
"BNOT",
-- literal
"STRING_LITERAL",
"CHAR_LITERAL",
"HEX_LITERAL",
"FPNUM_LITERAL",
"NUMBER_LITERAL",
},
keywords = {
DEFINED = '^defined',
FUNCTIONAL_MACRO = '^' .. IDENTIFIER .. "%s*%b()",
BROPEN = '^[(]',
BRCLOSE = '^[)]',
TENARY_START = '^%?',
TENARY_MIDDLE = '^%:',
EQUAL = '^==',
NOT_EQUAL = '^!=',
AND = '^&&',
OR = '^||',
BAND = '^&',
BOR = '^|',
BXOR = '^%^',
PLUS = '^%+',
MINUS = '^%-',
MULTIPLY = '^%*',
DIV = '^%/',
MOD = '^%%',
LTE = '^<=',
MTE = '^>=',
LSHIFT = '^<<',
RSHIFT = '^>>',
LT = '^<',
MT = '^>',
NOT = '^!',
BNOT = '^~',
STRING_LITERAL = '^L?"[^"]*"',
CHAR_LITERAL = "^L?'.*'",
HEX_LITERAL = '^[%+%-]?0?x[a-fA-F%d]+[UL]*',
FPNUM_LITERAL = '^[%+%-]?%d+[%.]?%d*e[%+%-]%d*',
NUMBER_LITERAL = '^[%+%-]?0?b?%d+[%.]?%d*[UL]*',
},
}
local function parseDefined(state, input)
local result = false
local bropen = false
local brclose = false
local ident = nil
for key, value in input do
if key == "BROPEN" then
bropen = true
end
if key == "identifier" then
ident = value
if not bropen then break end
end
if key == "BRCLOSE" and ident then
brclose = true
break
end
end
-- wiht and w/o brackets allowed
if ident and ((bropen and brclose) or (not bropen and not brclose)) then
return state:defined(ident)
end
error("expression parse error: defined(ident)")
end
--[[
order : smaller is higher priority
1 () [] -> .
2 ! ~ - + * & sizeof type cast ++ --
3 * / %
4 + -
5 << >>
6 < <= > >=
7 == !=
8 &
9 ^
10 |
11 &&
12 ||
13 ?: = += -= *= /= %= &= |= ^= <<= >>=
14 ,
]]
local combination_order = function (op, unary)
if unary then
if op == '-' or op == '!' or op == '~' then
return 2
else
assert(false, 'unsupported unary operator:' .. op)
end
else
if op == '*' or op == '/' or op == '%' then
return 3
elseif op == '+' or op == '-' then
return 4
elseif op == '>>' or op == '<<' then
return 5
elseif op == '<' or op == '>' or op == '<=' or op == '>=' then
return 6
elseif op == '==' or op == '!=' then
return 7
elseif op == '&' then
return 8
elseif op == '^' then
return 9
elseif op == '|' then
return 10
elseif op == '&&' then
return 11
elseif op == '||' then
return 12
elseif op == '?' or op == ':' then
return 13
else
assert(false, 'unsupported operator:' .. op)
end
end
end
local evaluate
evaluate = function (node)
if not node.op then -- leaf node or leaf node with unary operators
local v = node.v
if node.uops then
for _, uop in ipairs(node.uops) do
-- print('apply uop:'..uop.."|"..tostring(v))
if uop == '-' then
v = -v
elseif uop == '!' then
v = (not v)
elseif uop == '~' then
v = bit.bnot(v)
else
assert(false, 'invalid uop:' .. tostring(uop))
end
end
end
-- print('after apply:'..tostring(v))
return v