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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
|
// Copyright 2019 The CC Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cc // import "modernc.org/cc/v3"
import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
)
// Source is a named part of a translation unit. If Value is empty, Name is
// interpreted as a path to file containing the source code.
type Source struct {
Name string
Value string
DoNotCache bool // Disable caching of this source
}
// Promote returns the type the operands of a binary operation are promoted to
// or the type and argument passed in a function call is promoted.
func (n *AssignmentExpression) Promote() Type { return n.promote }
type StructInfo struct {
Size uintptr
Align int
}
// AST represents a translation unit and its related data.
type AST struct {
Enums map[StringID]Operand // Enumeration constants declared in file scope.
Macros map[StringID]*Macro // Macros as defined after parsing.
PtrdiffType Type
Scope Scope // File scope.
SizeType Type
StructTypes map[StringID]Type // Tagged struct/union types declared in file scope.
// Alignment and size of every struct/union defined in the translation
// unit. Valid only after Translate.
Structs map[StructInfo]struct{}
// TLD contains pruned file scope declarators, ie. either the first one
// or the first one that has an initializer.
TLD map[*Declarator]struct{}
TrailingSeperator StringID // White space and/or comments preceding EOF.
TranslationUnit *TranslationUnit
WideCharType Type
cfg *Config
cpp *cpp
}
// Eval returns the operand that represents the value of m, if it expands to a
// valid constant expression other than an identifier, or an error, if any.
func (n *AST) Eval(m *Macro) (o Operand, err error) {
defer func() {
if e := recover(); e != nil {
o = nil
err = fmt.Errorf("%v", e)
}
}()
if m.IsFnLike() {
return nil, fmt.Errorf("cannot evaluate function-like macro")
}
n.cpp.ctx.cfg.ignoreErrors = true
n.cpp.ctx.evalIdentError = true
v := n.cpp.eval(m.repl)
switch x := v.(type) {
case int64:
return &operand{abi: &n.cfg.ABI, typ: n.cfg.ABI.Type(LongLong), value: Int64Value(x)}, nil
case uint64:
return &operand{abi: &n.cfg.ABI, typ: n.cfg.ABI.Type(ULongLong), value: Uint64Value(x)}, nil
default:
return nil, fmt.Errorf("unexpected value: %T", x)
}
}
// Parse preprocesses and parses a translation unit and returns an *AST or
// error, if any.
//
// Search paths listed in includePaths and sysIncludePaths are used to resolve
// #include "foo.h" and #include <foo.h> preprocessing directives respectively.
// A special search path "@" is interpreted as 'the same directory as where the
// file with the #include directive is'.
//
// The sources should typically provide, usually in this particular order:
//
// - predefined macros, eg.
//
// #define __SIZE_TYPE__ long unsigned int
//
// - built-in declarations, eg.
//
// int __builtin_printf(char *__format, ...);
//
// - command-line provided directives, eg.
//
// #define FOO
// #define BAR 42
// #undef QUX
//
// - normal C sources, eg.
//
// int main() {}
//
// All search and file paths should be absolute paths.
//
// If the preprocessed translation unit is empty, the function may return (nil,
// nil).
//
// The parser does only the minimum declarations/identifier resolving necessary
// for correct parsing. Redeclarations are not checked.
//
// Declarators (*Declarator) and StructDeclarators (*StructDeclarator) are
// inserted in the appropriate scopes.
//
// Tagged struct/union specifier definitions (*StructOrUnionSpecifier) are
// inserted in the appropriate scopes.
//
// Tagged enum specifier definitions (*EnumSpecifier) and enumeration constants
// (*Enumerator) are inserted in the appropriate scopes.
//
// Labels (*LabeledStatement) are inserted in the appropriate scopes.
func Parse(cfg *Config, includePaths, sysIncludePaths []string, sources []Source) (*AST, error) {
return parse(newContext(cfg), includePaths, sysIncludePaths, sources)
}
func parse(ctx *context, includePaths, sysIncludePaths []string, sources []Source) (*AST, error) {
if s := ctx.cfg.SharedFunctionDefinitions; s != nil {
if s.M == nil {
s.M = map[*FunctionDefinition]struct{}{}
}
if s.m == nil {
s.m = map[sharedFunctionDefinitionKey]*FunctionDefinition{}
}
}
if debugWorkingDir || ctx.cfg.DebugWorkingDir {
switch wd, err := os.Getwd(); err {
case nil:
fmt.Fprintf(os.Stderr, "OS working dir: %s\n", wd)
default:
fmt.Fprintf(os.Stderr, "OS working dir: error %s\n", err)
}
fmt.Fprintf(os.Stderr, "Config.WorkingDir: %s\n", ctx.cfg.WorkingDir)
}
if debugIncludePaths || ctx.cfg.DebugIncludePaths {
fmt.Fprintf(os.Stderr, "include paths: %v\n", includePaths)
fmt.Fprintf(os.Stderr, "system include paths: %v\n", sysIncludePaths)
}
ctx.includePaths = includePaths
ctx.sysIncludePaths = sysIncludePaths
var in []source
for _, v := range sources {
ts, err := cache.get(ctx, v)
if err != nil {
return nil, err
}
in = append(in, ts)
}
p := newParser(ctx, make(chan *[]Token, 5000)) //DONE benchmark tuned
var sep StringID
var ssep []byte
var seq int32
cpp := newCPP(ctx)
go func() {
defer func() {
close(p.in)
ctx.intMaxWidth = cpp.intMaxWidth()
}()
toks := tokenPool.Get().(*[]Token)
*toks = (*toks)[:0]
for pline := range cpp.translationPhase4(in) {
line := *pline
for _, tok := range line {
switch tok.char {
case ' ', '\n':
if ctx.cfg.PreserveOnlyLastNonBlankSeparator {
if strings.TrimSpace(tok.value.String()) != "" {
sep = tok.value
}
break
}
switch {
case sep != 0:
ssep = append(ssep, tok.String()...)
default:
sep = tok.value
ssep = append(ssep[:0], sep.String()...)
}
default:
var t Token
t.Rune = tok.char
switch {
case len(ssep) != 0:
t.Sep = dict.id(ssep)
default:
t.Sep = sep
}
t.Value = tok.value
t.Src = tok.src
t.file = tok.file
t.macro = tok.macro
t.pos = tok.pos
seq++
t.seq = seq
*toks = append(*toks, t)
sep = 0
ssep = ssep[:0]
}
}
token4Pool.Put(pline)
var c rune
if n := len(*toks); n != 0 {
c = (*toks)[n-1].Rune
}
switch c {
case STRINGLITERAL, LONGSTRINGLITERAL:
// nop
default:
if len(*toks) != 0 {
p.in <- translationPhase5(ctx, toks)
toks = tokenPool.Get().(*[]Token)
*toks = (*toks)[:0]
}
}
}
if len(*toks) != 0 {
p.in <- translationPhase5(ctx, toks)
}
}()
tu := p.translationUnit()
if p.errored { // Must drain
go func() {
for range p.in {
}
}()
}
if err := ctx.Err(); err != nil {
return nil, err
}
if p.errored && !ctx.cfg.ignoreErrors {
return nil, fmt.Errorf("%v: syntax error", p.tok.Position())
}
if p.scopes != 0 {
panic(internalErrorf("invalid scope nesting but no error reported"))
}
ts := sep
if len(ssep) != 0 {
ts = dict.id(ssep)
}
return &AST{
Macros: cpp.macros,
Scope: p.fileScope,
TLD: map[*Declarator]struct{}{},
TrailingSeperator: ts,
TranslationUnit: tu,
cfg: ctx.cfg,
cpp: cpp,
}, nil
}
func translationPhase5(ctx *context, toks *[]Token) *[]Token {
// [0], 5.1.1.2, 5
//
// Each source character set member and escape sequence in character
// constants and string literals is converted to the corresponding
// member of the execution character set; if there is no corresponding
// member, it is converted to an implementation- defined member other
// than the null (wide) character.
for i, tok := range *toks {
var cpt cppToken
switch tok.Rune {
case STRINGLITERAL, LONGSTRINGLITERAL:
cpt.char = tok.Rune
cpt.value = tok.Value
cpt.src = tok.Src
cpt.file = tok.file
cpt.pos = tok.pos
(*toks)[i].Value = dict.sid(stringConst(ctx, cpt))
case CHARCONST, LONGCHARCONST:
var cpt cppToken
cpt.char = tok.Rune
cpt.value = tok.Value
cpt.src = tok.Src
cpt.file = tok.file
cpt.pos = tok.pos
switch r := charConst(ctx, cpt); {
case r <= 255:
(*toks)[i].Value = dict.sid(string(r))
default:
switch cpt.char {
case CHARCONST:
ctx.err(tok.Position(), "invalid character constant: %s", tok.Value)
default:
(*toks)[i].Value = dict.sid(string(r))
}
}
}
}
return toks
}
// Preprocess preprocesses a translation unit and outputs the result to w.
//
// Please see Parse for the documentation of the other parameters.
func Preprocess(cfg *Config, includePaths, sysIncludePaths []string, sources []Source, w io.Writer) error {
ctx := newContext(cfg)
if debugWorkingDir || ctx.cfg.DebugWorkingDir {
switch wd, err := os.Getwd(); err {
case nil:
fmt.Fprintf(os.Stderr, "OS working dir: %s\n", wd)
default:
fmt.Fprintf(os.Stderr, "OS working dir: error %s\n", err)
}
fmt.Fprintf(os.Stderr, "Config.WorkingDir: %s\n", ctx.cfg.WorkingDir)
}
if debugIncludePaths || ctx.cfg.DebugIncludePaths {
fmt.Fprintf(os.Stderr, "include paths: %v\n", includePaths)
fmt.Fprintf(os.Stderr, "system include paths: %v\n", sysIncludePaths)
}
ctx.includePaths = includePaths
ctx.sysIncludePaths = sysIncludePaths
var in []source
for _, v := range sources {
ts, err := cache.get(ctx, v)
if err != nil {
return err
}
in = append(in, ts)
}
var sep StringID
cpp := newCPP(ctx)
toks := tokenPool.Get().(*[]Token)
*toks = (*toks)[:0]
for pline := range cpp.translationPhase4(in) {
line := *pline
for _, tok := range line {
switch tok.char {
case ' ', '\n':
if ctx.cfg.PreserveOnlyLastNonBlankSeparator {
if strings.TrimSpace(tok.value.String()) != "" {
sep = tok.value
}
break
}
switch {
case sep != 0:
sep = dict.sid(sep.String() + tok.String())
default:
sep = tok.value
}
default:
var t Token
t.Rune = tok.char
t.Sep = sep
t.Value = tok.value
t.Src = tok.src
t.file = tok.file
t.pos = tok.pos
*toks = append(*toks, t)
sep = 0
}
}
token4Pool.Put(pline)
var c rune
if n := len(*toks); n != 0 {
c = (*toks)[n-1].Rune
}
switch c {
case STRINGLITERAL, LONGSTRINGLITERAL:
// nop
default:
if len(*toks) != 0 {
for _, v := range *translationPhase5(ctx, toks) {
if err := wTok(w, v); err != nil {
return err
}
}
toks = tokenPool.Get().(*[]Token)
*toks = (*toks)[:0]
}
}
}
if len(*toks) != 0 {
for _, v := range *translationPhase5(ctx, toks) {
if err := wTok(w, v); err != nil {
return err
}
}
}
if _, err := fmt.Fprintln(w); err != nil {
return err
}
return ctx.Err()
}
func wTok(w io.Writer, tok Token) (err error) {
switch tok.Rune {
case STRINGLITERAL, LONGSTRINGLITERAL:
_, err = fmt.Fprintf(w, `%s"%s"`, tok.Sep, cQuotedString(tok.String(), true))
case CHARCONST, LONGCHARCONST:
_, err = fmt.Fprintf(w, `%s'%s'`, tok.Sep, cQuotedString(tok.String(), false))
default:
_, err = fmt.Fprintf(w, "%s%s", tok.Sep, tok)
}
return err
}
func cQuotedString(s string, isString bool) []byte {
var b []byte
for i := 0; i < len(s); i++ {
c := s[i]
switch c {
case '\b':
b = append(b, '\\', 'b')
continue
case '\f':
b = append(b, '\\', 'f')
continue
case '\n':
b = append(b, '\\', 'n')
continue
case '\r':
b = append(b, '\\', 'r')
continue
case '\t':
b = append(b, '\\', 't')
continue
case '\\':
b = append(b, '\\', '\\')
continue
case '"':
switch {
case isString:
b = append(b, '\\', '"')
default:
b = append(b, '"')
}
continue
case '\'':
switch {
case isString:
b = append(b, '\'')
default:
b = append(b, '\\', '\'')
}
continue
}
switch {
case c < ' ' || c >= 0x7f:
b = append(b, '\\', octal(c>>6), octal(c>>3), octal(c))
default:
b = append(b, c)
}
}
return b
}
func octal(b byte) byte { return '0' + b&7 }
var trcSource = Source{"<builtin-trc>", `
extern void *stderr;
int fflush(void *stream);
int fprintf(void *stream, const char *format, ...);
`, false}
// Translate parses and typechecks a translation unit and returns an *AST or
// error, if any.
//
// Please see Parse for the documentation of the parameters.
func Translate(cfg *Config, includePaths, sysIncludePaths []string, sources []Source) (*AST, error) {
if cfg.InjectTracingCode {
for i, v := range sources {
if filepath.Ext(v.Name) == ".c" {
sources = append(append(append([]Source(nil), sources[:i]...), trcSource), sources[i:]...)
}
}
}
return translate(newContext(cfg), includePaths, sysIncludePaths, sources)
}
func translate(ctx *context, includePaths, sysIncludePaths []string, sources []Source) (*AST, error) {
ast, err := parse(ctx, includePaths, sysIncludePaths, sources)
if err != nil {
return nil, err
}
if ctx, err = ast.typecheck(); err != nil {
return nil, err
}
ast.PtrdiffType = ptrdiffT(ctx, ast.Scope, Token{})
ast.SizeType = sizeT(ctx, ast.Scope, Token{})
ast.WideCharType = wcharT(ctx, ast.Scope, Token{})
return ast, nil
}
// Typecheck determines types of objects and expressions and verifies types are
// valid in the context they are used.
func (n *AST) Typecheck() error {
_, err := n.typecheck()
return err
}
func (n *AST) typecheck() (*context, error) {
ctx := newContext(n.cfg)
if err := ctx.cfg.ABI.sanityCheck(ctx, int(ctx.intMaxWidth), n.Scope); err != nil {
return nil, err
}
ctx.intBits = int(ctx.cfg.ABI.Types[Int].Size) * 8
ctx.ast = n
n.TranslationUnit.check(ctx)
n.Structs = ctx.structs
var a []int
for k := range n.Scope {
a = append(a, int(k))
}
sort.Ints(a)
for _, v := range a {
nm := StringID(v)
defs := n.Scope[nm]
var r, w int
for _, v := range defs {
switch x := v.(type) {
case *Declarator:
r += x.Read
w += x.Write
}
}
for _, v := range defs {
switch x := v.(type) {
case *Declarator:
x.Read = r
x.Write = w
}
}
var pruned *Declarator
for _, v := range defs {
switch x := v.(type) {
case *Declarator:
//TODO check compatible types
switch {
case x.IsExtern() && !x.fnDef:
// nop
case pruned == nil:
pruned = x
case pruned.hasInitializer && x.hasInitializer:
ctx.errNode(x, "multiple initializers for the same symbol")
continue
case pruned.fnDef && x.fnDef:
ctx.errNode(x, "multiple function definitions")
continue
case x.hasInitializer || x.fnDef:
pruned = x
}
}
}
if pruned == nil {
continue
}
n.TLD[pruned] = struct{}{}
}
n.Enums = ctx.enums
n.StructTypes = ctx.structTypes
return ctx, ctx.Err()
}
func (n *AlignmentSpecifier) align() int {
switch n.Case {
case AlignmentSpecifierAlignasType: // "_Alignas" '(' TypeName ')'
return n.TypeName.Type().Align()
case AlignmentSpecifierAlignasExpr: // "_Alignas" '(' ConstantExpression ')'
return n.ConstantExpression.Operand.Type().Align()
default:
panic(internalError())
}
}
// Closure reports the variables closed over by a nested function (case
// BlockItemFuncDef).
func (n *BlockItem) Closure() map[StringID]struct{} { return n.closure }
// FunctionDefinition returns the nested function (case BlockItemFuncDef).
func (n *BlockItem) FunctionDefinition() *FunctionDefinition { return n.fn }
func (n *Declarator) IsStatic() bool { return n.td != nil && n.td.static() }
// IsImplicit reports whether n was not declared nor defined, only inferred.
func (n *Declarator) IsImplicit() bool { return n.implicit }
func (n *Declarator) isVisible(at int32) bool { return at == 0 || n.DirectDeclarator.ends() < at }
func (n *Declarator) setLHS(lhs *Declarator) {
if n == nil {
return
}
if n.lhs == nil {
n.lhs = map[*Declarator]struct{}{}
}
n.lhs[lhs] = struct{}{}
}
// LHS reports which declarators n is used in assignment RHS or which function
// declarators n is used in a function argument. To collect this information,
// TrackAssignments in Config must be set during type checking.
// The returned map may contain a nil key. That means that n is assigned to a
// declarator not known at typechecking time.
func (n *Declarator) LHS() map[*Declarator]struct{} { return n.lhs }
// Called reports whether n is involved in expr in expr(callArgs).
func (n *Declarator) Called() bool { return n.called }
// FunctionDefinition returns the function definition associated with n, if any.
func (n *Declarator) FunctionDefinition() *FunctionDefinition {
return n.funcDefinition
}
// NameTok returns n's declaring name token.
func (n *Declarator) NameTok() (r Token) {
if n == nil || n.DirectDeclarator == nil {
return r
}
return n.DirectDeclarator.NameTok()
}
// LexicalScope returns the lexical scope of n.
func (n *Declarator) LexicalScope() Scope { return n.DirectDeclarator.lexicalScope }
// Name returns n's declared name.
func (n *Declarator) Name() StringID {
if n == nil || n.DirectDeclarator == nil {
return 0
}
return n.DirectDeclarator.Name()
}
// ParamScope returns the scope in which n's function parameters are declared
// if the underlying type of n is a function or nil otherwise. If n is part of
// a function definition the scope is the same as the scope of the function
// body.
func (n *Declarator) ParamScope() Scope {
if n == nil {
return nil
}
return n.DirectDeclarator.ParamScope()
}
// Type returns the type of n.
func (n *Declarator) Type() Type { return n.typ }
// IsExtern reports whether n was declared with storage class specifier 'extern'.
func (n *Declarator) IsExtern() bool { return n.td != nil && n.td.extern() }
func (n *DeclarationSpecifiers) auto() bool { return n != nil && n.class&fAuto != 0 }
func (n *DeclarationSpecifiers) extern() bool { return n != nil && n.class&fExtern != 0 }
func (n *DeclarationSpecifiers) register() bool { return n != nil && n.class&fRegister != 0 }
func (n *DeclarationSpecifiers) static() bool { return n != nil && n.class&fStatic != 0 }
func (n *DeclarationSpecifiers) threadLocal() bool { return n != nil && n.class&fThreadLocal != 0 }
func (n *DeclarationSpecifiers) typedef() bool { return n != nil && n.class&fTypedef != 0 }
func (n *DirectAbstractDeclarator) TypeQualifier() Type { return n.typeQualifiers }
func (n *DirectDeclarator) ends() int32 {
switch n.Case {
case DirectDeclaratorIdent: // IDENTIFIER
return n.Token.seq
case DirectDeclaratorDecl: // '(' Declarator ')'
return n.Token2.seq
case DirectDeclaratorArr: // DirectDeclarator '[' TypeQualifierList AssignmentExpression ']'
return n.Token2.seq
case DirectDeclaratorStaticArr: // DirectDeclarator '[' "static" TypeQualifierList AssignmentExpression ']'
return n.Token3.seq
case DirectDeclaratorArrStatic: // DirectDeclarator '[' TypeQualifierList "static" AssignmentExpression ']'
return n.Token3.seq
case DirectDeclaratorStar: // DirectDeclarator '[' TypeQualifierList '*' ']'
return n.Token3.seq
case DirectDeclaratorFuncParam: // DirectDeclarator '(' ParameterTypeList ')'
return n.Token2.seq
case DirectDeclaratorFuncIdent: // DirectDeclarator '(' IdentifierList ')'
return n.Token2.seq
default:
panic(internalError())
}
}
func (n *DirectDeclarator) TypeQualifier() Type { return n.typeQualifiers }
// NameTok returns n's declarin name token.
func (n *DirectDeclarator) NameTok() (r Token) {
for {
if n == nil {
return r
}
switch n.Case {
case DirectDeclaratorIdent: // IDENTIFIER
return n.Token
case DirectDeclaratorDecl: // '(' Declarator ')'
return n.Declarator.NameTok()
default:
n = n.DirectDeclarator
}
}
}
// Name returns n's declared name.
func (n *DirectDeclarator) Name() StringID {
for {
if n == nil {
return 0
}
switch n.Case {
case DirectDeclaratorIdent: // IDENTIFIER
return n.Token.Value
case DirectDeclaratorDecl: // '(' Declarator ')'
return n.Declarator.Name()
default:
n = n.DirectDeclarator
}
}
}
// ParamScope returns the innermost scope in which function parameters are
// declared for Case DirectDeclaratorFuncParam or DirectDeclaratorFuncIdent or
// nil otherwise.
func (n *DirectDeclarator) ParamScope() Scope {
if n == nil {
return nil
}
switch n.Case {
case DirectDeclaratorIdent: // IDENTIFIER
return nil
case DirectDeclaratorDecl: // '(' Declarator ')'
return n.Declarator.ParamScope()
case DirectDeclaratorArr: // DirectDeclarator '[' TypeQualifierList AssignmentExpression ']'
return n.DirectDeclarator.ParamScope()
case DirectDeclaratorStaticArr: // DirectDeclarator '[' "static" TypeQualifierList AssignmentExpression ']'
return n.DirectDeclarator.ParamScope()
case DirectDeclaratorArrStatic: // DirectDeclarator '[' TypeQualifierList "static" AssignmentExpression ']'
return n.DirectDeclarator.ParamScope()
case DirectDeclaratorStar: // DirectDeclarator '[' TypeQualifierList '*' ']'
return n.DirectDeclarator.ParamScope()
case DirectDeclaratorFuncParam: // DirectDeclarator '(' ParameterTypeList ')'
if s := n.DirectDeclarator.ParamScope(); s != nil {
return s
}
return n.paramScope
case DirectDeclaratorFuncIdent: // DirectDeclarator '(' IdentifierList ')'
if s := n.DirectDeclarator.ParamScope(); s != nil {
return s
}
return n.paramScope
default:
panic(internalError())
}
}
func (n *Enumerator) isVisible(at int32) bool { return n.Token.seq < at }
func (n *EnumSpecifier) Type() Type { return n.typ }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *EqualityExpression) Promote() Type { return n.promote }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *AdditiveExpression) Promote() Type { return n.promote }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *MultiplicativeExpression) Promote() Type { return n.promote }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *InclusiveOrExpression) Promote() Type { return n.promote }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *ExclusiveOrExpression) Promote() Type { return n.promote }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *AndExpression) Promote() Type { return n.promote }
func (n *InitDeclarator) Value() *InitializerValue { return n.initializer }
// FirstDesignatorField returns the first field a designator of an union type
// denotes, if any.
func (n *Initializer) FirstDesignatorField() Field { return n.field0 }
// TrailingComma returns the comma token following n, if any.
func (n *Initializer) TrailingComma() *Token { return n.trailingComma }
// IsConst reports whether n is constant.
func (n *Initializer) IsConst() bool { return n == nil || n.isConst }
// IsZero reports whether n is a zero value.
func (n *Initializer) IsZero() bool { return n == nil || n.isZero }
// List returns n as a flattened list of all items that are case
// InitializerExpr.
func (n *Initializer) List() []*Initializer { return n.list }
// Parent returns the parent of n, if any.
func (n *Initializer) Parent() *Initializer { return n.parent }
// Type returns the type this initializer initializes.
func (n *Initializer) Type() Type { return n.typ }
// IsConst reports whether n is constant.
func (n *InitializerList) IsConst() bool { return n == nil || n.isConst }
// IsZero reports whether n is a zero value.
func (n *InitializerList) IsZero() bool { return n == nil || n.isZero }
// List returns n as a flattened list of all items that are case
// InitializerExpr.
func (n *InitializerList) List() []*Initializer {
if n == nil {
return nil
}
return n.list
}
// IsEmpty reprts whether n is an empty list.
func (n *InitializerList) IsEmpty() bool { return len(n.list) == 0 }
// LexicalScope returns the lexical scope of n.
func (n *JumpStatement) LexicalScope() Scope { return n.lexicalScope }
// LexicalScope returns the lexical scope of n.
func (n *LabeledStatement) LexicalScope() Scope { return n.lexicalScope }
func (n *ParameterDeclaration) Type() Type { return n.typ }
func (n *Pointer) TypeQualifier() Type { return n.typeQualifiers }
// ResolvedIn reports which scope the identifier of cases
// PrimaryExpressionIdent, PrimaryExpressionEnum were resolved in, if any.
func (n *PrimaryExpression) ResolvedIn() Scope { return n.resolvedIn }
// ResolvedTo reports which Node the identifier of cases
// PrimaryExpressionIdent, PrimaryExpressionEnum resolved to, if any.
func (n *PrimaryExpression) ResolvedTo() Node { return n.resolvedTo }
// Promote returns the type the operands of the binary operation are promoted to.
func (n *RelationalExpression) Promote() Type { return n.promote }
// Cases returns the cases a switch statement consist of, in source order.
func (n *SelectionStatement) Cases() []*LabeledStatement { return n.cases }
// Promote returns the type the shift count operand is promoted to.
func (n *ShiftExpression) Promote() Type { return n.promote }
func (n *StructOrUnionSpecifier) Type() Type { return n.typ }
// Promote returns the type the type the switch expression is promoted to.
func (n *SelectionStatement) Promote() Type { return n.promote }
// Type returns the type of n.
func (n *TypeName) Type() Type { return n.typ }
// // LexicalScope returns the lexical scope of n.
// func (n *AttributeValue) LexicalScope() Scope { return n.lexicalScope }
// // Scope returns n's scope.
// func (n *CompoundStatement) Scope() Scope { return n.scope }
// // LexicalScope returns the lexical scope of n.
// func (n *Designator) LexicalScope() Scope { return n.lexicalScope }
// // LexicalScope returns the lexical scope of n.
// func (n *DirectDeclarator) LexicalScope() Scope { return n.lexicalScope }
// LexicalScope returns the lexical scope of n.
func (n *EnumSpecifier) LexicalScope() Scope { return n.lexicalScope }
// // LexicalScope returns the lexical scope of n.
// func (n *IdentifierList) LexicalScope() Scope { return n.lexicalScope }
// // LexicalScope returns the lexical scope of n.
// func (n *PrimaryExpression) LexicalScope() Scope { return n.lexicalScope }
// // LexicalScope returns the lexical scope of n.
// func (n *StructOrUnionSpecifier) LexicalScope() Scope { return n.lexicalScope }
// // ResolvedIn reports which scope the identifier of case
// // TypeSpecifierTypedefName was resolved in, if any.
// func (n *TypeSpecifier) ResolvedIn() Scope { return n.resolvedIn }
func (n *TypeSpecifier) list() (r []*TypeSpecifier) {
switch n.Case {
case TypeSpecifierAtomic:
return n.AtomicTypeSpecifier.list
default:
return []*TypeSpecifier{n}
}
}
// // LexicalScope returns the lexical scope of n.
// func (n *UnaryExpression) LexicalScope() Scope { return n.lexicalScope }
func (n *UnaryExpression) Declarator() *Declarator {
switch n.Case {
case UnaryExpressionPostfix: // PostfixExpression
return n.PostfixExpression.Declarator()
default:
return nil
}
}
func (n *PostfixExpression) Declarator() *Declarator {
switch n.Case {
case PostfixExpressionPrimary: // PrimaryExpression
return n.PrimaryExpression.Declarator()
default:
return nil
}
}
func (n *PrimaryExpression) Declarator() *Declarator {
switch n.Case {
case PrimaryExpressionIdent: // IDENTIFIER
if n.Operand != nil {
return n.Operand.Declarator()
}
return nil
case PrimaryExpressionExpr: // '(' Expression ')'
return n.Expression.Declarator()
default:
return nil
}
}
func (n *Expression) Declarator() *Declarator {
switch n.Case {
case ExpressionAssign: // AssignmentExpression
return n.AssignmentExpression.Declarator()
default:
return nil
}
}
func (n *AssignmentExpression) Declarator() *Declarator {
switch n.Case {
case AssignmentExpressionCond: // ConditionalExpression
return n.ConditionalExpression.Declarator()
default:
return nil
}
}
func (n *ConditionalExpression) Declarator() *Declarator {
switch n.Case {
case ConditionalExpressionLOr: // LogicalOrExpression
return n.LogicalOrExpression.Declarator()
default:
return nil
}
}
func (n *LogicalOrExpression) Declarator() *Declarator {
switch n.Case {
case LogicalOrExpressionLAnd: // LogicalAndExpression
return n.LogicalAndExpression.Declarator()
default:
return nil
}
}
func (n *LogicalAndExpression) Declarator() *Declarator {
switch n.Case {
case LogicalAndExpressionOr: // InclusiveOrExpression
return n.InclusiveOrExpression.Declarator()
default:
return nil
}
}
func (n *InclusiveOrExpression) Declarator() *Declarator {
switch n.Case {
case InclusiveOrExpressionXor: // ExclusiveOrExpression
return n.ExclusiveOrExpression.Declarator()
default:
return nil
}
}
func (n *ExclusiveOrExpression) Declarator() *Declarator {
switch n.Case {
case ExclusiveOrExpressionAnd: // AndExpression
return n.AndExpression.Declarator()
default:
return nil
}
}
func (n *AndExpression) Declarator() *Declarator {
switch n.Case {
case AndExpressionEq: // EqualityExpression
return n.EqualityExpression.Declarator()
default:
return nil
}
}
func (n *EqualityExpression) Declarator() *Declarator {
switch n.Case {
case EqualityExpressionRel: // RelationalExpression
return n.RelationalExpression.Declarator()
default:
return nil
}
}
func (n *RelationalExpression) Declarator() *Declarator {
switch n.Case {
case RelationalExpressionShift: // ShiftExpression
return n.ShiftExpression.Declarator()
default:
return nil
}
}
func (n *ShiftExpression) Declarator() *Declarator {
switch n.Case {
case ShiftExpressionAdd: // AdditiveExpression
return n.AdditiveExpression.Declarator()
default:
return nil
}
}
func (n *AdditiveExpression) Declarator() *Declarator {
switch n.Case {
case AdditiveExpressionMul: // MultiplicativeExpression
return n.MultiplicativeExpression.Declarator()
default:
return nil
}
}
func (n *MultiplicativeExpression) Declarator() *Declarator {
switch n.Case {
case MultiplicativeExpressionCast: // CastExpression
return n.CastExpression.Declarator()
default:
return nil
}
}
func (n *CastExpression) Declarator() *Declarator {
switch n.Case {
case CastExpressionUnary: // UnaryExpression
return n.UnaryExpression.Declarator()
default:
return nil
}
}
// Has reports whether n has any of attributes in key.
func (n *AttributeSpecifier) Has(key ...StringID) (*ExpressionList, bool) {
if n == nil {
return nil, false
}
for list := n.AttributeValueList; list != nil; list = list.AttributeValueList {
av := list.AttributeValue
for _, k := range key {
if av.Token.Value == k {
switch av.Case {
case AttributeValueIdent: // IDENTIFIER
return nil, true
case AttributeValueExpr: // IDENTIFIER '(' ExpressionList ')'
return av.ExpressionList, true
}
}
}
}
return nil, false
}
// Has reports whether n has any of attributes in key.
func (n *AttributeSpecifierList) Has(key ...StringID) (*ExpressionList, bool) {
for ; n != nil; n = n.AttributeSpecifierList {
if exprList, ok := n.AttributeSpecifier.Has(key...); ok {
return exprList, ok
}
}
return nil, false
}
// Parent returns the CompoundStatement that contains n, if any.
func (n *CompoundStatement) Parent() *CompoundStatement { return n.parent }
// IsJumpTarget returns whether n or any of its children contain a named
// labeled statement.
func (n *CompoundStatement) IsJumpTarget() bool { return n.isJumpTarget }
func (n *CompoundStatement) hasLabel() {
for ; n != nil; n = n.parent {
n.isJumpTarget = true
}
}
// Declarations returns the list of declarations in n.
func (n *CompoundStatement) Declarations() []*Declaration { return n.declarations }
// Children returns the list of n's children.
func (n *CompoundStatement) Children() []*CompoundStatement { return n.children }
// CompoundStatements returns the list of compound statements in n.
func (n *FunctionDefinition) CompoundStatements() []*CompoundStatement { return n.compoundStatements }
// CompoundStatement returns the block containing n.
func (n *LabeledStatement) CompoundStatement() *CompoundStatement { return n.block }
// LabeledStatements returns labeled statements of n.
func (n *CompoundStatement) LabeledStatements() []*LabeledStatement { return n.labeledStmts }
// HasInitializer reports whether d has an initializator.
func (n *Declarator) HasInitializer() bool { return n.hasInitializer }
// Context reports the statement, if any, a break or continue belongs to. Valid
// only after typecheck and for n.Case == JumpStatementBreak or
// JumpStatementContinue.
func (n *JumpStatement) Context() Node { return n.context }
// IsFunctionPrototype reports whether n is a function prototype.
func (n *Declarator) IsFunctionPrototype() bool {
return n != nil && n.Type() != nil && n.Type().Kind() == Function && !n.fnDef && !n.IsParameter
}
// DeclarationSpecifiers returns the declaration specifiers associated with n or nil.
func (n *Declarator) DeclarationSpecifiers() *DeclarationSpecifiers {
if x, ok := n.td.(*DeclarationSpecifiers); ok {
return x
}
return nil
}
// SpecifierQualifierList returns the specifier qualifer list associated with n or nil.
func (n *Declarator) SpecifierQualifierList() *SpecifierQualifierList {
if x, ok := n.td.(*SpecifierQualifierList); ok {
return x
}
return nil
}
// TypeQualifier returns the type qualifiers associated with n or nil.
func (n *Declarator) TypeQualifiers() *TypeQualifiers {
if x, ok := n.td.(*TypeQualifiers); ok {
return x
}
return nil
}
// StructDeclaration returns the struct declaration associated with n.
func (n *StructDeclarator) StructDeclaration() *StructDeclaration { return n.decl }
|