forked from nim-lang/c2nim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cparse.nim
2672 lines (2477 loc) · 86.1 KB
/
cparse.nim
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
#
#
# c2nim - C to Nim source converter
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module implements an Ansi C / C++ parser.
## It translates a C source file into a Nim AST. Then the renderer can be
## used to convert the AST to its text representation.
# TODO
# - implement handling of '::': function declarations
# - support '#if' in classes
import
os, compiler/llstream, compiler/renderer, clex, compiler/idents, strutils,
pegs, compiler/ast, compiler/astalgo, compiler/msgs,
compiler/options, strtabs, hashes, algorithm
import pegs except Token, Tokkind
type
ParserFlag* = enum
pfRefs, ## use "ref" instead of "ptr" for C's typ*
pfCDecl, ## annotate procs with cdecl
pfStdCall, ## annotate procs with stdcall
pfSkipInclude, ## skip all ``#include``
pfTypePrefixes, ## all generated types start with 'T' or 'P'
pfSkipComments, ## do not generate comments
pfCpp, ## process C++
pfIgnoreRValueRefs, ## transform C++'s 'T&&' to 'T'
pfKeepBodies, ## do not skip C++ method bodies
pfAssumeIfIsTrue, ## assume #if is true
pfStructStruct ## do not treat struct Foo Foo as a forward decl
Macro = object
name: string
params: int # number of parameters; 0 for empty (); -1 for no () at all
body: seq[ref Token] # can contain pxMacroParam tokens
ParserOptions = object ## shared parser state!
flags*: set[ParserFlag]
prefixes, suffixes: seq[string]
assumeDef, assumenDef: seq[string]
mangleRules: seq[tuple[pattern: Peg, frmt: string]]
privateRules: seq[Peg]
dynlibSym, headerOverride: string
macros: seq[Macro]
toMangle: StringTableRef
classes: StringTableRef
toPreprocess: StringTableRef
inheritable: StringTableRef
debugMode, followNep1, useHeader: bool
discardablePrefixes: seq[string]
constructor, destructor, importcLit: string
exportPrefix*: string
PParserOptions* = ref ParserOptions
Parser* = object
lex: Lexer
tok: ref Token # current token
header: string
options: PParserOptions
backtrack: seq[ref Token]
inTypeDef: int
scopeCounter: int
hasDeadCodeElimPragma: bool
currentClass: PNode # type that needs to be added as 'this' parameter
currentClassOrig: string # original class name
currentNamespace: string
inAngleBracket: int
lastConstType: PNode # another hack to be able to translate 'const Foo& foo'
# to 'foo: Foo' and not 'foo: var Foo'.
ReplaceTuple* = array[0..1, string]
ERetryParsing = object of Exception
SectionParser = proc(p: var Parser): PNode {.nimcall.}
proc parseDir(p: var Parser; sectionParser: SectionParser): PNode
proc addTypeDef(section, name, t, genericParams: PNode)
proc parseStruct(p: var Parser, stmtList: PNode, isUnion: bool): PNode
proc parseStructBody(p: var Parser, stmtList: PNode, isUnion: bool,
kind: TNodeKind = nkRecList): PNode
proc newParserOptions*(): PParserOptions =
new(result)
result.prefixes = @[]
result.suffixes = @[]
result.assumeDef = @[]
result.assumenDef = @["__cplusplus"]
result.macros = @[]
result.mangleRules = @[]
result.privateRules = @[]
result.discardablePrefixes = @[]
result.flags = {}
result.dynlibSym = ""
result.headerOverride = ""
result.toMangle = newStringTable(modeCaseSensitive)
result.classes = newStringTable(modeCaseSensitive)
result.toPreprocess = newStringTable(modeCaseSensitive)
result.inheritable = newStringTable(modeCaseSensitive)
result.constructor = "construct"
result.destructor = "destroy"
result.importcLit = "importc"
result.exportPrefix = ""
proc setOption*(parserOptions: PParserOptions, key: string, val=""): bool =
result = true
case key.normalize
of "ref": incl(parserOptions.flags, pfRefs)
of "dynlib": parserOptions.dynlibSym = val
of "header":
parserOptions.useHeader = true
if val.len > 0: parserOptions.headerOverride = val
of "cdecl": incl(parserOptions.flags, pfCdecl)
of "stdcall": incl(parserOptions.flags, pfStdCall)
of "prefix": parserOptions.prefixes.add(val)
of "suffix": parserOptions.suffixes.add(val)
of "assumedef": parserOptions.assumeDef.add(val)
of "assumendef": parserOptions.assumenDef.add(val)
of "skipinclude": incl(parserOptions.flags, pfSkipInclude)
of "typeprefixes": incl(parserOptions.flags, pfTypePrefixes)
of "skipcomments": incl(parserOptions.flags, pfSkipComments)
of "cpp":
incl(parserOptions.flags, pfCpp)
parserOptions.importcLit = "importcpp"
of "keepbodies": incl(parserOptions.flags, pfKeepBodies)
of "ignorervaluerefs": incl(parserOptions.flags, pfIgnoreRValueRefs)
of "class": parserOptions.classes[val] = "true"
of "debug": parserOptions.debugMode = true
of "nep1": parserOptions.followNep1 = true
of "constructor": parserOptions.constructor = val
of "destructor": parserOptions.destructor = val
of "assumeifistrue": incl(parserOptions.flags, pfAssumeIfIsTrue)
of "discardableprefix": parserOptions.discardablePrefixes.add(val)
of "structstruct": incl(parserOptions.flags, pfStructStruct)
else: result = false
proc parseUnit*(p: var Parser): PNode
proc openParser*(p: var Parser, filename: string,
inputStream: PLLStream, options = newParserOptions()) =
openLexer(p.lex, filename, inputStream)
p.options = options
p.header = filename.extractFilename
p.lex.debugMode = options.debugMode
p.backtrack = @[]
p.currentNamespace = ""
p.currentClassOrig = ""
new(p.tok)
proc parMessage(p: Parser, msg: TMsgKind, arg = "") =
lexMessage(p.lex, msg, arg)
proc closeParser*(p: var Parser) = closeLexer(p.lex)
proc saveContext(p: var Parser) = p.backtrack.add(p.tok)
# EITHER call 'closeContext' or 'backtrackContext':
proc closeContext(p: var Parser) = discard p.backtrack.pop()
proc backtrackContext(p: var Parser) = p.tok = p.backtrack.pop()
proc rawGetTok(p: var Parser) =
if p.tok.next != nil:
p.tok = p.tok.next
elif p.backtrack.len == 0:
p.tok.next = nil
getTok(p.lex, p.tok[])
else:
# We need the next token and must be able to backtrack. So we need to
# allocate a new token.
var t: ref Token
new(t)
getTok(p.lex, t[])
p.tok.next = t
p.tok = t
proc insertAngleRi(currentToken: ref Token) =
var t: ref Token
new(t)
t.xkind = pxAngleRi
t.next = currentToken.next
currentToken.next = t
proc findMacro(p: Parser): int =
for i in 0..high(p.options.macros):
if p.tok.s == p.options.macros[i].name: return i
return -1
proc rawEat(p: var Parser, xkind: Tokkind) =
if p.tok.xkind == xkind: rawGetTok(p)
else: parMessage(p, errTokenExpected, tokKindToStr(xkind))
proc parseMacroArguments(p: var Parser): seq[seq[ref Token]] =
result = @[]
result.add(@[])
var i: array[pxParLe..pxCurlyLe, int]
var L = 0
# we push a context here, so that no token will be overwritten, but we get
# fresh tokens instead:
saveContext(p)
while true:
var kind = p.tok.xkind
case kind
of pxEof: rawEat(p, pxParRi)
of pxParLe, pxBracketLe, pxCurlyLe:
inc(i[kind])
result[L].add(p.tok)
of pxParRi:
# end of arguments?
if i[pxParLe] == 0 and i[pxBracketLe] == 0 and i[pxCurlyLe] == 0: break
if i[pxParLe] > 0: dec(i[pxParLe])
result[L].add(p.tok)
of pxBracketRi, pxCurlyRi:
kind = pred(kind, 3)
if i[kind] > 0: dec(i[kind])
result[L].add(p.tok)
of pxComma:
if i[pxParLe] == 0 and i[pxBracketLe] == 0 and i[pxCurlyLe] == 0:
# next argument: comma is not part of the argument
result.add(@[])
inc(L)
else:
# comma does not separate different arguments:
result[L].add(p.tok)
else:
result[L].add(p.tok)
rawGetTok(p)
closeContext(p)
proc expandMacro(p: var Parser, m: Macro) =
rawGetTok(p) # skip macro name
var arguments: seq[seq[ref Token]]
if m.params >= 0:
rawEat(p, pxParLe)
if m.params > 0:
arguments = parseMacroArguments(p)
if arguments.len != m.params:
parMessage(p, errWrongNumberOfArguments)
rawEat(p, pxParRi)
# insert into the token list:
if m.body.len > 0:
var newList: ref Token
new(newList)
var lastTok = newList
var mergeToken = false
template appendTok(t) {.dirty.} =
if mergeToken:
mergeToken = false
lastTok.s &= t.s
else:
lastTok.next = t
lastTok = t
for tok in items(m.body):
if tok.xkind == pxMacroParam:
# it can happen that parameters are expanded multiple times:
# #def foo(x) x x
# Therefore we have to copy the token here to avoid wrong aliasing
# that leads to an invalid token sequence:
for t in items(arguments[int(tok.iNumber)]):
var newToken: ref Token
new(newToken); newToken[] = t[]
appendTok(newToken)
elif tok.xkind == pxDirConc:
# implement token merging:
mergeToken = true
elif tok.xkind == pxMacroParamToStr:
var newToken: ref Token
new(newToken)
newToken.xkind = pxStrLit; newToken.s = ""
for t in items(arguments[int(tok.iNumber)]):
newToken.s &= $t[]
appendTok(newToken)
else:
appendTok(tok)
lastTok.next = p.tok
p.tok = newList.next
proc getTok(p: var Parser) =
rawGetTok(p)
while p.tok.xkind == pxSymbol:
var idx = findMacro(p)
if idx >= 0:
expandMacro(p, p.options.macros[idx])
else:
break
proc parLineInfo(p: Parser): TLineInfo =
result = getLineInfo(p.lex)
proc skipComAux(p: var Parser, n: PNode) =
if n != nil and n.kind != nkEmpty:
if pfSkipComments notin p.options.flags:
if n.comment == nil: n.comment = p.tok.s
else: add(n.comment, "\n" & p.tok.s)
else:
parMessage(p, warnCommentXIgnored, p.tok.s)
getTok(p)
proc skipCom(p: var Parser, n: PNode) =
while p.tok.xkind in {pxLineComment, pxStarComment}: skipComAux(p, n)
proc skipStarCom(p: var Parser, n: PNode) =
while p.tok.xkind == pxStarComment: skipComAux(p, n)
proc getTok(p: var Parser, n: PNode) =
getTok(p)
skipCom(p, n)
proc expectIdent(p: Parser) =
if p.tok.xkind != pxSymbol:
parMessage(p, errIdentifierExpected, debugTok(p.lex, p.tok[]))
proc eat(p: var Parser, xkind: Tokkind, n: PNode) =
if p.tok.xkind == xkind: getTok(p, n)
else: parMessage(p, errTokenExpected, tokKindToStr(xkind))
proc eat(p: var Parser, xkind: Tokkind) =
if p.tok.xkind == xkind: getTok(p)
else: parMessage(p, errTokenExpected, tokKindToStr(xkind))
proc eat(p: var Parser, tok: string, n: PNode) =
if p.tok.s == tok: getTok(p, n)
else: parMessage(p, errTokenExpected, tok)
proc opt(p: var Parser, xkind: Tokkind, n: PNode) =
if p.tok.xkind == xkind: getTok(p, n)
proc addSon(father, a, b: PNode) =
addSon(father, a)
addSon(father, b)
proc addSon(father, a, b, c: PNode) =
addSon(father, a)
addSon(father, b)
addSon(father, c)
proc newNodeP(kind: TNodeKind, p: Parser): PNode =
result = newNodeI(kind, getLineInfo(p.lex))
proc newIntNodeP(kind: TNodeKind, intVal: BiggestInt, p: Parser): PNode =
result = newNodeP(kind, p)
result.intVal = intVal
proc newFloatNodeP(kind: TNodeKind, floatVal: BiggestFloat,
p: Parser): PNode =
result = newNodeP(kind, p)
result.floatVal = floatVal
proc newStrNodeP(kind: TNodeKind, strVal: string, p: Parser): PNode =
result = newNodeP(kind, p)
result.strVal = strVal
proc newIdentNodeP(ident: PIdent, p: Parser): PNode =
result = newNodeP(nkIdent, p)
result.ident = ident
proc newIdentNodeP(ident: string, p: Parser): PNode =
assert(not ident.isNil)
result = newIdentNodeP(getIdent(ident), p)
proc newIdentPair(a, b: string, p: Parser): PNode =
result = newNodeP(nkExprColonExpr, p)
addSon(result, newIdentNodeP(a, p))
addSon(result, newIdentNodeP(b, p))
proc newIdentStrLitPair(a, b: string, p: Parser): PNode =
result = newNodeP(nkExprColonExpr, p)
addSon(result, newIdentNodeP(a, p))
addSon(result, newStrNodeP(nkStrLit, b, p))
include rules
proc newBinary(opr: string, a, b: PNode, p: Parser): PNode =
result = newNodeP(nkInfix, p)
addSon(result, newIdentNodeP(getIdent(opr), p))
addSon(result, a)
addSon(result, b)
proc skipIdent(p: var Parser; kind: TSymKind): PNode =
expectIdent(p)
result = mangledIdent(p.tok.s, p, kind)
getTok(p, result)
proc skipIdentExport(p: var Parser; kind: TSymKind): PNode =
expectIdent(p)
result = exportSym(p, mangledIdent(p.tok.s, p, kind), p.tok.s)
getTok(p, result)
proc markTypeIdent(p: var Parser, typ: PNode) =
if pfTypePrefixes in p.options.flags:
var prefix = ""
if typ == nil or typ.kind == nkEmpty:
prefix = "T"
else:
var t = typ
while t != nil and t.kind in {nkVarTy, nkPtrTy, nkRefTy}:
prefix.add('P')
t = t.sons[0]
if prefix.len == 0: prefix.add('T')
expectIdent(p)
p.options.toMangle[p.tok.s] = prefix & mangleRules(p.tok.s, p, skType)
# --------------- parser -----------------------------------------------------
# We use this parsing rule: If it looks like a declaration, it is one. This
# avoids to build a symbol table, which can't be done reliably anyway for our
# purposes.
proc expression(p: var Parser, rbp: int = 0): PNode
proc constantExpression(p: var Parser): PNode = expression(p, 40)
proc assignmentExpression(p: var Parser): PNode = expression(p, 30)
proc compoundStatement(p: var Parser; newScope=true): PNode
proc statement(p: var Parser): PNode
proc declKeyword(p: Parser, s: string): bool =
# returns true if it is a keyword that introduces a declaration
case s
of "extern", "static", "auto", "register", "const", "volatile", "restrict",
"inline", "__inline", "__cdecl", "__stdcall", "__syscall", "__fastcall",
"__safecall", "void", "struct", "union", "enum", "typedef", "size_t",
"short", "int", "long", "float", "double", "signed", "unsigned", "char":
result = true
of "class", "mutable":
result = p.options.flags.contains(pfCpp)
else: discard
proc stmtKeyword(s: string): bool =
case s
of "if", "for", "while", "do", "switch", "break", "continue", "return",
"goto":
result = true
else: discard
# ------------------- type desc -----------------------------------------------
proc typeDesc(p: var Parser): PNode
proc isIntType(s: string): bool =
case s
of "short", "int", "long", "float", "double", "signed", "unsigned", "size_t":
result = true
else: discard
proc skipConst(p: var Parser): bool {.discardable.} =
while p.tok.xkind == pxSymbol and
(p.tok.s == "const" or p.tok.s == "volatile" or p.tok.s == "restrict" or
(p.tok.s == "mutable" and pfCpp in p.options.flags)):
if p.tok.s == "const": result = true
getTok(p, nil)
proc isTemplateAngleBracket(p: var Parser): bool =
if pfCpp notin p.options.flags: return false
saveContext(p)
getTok(p, nil) # skip "<"
var i: array[pxParLe..pxCurlyLe, int]
var angles = 0
while true:
let kind = p.tok.xkind
case kind
of pxEof: break
of pxParLe, pxBracketLe, pxCurlyLe: inc(i[kind])
of pxGt, pxAngleRi:
# end of arguments?
if i[pxParLe] == 0 and i[pxBracketLe] == 0 and i[pxCurlyLe] == 0 and
angles == 0:
# mark as end token:
p.tok.xkind = pxAngleRi
result = true;
break
if angles > 0: dec(angles)
of pxShr:
# >> can end a template too:
if i[pxParLe] == 0 and i[pxBracketLe] == 0 and i[pxCurlyLe] == 0 and
angles == 1:
p.tok.xkind = pxAngleRi
insertAngleRi(p.tok)
result = true
break
if angles > 1: dec(angles, 2)
of pxLt: inc(angles)
of pxParRi, pxBracketRi, pxCurlyRi:
let kind = pred(kind, 3)
if i[kind] > 0: dec(i[kind])
else: break
of pxSemicolon: break
else: discard
getTok(p, nil)
backtrackContext(p)
proc optScope(p: var Parser, n: PNode; kind: TSymKind): PNode =
result = n
if pfCpp in p.options.flags:
while p.tok.xkind == pxScope:
when true:
getTok(p, result)
expectIdent(p)
result = mangledIdent(p.tok.s, p, kind)
else:
let a = result
result = newNodeP(nkDotExpr, p)
result.add(a)
getTok(p, result)
expectIdent(p)
result.add(mangledIdent(p.tok.s, p, kind))
getTok(p, result)
proc optAngle(p: var Parser, n: PNode): PNode =
if p.tok.xkind == pxLt and isTemplateAngleBracket(p):
getTok(p)
result = newNodeP(nkBracketExpr, p)
result.add(n)
inc p.inAngleBracket
while true:
let a = if p.tok.xkind == pxSymbol: typeDesc(p)
else: assignmentExpression(p)
if not a.isNil: result.add(a)
if p.tok.xkind != pxComma: break
getTok(p)
dec p.inAngleBracket
eat(p, pxAngleRi)
result = optScope(p, result, skType)
else:
result = n
proc typeAtom(p: var Parser): PNode =
var isConst = skipConst(p)
expectIdent(p)
case p.tok.s
of "void":
result = newNodeP(nkNilLit, p) # little hack
getTok(p, nil)
of "struct", "union", "enum":
getTok(p, nil)
result = skipIdent(p, skType)
elif isIntType(p.tok.s):
var x = ""
#getTok(p, nil)
var isUnsigned = false
var isSizeT = false
while p.tok.xkind == pxSymbol and (isIntType(p.tok.s) or p.tok.s == "char"):
if p.tok.s == "unsigned":
isUnsigned = true
elif p.tok.s == "size_t":
isSizeT = true
elif p.tok.s == "signed" or p.tok.s == "int":
discard
else:
add(x, p.tok.s)
getTok(p, nil)
if skipConst(p): isConst = true
if x.len == 0: x = "int"
let xx = if isSizeT: "csize" elif isUnsigned: "cu" & x else: "c" & x
result = mangledIdent(xx, p, skDontMangle)
else:
result = mangledIdent(p.tok.s, p, skType)
getTok(p, result)
result = optScope(p, result, skType)
result = optAngle(p, result)
if isConst: p.lastConstType = result
proc newPointerTy(p: Parser, typ: PNode): PNode =
if pfRefs in p.options.flags:
result = newNodeP(nkRefTy, p)
else:
result = newNodeP(nkPtrTy, p)
result.addSon(typ)
proc pointer(p: var Parser, a: PNode): PNode =
result = a
var i = 0
let isConstA = skipConst(p)
while true:
if p.tok.xkind == pxStar:
inc(i)
getTok(p, result)
skipConst(p)
result = newPointerTy(p, result)
elif p.tok.xkind == pxAmp and pfCpp in p.options.flags:
getTok(p, result)
let isConstB = skipConst(p)
if isConstA or isConstB or p.lastConstType == result:
discard "transform 'const Foo&' to just 'Foo'"
else:
let b = result
result = newNodeP(nkVarTy, p)
result.add(b)
elif p.tok.xkind == pxAmpAmp and pfCpp in p.options.flags:
getTok(p, result)
skipConst(p)
if pfIgnoreRvalueRefs notin p.options.flags:
let b = result
result = newNodeP(nkVarTy, p)
result.add(b)
else: break
if a.kind == nkIdent and a.ident.s == "char":
if i >= 2:
result = newIdentNodeP("cstringArray", p)
for j in 1..i-2: result = newPointerTy(p, result)
elif i == 1: result = newIdentNodeP("cstring", p)
elif a.kind == nkNilLit and i > 0:
result = newIdentNodeP("pointer", p)
for j in 1..i-1: result = newPointerTy(p, result)
proc newProcPragmas(p: Parser): PNode =
result = newNodeP(nkPragma, p)
if pfCDecl in p.options.flags:
addSon(result, newIdentNodeP("cdecl", p))
elif pfStdCall in p.options.flags:
addSon(result, newIdentNodeP("stdcall", p))
proc addPragmas(father, pragmas: PNode) =
if sonsLen(pragmas) > 0: addSon(father, pragmas)
else: addSon(father, ast.emptyNode)
proc addReturnType(params, rettyp: PNode): bool =
if rettyp == nil: addSon(params, ast.emptyNode)
elif rettyp.kind != nkNilLit:
addSon(params, rettyp)
result = true
else: addSon(params, ast.emptyNode)
proc addDiscardable(origName: string; pragmas: PNode; p: Parser) =
for prefix in p.options.discardablePrefixes:
if origName.startsWith(prefix):
addSon(pragmas, newIdentNodeP("discardable", p))
proc parseFormalParams(p: var Parser, params, pragmas: PNode)
proc parseTypeSuffix(p: var Parser, typ: PNode): PNode =
result = typ
case p.tok.xkind
of pxBracketLe:
getTok(p, result)
skipConst(p) # POSIX contains: ``int [restrict]``
if p.tok.xkind != pxBracketRi:
var tmp = result
var index = expression(p)
# array type:
result = newNodeP(nkBracketExpr, p)
addSon(result, newIdentNodeP("array", p))
addSon(result, index)
eat(p, pxBracketRi, result)
addSon(result, parseTypeSuffix(p, tmp))
else:
# pointer type:
var tmp = result
if pfRefs in p.options.flags:
result = newNodeP(nkRefTy, p)
else:
result = newNodeP(nkPtrTy, p)
eat(p, pxBracketRi, result)
addSon(result, parseTypeSuffix(p, tmp))
of pxParLe:
# function pointer:
var procType = newNodeP(nkProcTy, p)
var pragmas = newProcPragmas(p)
var params = newNodeP(nkFormalParams, p)
discard addReturnType(params, result)
parseFormalParams(p, params, pragmas)
addSon(procType, params)
addPragmas(procType, pragmas)
result = parseTypeSuffix(p, procType)
else: discard
proc typeDesc(p: var Parser): PNode = pointer(p, typeAtom(p))
proc abstractDeclarator(p: var Parser, a: PNode): PNode
proc directAbstractDeclarator(p: var Parser, a: PNode): PNode =
if p.tok.xkind == pxParLe:
getTok(p, a)
if p.tok.xkind in {pxStar, pxAmp, pxAmpAmp}:
result = abstractDeclarator(p, a)
eat(p, pxParRi, result)
result = parseTypeSuffix(p, a)
proc abstractDeclarator(p: var Parser, a: PNode): PNode =
directAbstractDeclarator(p, pointer(p, a))
proc typeName(p: var Parser): PNode = abstractDeclarator(p, typeAtom(p))
proc parseField(p: var Parser, kind: TNodeKind): PNode =
if p.tok.xkind == pxParLe:
getTok(p, nil)
while p.tok.xkind == pxStar: getTok(p, nil)
result = parseField(p, kind)
eat(p, pxParRi, result)
else:
expectIdent(p)
if kind == nkRecList: result = fieldIdent(p.tok.s, p)
else: result = mangledIdent(p.tok.s, p, skField)
getTok(p, result)
proc structPragmas(p: Parser, name: PNode, origName: string): PNode =
assert name.kind == nkIdent
result = newNodeP(nkPragmaExpr, p)
addSon(result, exportSym(p, name, origName))
var pragmas = newNodeP(nkPragma, p)
#addSon(pragmas, newIdentNodeP("pure", p), newIdentNodeP("final", p))
if p.options.useHeader:
addSon(pragmas,
newIdentStrLitPair(p.options.importcLit, p.currentNamespace & origName, p),
getHeaderPair(p))
if p.options.inheritable.hasKey(origName):
addSon(pragmas, newIdentNodeP("inheritable", p))
addSon(pragmas, newIdentNodeP("pure", p))
pragmas.add newIdentNodeP("bycopy", p)
result.add pragmas
type
FilenameHash* = uint32
proc sdbmHash(hash: FilenameHash, c: char): FilenameHash {.inline.} =
return FilenameHash(c) + (hash shl 6) + (hash shl 16) - hash
proc sdbmHash(s: string): FilenameHash =
template `&=`(x, c) = x = sdbmHash(x, c)
result = 0
for i in 0..<s.len:
result &= s[i]
proc hashPosition(p: Parser): string =
let lineInfo = parLineInfo(p)
let fileInfo = fileInfos[lineInfo.fileIndex]
result = $sdbmHash(fileInfo.shortName & "_" & $lineInfo.line & "_" &
$lineInfo.col)
proc parseInnerStruct(p: var Parser, stmtList: PNode,
isUnion: bool, name: string): PNode =
if p.tok.xkind != pxCurlyLe:
parMessage(p, errUser, "Expected '{' but found '" & $(p.tok[]) & "'")
var structName: string
if name == "":
if isUnion: structName = "INNER_C_UNION_" & p.hashPosition
else: structName = "INNER_C_STRUCT_" & p.hashPosition
else:
structName = name & "_" & p.hashPosition
let typeSection = newNodeP(nkTypeSection, p)
let newStruct = newNodeP(nkObjectTy, p)
var pragmas = ast.emptyNode
if isUnion:
pragmas = newNodeP(nkPragma, p)
addSon(pragmas, newIdentNodeP("union", p))
addSon(newStruct, pragmas, ast.emptyNode) # no inheritance
result = newNodeP(nkIdent, p)
result.ident = getIdent(structName)
let struct = parseStructBody(p, stmtList, isUnion)
let defName = newNodeP(nkIdent, p)
defName.ident = getIdent(structName)
addSon(newStruct, struct)
addTypeDef(typeSection, structPragmas(p, defName, "no_name"), newStruct,
ast.emptyNode)
addSon(stmtList, typeSection)
proc parseStructBody(p: var Parser, stmtList: PNode, isUnion: bool,
kind: TNodeKind = nkRecList): PNode =
result = newNodeP(kind, p)
eat(p, pxCurlyLe, result)
while p.tok.xkind notin {pxEof, pxCurlyRi}:
skipConst(p)
var baseTyp: PNode
if p.tok.xkind == pxSymbol and (p.tok.s == "struct" or p.tok.s == "union"):
let gotUnion = if p.tok.s == "union": true else: false
saveContext(p)
getTok(p, nil)
let prev = p
getTok(p, nil)
if prev.tok.xkind == pxSymbol and p.tok.xkind != pxCurlyLe:
backtrackContext(p)
baseTyp = typeAtom(p)
else:
backtrackContext(p)
getTok(p)
var name = ""
if p.tok.xkind == pxSymbol:
name = p.tok.s
getTok(p)
baseTyp = parseInnerStruct(p, stmtList, gotUnion, name)
if p.tok.xkind == pxSemiColon:
let def = newNodeP(nkIdentDefs, p)
var t = pointer(p, baseTyp)
let i = fieldIdent("ano_" & p.hashPosition, p)
t = parseTypeSuffix(p, t)
addSon(def, i, t, ast.emptyNode)
addSon(result, def)
getTok(p, nil)
continue
elif p.tok.xkind == pxDirective or p.tok.xkind == pxDirectiveParLe:
var define = parseDir(p, statement)
addSon(result, define)
baseTyp = typeAtom(p)
else:
baseTyp = typeAtom(p)
while true:
var def = newNodeP(nkIdentDefs, p)
var t = pointer(p, baseTyp)
var i = parseField(p, kind)
t = parseTypeSuffix(p, t)
if p.tok.xkind == pxColon:
getTok(p)
var bits = p.tok.iNumber
eat(p, pxIntLit)
var pragma = newNodeP(nkPragma, p)
var bitsize = newNodeP(nkExprColonExpr, p)
addSon(bitsize, newIdentNodeP("bitsize", p))
addSon(bitsize, newIntNodeP(nkIntLit, bits, p))
addSon(pragma, bitsize)
var pragmaExpr = newNodeP(nkPragmaExpr, p)
addSon(pragmaExpr, i)
addSon(pragmaExpr, pragma)
i = pragmaExpr
addSon(def, i, t, ast.emptyNode)
addSon(result, def)
if p.tok.xkind != pxComma: break
getTok(p, def)
eat(p, pxSemicolon, lastSon(result))
eat(p, pxCurlyRi, result)
proc enumPragmas(p: Parser, name: PNode; origName: string): PNode =
result = newNodeP(nkPragmaExpr, p)
addSon(result, name)
var pragmas = newNodeP(nkPragma, p)
if p.options.dynlibSym.len > 0 or p.options.useHeader:
var e = newNodeP(nkExprColonExpr, p)
# HACK: sizeof(cint) should be constructed as AST
addSon(e, newIdentNodeP("size", p), newIdentNodeP("sizeof(cint)", p))
addSon(pragmas, e)
if p.options.inheritable.hasKey(origName):
addSon(pragmas, newIdentNodeP("pure", p))
if pfCpp in p.options.flags and p.options.useHeader:
let importName =
if p.currentClassOrig.len > 0:
p.currentNamespace & p.currentClassOrig & "::" & origName
else:
p.currentNamespace & origName
addSon(pragmas, newIdentStrLitPair("importcpp", importName, p))
addSon(pragmas, getHeaderPair(p))
if pragmas.len > 0:
addSon(result, pragmas)
else:
result = name
proc skipInheritKeyw(p: var Parser) =
if p.tok.xkind == pxSymbol and (p.tok.s == "private" or
p.tok.s == "protected" or
p.tok.s == "public"):
getTok(p)
proc parseInheritance(p: var Parser; result: PNode) =
if p.tok.xkind == pxColon:
getTok(p, result)
skipInheritKeyw(p)
var baseTyp = typeAtom(p)
var inh = newNodeP(nkOfInherit, p)
inh.add(baseTyp)
if p.tok.xkind == pxComma:
parMessage(p, warnUser, "multiple inheritance is not supported")
while p.tok.xkind == pxComma:
getTok(p)
skipInheritKeyw(p)
discard typeAtom(p)
result.sons[0] = inh
proc parseStruct(p: var Parser, stmtList: PNode, isUnion: bool): PNode =
result = newNodeP(nkObjectTy, p)
var pragmas = ast.emptyNode
if isUnion:
pragmas = newNodeP(nkPragma, p)
addSon(pragmas, newIdentNodeP("union", p))
addSon(result, pragmas, ast.emptyNode) # no inheritance
parseInheritance(p, result)
if p.tok.xkind == pxCurlyLe:
addSon(result, parseStructBody(p, stmtList, isUnion))
else:
addSon(result, newNodeP(nkRecList, p))
proc declarator(p: var Parser, a: PNode, ident: ptr PNode): PNode
proc directDeclarator(p: var Parser, a: PNode, ident: ptr PNode): PNode =
case p.tok.xkind
of pxSymbol:
ident[] = skipIdent(p, skParam)
of pxParLe:
getTok(p, a)
if p.tok.xkind in {pxStar, pxAmp, pxAmpAmp, pxSymbol}:
result = declarator(p, a, ident)
eat(p, pxParRi, result)
else:
discard
return parseTypeSuffix(p, a)
proc declarator(p: var Parser, a: PNode, ident: ptr PNode): PNode =
directDeclarator(p, pointer(p, a), ident)
# parameter-declaration
# declaration-specifiers declarator
# declaration-specifiers asbtract-declarator(opt)
proc parseParam(p: var Parser, params: PNode) =
var typ = typeDesc(p)
# support for ``(void)`` parameter list:
if typ.kind == nkNilLit and p.tok.xkind == pxParRi: return
var name: PNode
typ = declarator(p, typ, addr name)
if name == nil:
var idx = sonsLen(params)+1
name = newIdentNodeP("a" & $idx, p)
var x = newNodeP(nkIdentDefs, p)
addSon(x, name, typ)
if p.tok.xkind == pxAsgn:
# for the wxWidgets wrapper we need to transform 'auto x = foo' into
# 'x = foo' cause 'x: auto = foo' is not really supported by Nim yet...
if typ.kind == nkIdent and typ.ident.s == "auto":
x.sons[^1] = ast.emptyNode
# we support default parameters for C++:
getTok(p, x)
addSon(x, assignmentExpression(p))
else:
addSon(x, ast.emptyNode)
addSon(params, x)
proc parseFormalParams(p: var Parser, params, pragmas: PNode) =
eat(p, pxParLe, params)
while p.tok.xkind notin {pxEof, pxParRi}:
if p.tok.xkind == pxDotDotDot:
addSon(pragmas, newIdentNodeP("varargs", p))
getTok(p, pragmas)
break
parseParam(p, params)
if p.tok.xkind != pxComma: break
getTok(p, params)
eat(p, pxParRi, params)
proc parseCallConv(p: var Parser, pragmas: PNode) =
while p.tok.xkind == pxSymbol:
case p.tok.s
of "inline", "__inline":
if pfCpp in p.options.flags and pfKeepbodies notin p.options.flags:
discard
else:
addSon(pragmas, newIdentNodeP("inline", p))
of "__cdecl": addSon(pragmas, newIdentNodeP("cdecl", p))
of "__stdcall": addSon(pragmas, newIdentNodeP("stdcall", p))
of "__syscall": addSon(pragmas, newIdentNodeP("syscall", p))
of "__fastcall": addSon(pragmas, newIdentNodeP("fastcall", p))
of "__safecall": addSon(pragmas, newIdentNodeP("safecall", p))
else: break
getTok(p, nil)
proc parseFunctionPointerDecl(p: var Parser, rettyp: PNode): PNode =
var procType = newNodeP(nkProcTy, p)
var pragmas = newProcPragmas(p)
var params = newNodeP(nkFormalParams, p)
eat(p, pxParLe, params)
discard addReturnType(params, rettyp)
parseCallConv(p, pragmas)
if pfCpp in p.options.flags and p.tok.xkind == pxSymbol:
getTok(p)
eat(p, pxScope)
addSon(pragmas, newIdentNodeP("memberfuncptr", p))
if p.tok.xkind == pxStar: getTok(p, params)
#else: parMessage(p, errTokenExpected, "*")
if p.inTypeDef > 0: markTypeIdent(p, nil)
var name = skipIdentExport(p, if p.inTypeDef > 0: skType else: skVar)
eat(p, pxParRi, name)
parseFormalParams(p, params, pragmas)
addSon(procType, params)
addPragmas(procType, pragmas)
if p.inTypeDef == 0:
result = newNodeP(nkVarSection, p)
var def = newNodeP(nkIdentDefs, p)
addSon(def, name, procType, ast.emptyNode)
addSon(result, def)
else:
result = newNodeP(nkTypeDef, p)
addSon(result, name, ast.emptyNode, procType)
assert result != nil
proc addTypeDef(section, name, t, genericParams: PNode) =
var def = newNodeI(nkTypeDef, name.info)
addSon(def, name, genericParams, t)
addSon(section, def)
proc otherTypeDef(p: var Parser, section, typ: PNode) =
var name: PNode
var t = typ
if p.tok.xkind in {pxStar, pxAmp, pxAmpAmp}:
t = pointer(p, t)
if p.tok.xkind == pxParLe:
# function pointer: typedef typ (*name)();