-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpp.go
1374 lines (1209 loc) · 28.7 KB
/
cpp.go
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
// Copyright 2017 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.
// [0]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
// [1]: https://www.spinellis.gr/blog/20060626/cpp.algo.pdf
package cc
import (
"bytes"
"encoding/binary"
"fmt"
"go/token"
"io"
"math"
"os"
"path/filepath"
"strings"
"github.com/cznic/golex/lex"
"github.com/cznic/ir"
"github.com/cznic/mathutil"
"github.com/cznic/xc"
)
const (
maxIncludeLevel = 200 // gcc, std is at least 15.
)
var (
_ tokenReader = (*cppReader)(nil)
_ tokenReader = (*tokenBuffer)(nil)
_ tokenReader = (*tokenPipe)(nil)
_ tokenWriter = (*tokenBuffer)(nil)
_ tokenWriter = (*tokenPipe)(nil)
)
type tokenWriter interface {
write(...xc.Token)
}
type tokenReader interface {
read() xc.Token
unget(xc.Token)
ungets(...xc.Token)
}
type tokenPipe struct {
b []byte
ch chan xc.Token
s []xc.Token
}
func newTokenPipe(n int) *tokenPipe { return &tokenPipe{ch: make(chan xc.Token, n)} }
func (*tokenPipe) unget(xc.Token) { panic("internal error") }
func (*tokenPipe) ungets(...xc.Token) { panic("internal error") }
func (p *tokenPipe) close() {
if len(p.s) != 0 {
p.flush()
}
close(p.ch)
}
func (p *tokenPipe) flush() {
p.b = p.b[:0]
p.b = append(p.b, '"')
for _, t := range p.s {
s := dict.S(t.Val)
p.b = append(p.b, s[1:len(s)-1]...)
}
p.b = append(p.b, '"')
p.s[0].Val = dict.ID(p.b)
p.ch <- p.s[0]
p.s = p.s[:0]
}
func (p *tokenPipe) read() xc.Token {
t, ok := <-p.ch
if !ok {
t.Rune = ccEOF
}
return t
}
func (p *tokenPipe) write(toks ...xc.Token) {
for _, t := range toks {
switch t.Rune {
case '\n', ' ':
// nop
case STRINGLITERAL:
p.s = append(p.s, t)
case LONGSTRINGLITERAL:
panic("TODO")
default:
if len(p.s) != 0 {
p.flush()
}
p.ch <- t
}
}
}
type tokenBuffer struct {
toks0 []xc.Token
toks []xc.Token
ungetBuffer
last rune
}
func (b *tokenBuffer) write(t ...xc.Token) {
b.toks = append(b.toks, t...)
if b.toks0 == nil || &b.toks0[0] != &b.toks[0] {
b.toks0 = b.toks
}
}
func (b *tokenBuffer) read() (t xc.Token) {
if len(b.ungetBuffer) != 0 {
return b.ungetBuffer.read()
}
if len(b.toks) == 0 {
t.Rune = ccEOF
return
}
t = b.toks[0]
b.toks = b.toks[1:]
if len(b.toks) == 0 {
b.toks = b.toks0[:0]
}
if t.Rune == '#' && (b.last == '\n' || b.last == 0) {
t.Rune = DIRECTIVE
}
b.last = t.Rune
return t
}
type cppReader struct {
decBuf []byte
decPos token.Pos
tu [][]uint32
ungetBuffer
last rune
}
func (c *cppReader) unget(t xc.Token) { c.ungetBuffer = append(c.ungetBuffer, t) }
func (c *cppReader) read() (t xc.Token) {
if len(c.ungetBuffer) != 0 {
return c.ungetBuffer.read()
}
more:
if len(c.decBuf) == 0 {
if len(c.tu) == 0 {
t.Rune = ccEOF
return t
}
if len(c.tu[0]) == 0 {
c.tu = c.tu[1:]
goto more
}
c.decBuf = dict.S(int(c.tu[0][0]))
c.tu[0] = c.tu[0][1:]
c.decPos = 0
}
c.decBuf, c.decPos, t = decodeToken(c.decBuf, c.decPos)
if t.Rune == '#' && (c.last == '\n' || c.last == 0) {
t.Rune = DIRECTIVE
}
c.last = t.Rune
return t
}
type conds []cond
func (c conds) on() bool { return condOn[c.tos()] }
func (c conds) pop() conds { return c[:len(c)-1] }
func (c conds) push(n cond) conds { return append(c, n) }
func (c conds) tos() cond { return c[len(c)-1] }
// Macro represents a preprocessor Macro.
type Macro struct {
Args []int // Numeric IDs of argument identifiers.
DefTok xc.Token // Macro name definition token.
ReplacementToks []xc.Token // The tokens that replace the macro. R/O
IsFnLike bool // Whether the macro is function like.
IsVariadic bool // Whether the macro is variadic.
ident bool
}
func newMacro(def xc.Token, repl []xc.Token) *Macro {
return &Macro{DefTok: def, ReplacementToks: append([]xc.Token(nil), repl...)}
}
// Eval attempts to evaluate m, which must be a simple macro, like `#define foo numeric-literal`.
func (m *Macro) Eval(model Model, macros map[int]*Macro) (op Operand, err error) {
returned := false
defer func() {
e := recover()
if !returned && err == nil {
err = fmt.Errorf("PANIC: %v\n%s", e, debugStack())
}
}()
if m.IsFnLike {
return op, fmt.Errorf("cannot evaluate function-like macro")
}
ctx, err := newContext(&Tweaks{})
if err != nil {
return op, err
}
ctx.model = model
c := newCPP(ctx)
c.macros = macros
if op, _ = c.constExpr(m.ReplacementToks); op.Type == nil {
return op, fmt.Errorf("cannot evaluate macro")
}
returned = true
return op, nil
}
func (m *Macro) param(ap [][]xc.Token, nm int, out *[]xc.Token) bool {
*out = nil
if nm == idVaArgs {
if !m.IsVariadic {
return false
}
if i := len(m.Args); i < len(ap) {
o := *out
for i, v := range ap[i:] {
if i != 0 {
t := o[len(o)-1]
t.Rune = ','
t.Val = 0
o = append(o, t)
t.Rune = ' '
o = append(o, t)
}
o = append(o, v...)
}
*out = o
}
return true
}
if len(m.Args) != 0 && nm == m.Args[len(m.Args)-1] && m.IsVariadic && !m.ident {
if i := len(m.Args) - 1; i < len(ap) {
o := *out
for i, v := range ap[i:] {
if i != 0 {
t := o[len(o)-1]
t.Rune = ','
t.Val = 0
o = append(o, t)
t.Rune = ' '
o = append(o, t)
}
o = append(o, v...)
}
*out = o
}
return true
}
for i, v := range m.Args {
if v == nm {
*out = ap[i]
return true
}
}
return false
}
type nullReader struct{}
func (nullReader) Read([]byte) (int, error) { return 0, io.EOF }
type cpp struct {
*context
hideSet map[int]int // name: hidden if != 0.
includeLevel int
lx *lexer
macros map[int]*Macro // name ID: macro
toks []xc.Token
}
func newCPP(ctx *context) *cpp {
lx, err := newLexer(ctx, "", 0, nullReader{})
if err != nil {
panic(err)
}
lx.context = ctx
r := &cpp{
context: ctx,
hideSet: map[int]int{},
lx: lx,
macros: map[int]*Macro{},
}
return r
}
func (c *cpp) parse(src ...Source) (tokenReader, error) {
var (
encBuf []byte
encBuf1 [30]byte // Rune, position, optional value ID.
tokBuf []xc.Token
tu [][]uint32
)
for _, v := range src {
if pf := v.Cached(); pf != nil {
tu = append(tu, pf)
continue
}
sz, err := v.Size()
if err != nil {
return nil, err
}
if sz > mathutil.MaxInt {
return nil, fmt.Errorf("%v: file too big: %v", v.Name(), sz)
}
r, err := v.ReadCloser()
if err != nil {
return nil, err
}
lx, err := newLexer(c.context, v.Name(), int(sz), r)
if err != nil {
return nil, err
}
if err := func() (err error) {
returned := false
defer func() {
e := recover()
if !returned && err == nil {
err = fmt.Errorf("PANIC: %v\n%s", e, debugStack())
c.err(nopos, "%v", err)
}
if e := r.Close(); e != nil && err == nil {
err = e
}
}()
var pf []uint32
var t xc.Token
var toks []xc.Token
for {
ch := lx.cppScan()
if ch.Rune == ccEOF {
break
}
tokBuf = tokBuf[:0]
for {
t.Char = ch
t.Val = 0
if ch.Rune == '\n' {
toks = append(trimSpace(tokBuf), t)
break
}
if _, ok := tokHasVal[ch.Rune]; ok {
t.Val = dict.ID(lx.TokenBytes(nil))
}
tokBuf = append(tokBuf, t)
if ch = lx.cppScan(); ch.Rune == ccEOF {
if !c.tweaks.InjectFinalNL {
c.errPos(lx.last.Pos(), "file is missing final newline")
}
ch.Rune = '\n'
}
}
var encPos token.Pos
encBuf = encBuf[:0]
for _, t := range toks {
n := binary.PutUvarint(encBuf1[:], uint64(t.Rune))
pos := t.Pos()
n += binary.PutUvarint(encBuf1[n:], uint64(pos-encPos))
encPos = pos
if t.Val != 0 {
n += binary.PutUvarint(encBuf1[n:], uint64(t.Val))
}
encBuf = append(encBuf, encBuf1[:n]...)
}
id := dict.ID(encBuf)
if int64(id) > math.MaxUint32 {
panic("internal error 4")
}
pf = append(pf, uint32(id))
}
v.Cache(pf)
tu = append(tu, pf)
returned = true
return nil
}(); err != nil {
return nil, err
}
}
return &cppReader{tu: tu}, nil
}
func (c *cpp) eval(r tokenReader, w tokenWriter) (err error) {
c.macros[idFile] = &Macro{ReplacementToks: []xc.Token{{Char: lex.NewChar(0, STRINGLITERAL)}}}
c.macros[idLine] = &Macro{ReplacementToks: []xc.Token{{Char: lex.NewChar(0, INTCONST)}}}
if cs := c.expand(r, w, conds(nil).push(condZero), 0); len(cs) != 1 || cs.tos() != condZero {
return fmt.Errorf("unexpected top of condition stack value: %v", cs)
}
return nil
}
// [1]pg 1.
//
// expand(TS ) /* recur, substitute, pushback, rescan */
// {
// if TS is {} then
// // ---------------------------------------------------------- A
// return {};
//
// else if TS is T^HS • TS’ and T is in HS then
// //----------------------------------------------------------- B
// return T^HS • expand(TS’);
//
// else if TS is T^HS • TS’ and T is a "()-less macro" then
// // ---------------------------------------------------------- C
// return expand(subst(ts(T ),{},{},HS ∪{T},{}) • TS’ );
//
// else if TS is T^HS •(•TS’ and T is a "()’d macro" then
// // ---------------------------------------------------------- D
// check TS’ is actuals • )^HS’ • TS’’ and actuals are "correct for T"
// return expand(subst(ts(T ),fp(T ),actuals,(HS ∩HS’) ∪{T },{}) • TS’’);
//
// // ------------------------------------------------------------------ E
// note TS must be T^HS • TS’
// return T^HS • expand(TS’);
// }
func (c *cpp) expand(r tokenReader, w tokenWriter, cs conds, lvl int) conds {
for {
t := r.read()
switch t.Rune {
case ccEOF:
// -------------------------------------------------- A
return cs
case DIRECTIVE:
cs = c.directive(r, w, cs)
t.Rune = '\n'
t.Val = 0
w.write(t)
if f := c.tweaks.TrackExpand; f != nil && lvl == 0 {
f("\n")
}
case IDENTIFIER:
if !cs.on() {
break
}
nm := t.Val
if c.hideSet[nm] != 0 {
// ------------------------------------------ B
w.write(t)
continue
}
m := c.macros[nm]
if m != nil && !m.IsFnLike {
switch nm {
case idFile:
m.ReplacementToks[0].Val = dict.SID(fmt.Sprintf("%q", c.position(t).Filename))
case idLine:
m.ReplacementToks[0].Val = dict.SID(fmt.Sprint(c.position(t).Line))
}
// ------------------------------------------ C
c.hideSet[nm]++
toks := c.subst(m, nil)
for i, v := range toks {
toks[i].Char = lex.NewChar(t.Pos(), v.Rune)
}
r.ungets(c.sanitize(toks)...)
c.hideSet[nm]--
continue
}
if m != nil && m.IsFnLike {
// ------------------------------------------ D
var sentinels []xc.Token
again:
switch t2 := r.read(); t2.Rune {
case SENTINEL, '\n':
sentinels = append(sentinels, t2)
goto again
case '(':
// ok
case ccEOF:
r.ungets(sentinels...)
w.write(t)
continue
case ' ':
goto again
default:
r.ungets(sentinels...)
w.write(t)
w.write(t2)
continue
}
ap := c.actuals(m, r)
t.Rune = SENTINEL
sentinels = append([]xc.Token{t}, sentinels...)
toks := append(c.subst(m, ap), sentinels...)
for i, v := range toks {
toks[i].Char = lex.NewChar(t.Pos(), v.Rune)
}
c.hideSet[nm]++
r.ungets(c.sanitize(toks)...)
continue
}
w.write(t)
if f := c.tweaks.TrackExpand; f != nil && lvl == 0 {
f(TokSrc(t))
}
case SENTINEL:
if !cs.on() {
panic("internal error 5")
}
c.hideSet[t.Val]--
if c.hideSet[t.Val] < 0 {
panic(PrettyString(t))
}
default:
// -------------------------------------------------- E
if !cs.on() {
break
}
w.write(t)
if f := c.tweaks.TrackExpand; f != nil && lvl == 0 {
f(TokSrc(t))
}
}
}
}
func (c *cpp) sanitize(toks []xc.Token) []xc.Token {
for i, v := range toks {
if v.Rune == IDENTIFIER && c.hideSet[v.Val] != 0 {
toks[i].Rune = NON_REPL
}
}
return toks
}
func (c *cpp) actuals(m *Macro, r tokenReader) (out [][]xc.Token) {
var lvl, n int
for {
t := r.read()
if t.Rune < 0 {
c.err(t, "unexpected EOF")
return nil
}
switch t.Rune {
case ',':
if lvl == 0 {
n++
continue
}
case ')':
if lvl == 0 {
for i, v := range out {
out[i] = trimSpace(v)
}
for len(out) < len(m.Args) {
out = append(out, nil)
}
return out
}
lvl--
case '(':
lvl++
}
for len(out) <= n {
out = append(out, []xc.Token{})
}
if t.Rune == '\n' {
t.Rune = ' '
}
out[n] = append(out[n], t)
}
}
func (c *cpp) expands(toks []xc.Token) (out []xc.Token) {
var r, w tokenBuffer
r.toks = toks
c.expand(&r, &w, conds(nil).push(condZero), 1)
return w.toks
}
// [1]pg 2.
//
// subst(IS,FP,AP,HS,OS ) /* substitute args, handle stringize and paste */
// {
// if IS is {} then
// // ---------------------------------------------------------- A
// return hsadd(HS,OS);
//
// else if IS is #•T•IS’ and T is FP[i] then
// // ---------------------------------------------------------- B
// return subst(IS’,FP,AP,HS,OS • stringize(select(i,AP)));
//
// else if IS is ## • T • IS’ and T is FP[i] then
// {
// // ---------------------------------------------------------- C
// if select(i,AP ) is {} then /* only if actuals can be empty */
// // -------------------------------------------------- D
// return subst(IS’,FP,AP,HS,OS);
// else
// // -------------------------------------------------- E
// return subst(IS’,FP,AP,HS,glue(OS,select(i,AP)));
// }
//
// else if IS is ## • T^HS’ • IS’ then
// // ---------------------------------------------------------- F
// return subst(IS’,FP,AP,HS,glue(OS,T^HS’ ));
//
// else if IS is T•##^HS’ • IS’ and T is FP[i] then
// {
// // ---------------------------------------------------------- G
// if select(i,AP ) is {} then /* only if actuals can be empty */
// {
// // -------------------------------------------------- H
// if IS’ is T’ • IS’’ and T’ is FP[j] then
// // ------------------------------------------ I
// return subst(IS’’,FP,AP,HS,OS • select(j,AP));
// else
// // ------------------------------------------ J
// return subst(IS’,FP,AP,HS,OS);
// }
// else
// // -------------------------------------------------- K
// return subst(##^HS’ • IS’,FP,AP,HS,OS • select(i,AP));
//
// }
//
// else if IS is T•IS’ and T is FP[i] then
// // ---------------------------------------------------------- L
// return subst(IS’,FP,AP,HS,OS • expand(select(i,AP)));
//
// // ------------------------------------------------------------------ M
// note IS must be T^HS’ • IS’
// return subst(IS’,FP,AP,HS,OS • THS’);
// }
func (c *cpp) subst(m *Macro, ap [][]xc.Token) (out []xc.Token) {
// dbg("%s %v %v", m.def.S(), m.variadic, ap)
repl := m.ReplacementToks
var arg []xc.Token
for {
if len(repl) == 0 {
// -------------------------------------------------- A
return trimSpace(out)
}
if repl[0].Rune == '#' && len(repl) > 1 && repl[1].Rune == IDENTIFIER && m.param(ap, repl[1].Val, &arg) {
// -------------------------------------------------- B
out = append(out, c.stringize(arg))
repl = repl[2:]
continue
}
if repl[0].Rune == '#' && len(repl) > 2 && repl[1].Rune == ' ' && repl[2].Rune == IDENTIFIER && m.param(ap, repl[2].Val, &arg) {
// -------------------------------------------------- B
out = append(out, c.stringize(arg))
repl = repl[3:]
continue
}
if repl[0].Rune == PPPASTE && len(repl) > 1 && repl[1].Rune == IDENTIFIER && m.param(ap, repl[1].Val, &arg) {
// -------------------------------------------------- C
if len(arg) == 0 {
// ------------------------------------------ D
repl = repl[2:]
continue
}
// -------------------------------------------------- E
_, out = c.glue(out, arg)
repl = repl[2:]
continue
}
if repl[0].Rune == PPPASTE && len(repl) > 2 && repl[1].Rune == ' ' && repl[2].Rune == IDENTIFIER && m.param(ap, repl[2].Val, &arg) {
// -------------------------------------------------- C
if len(arg) == 0 {
// ------------------------------------------ D
repl = repl[3:]
continue
}
// -------------------------------------------------- E
_, out = c.glue(out, arg)
repl = repl[3:]
continue
}
if repl[0].Rune == PPPASTE && len(repl) > 1 && repl[1].Rune != ' ' {
// -------------------------------------------------- F
_, out = c.glue(out, repl[1:2])
repl = repl[2:]
continue
}
if repl[0].Rune == PPPASTE && len(repl) > 2 && repl[1].Rune == ' ' {
// -------------------------------------------------- F
_, out = c.glue(out, repl[2:3])
repl = repl[3:]
continue
}
if len(repl) > 1 && repl[0].Rune == IDENTIFIER && m.param(ap, repl[0].Val, &arg) && repl[1].Rune == PPPASTE {
// -------------------------------------------------- G
if len(arg) == 0 {
// ------------------------------------------ H
panic(c.position(repl[0]))
}
// -------------------------------------------------- K
out = append(out, arg...)
repl = repl[1:]
continue
}
if len(repl) > 2 && repl[0].Rune == IDENTIFIER && m.param(ap, repl[0].Val, &arg) && repl[1].Rune == ' ' && repl[2].Rune == PPPASTE {
// -------------------------------------------------- G
if len(arg) == 0 {
// ------------------------------------------ H
if len(repl) > 3 && repl[3].Rune == IDENTIFIER && m.param(ap, repl[3].Val, &arg) {
// ---------------------------------- I
panic("TODO")
}
// ------------------------------------------ J
repl = repl[3:]
continue
}
// -------------------------------------------------- K
out = append(out, arg...)
repl = repl[2:]
continue
}
if repl[0].Rune == IDENTIFIER && m.param(ap, repl[0].Val, &arg) {
// -------------------------------------------------- L
out = append(out, c.expands(arg)...)
repl = repl[1:]
continue
}
// ---------------------------------------------------------- M
out = append(out, repl[0])
repl = repl[1:]
}
}
// paste last of left side with first of right side
//
// [1] pg. 3
func (c *cpp) glue(ls, rs []xc.Token) (n int, out []xc.Token) {
for len(ls) != 0 && ls[len(ls)-1].Rune == ' ' {
ls = ls[:len(ls)-1]
}
for len(rs) != 0 && rs[0].Rune == ' ' {
rs = rs[1:]
n++
}
if len(rs) == 0 {
panic("TODO")
}
if len(ls) == 0 {
return n, rs
}
l := ls[len(ls)-1]
ls = ls[:len(ls)-1]
r := rs[0]
rs = rs[1:]
n++
switch l.Rune {
case '#':
switch r.Rune {
case '#':
l.Rune = PPPASTE
default:
panic(PrettyString([]xc.Token{l, r}))
}
default:
switch l.Rune {
case STRINGLITERAL:
s := TokSrc(l)
if len(s) > 2 && s[0] == '"' && s[len(s)-1] == '"' {
s = s[1 : len(s)-1]
}
l.Val = dict.SID(s + TokSrc(r))
default:
l.Val = dict.SID(TokSrc(l) + TokSrc(r))
}
}
return n, append(append(ls, l), rs...)
}
// Given a token sequence, stringize returns a single string literal token
// containing the concatenated spellings of the tokens.
//
// [1] pg. 3
func (c *cpp) stringize(s []xc.Token) xc.Token {
var a []string
for _, v := range s {
switch v.Rune {
case CHARCONST, LONGCHARCONST, LONGSTRINGLITERAL, STRINGLITERAL:
s := fmt.Sprintf("%q", TokSrc(v))
a = append(a, s[1:len(s)-1])
default:
a = append(a, TokSrc(v))
}
}
if v := dict.SID(fmt.Sprintf(`"%s"`, strings.Join(a, ""))); v != 0 {
var t xc.Token
if len(s) != 0 {
t = s[0]
}
t.Rune = STRINGLITERAL
t.Val = v
return t
}
return xc.Token{}
}
func (c *cpp) directive(r tokenReader, w tokenWriter, cs conds) (y conds) {
line := c.line(r)
if len(line) == 0 {
return cs
}
if f := c.tweaks.TrackExpand; f != nil {
s0 := fmt.Sprint(cs)
defer func() { f(fmt.Sprintf("#%s // %v->%v %v", toksDump(line, ""), s0, y, c.position(line[0]))) }()
}
switch t := line[0]; t.Rune {
case ccEOF:
// nop
case IDENTIFIER:
switch t.Val {
case idDefine:
if !cs.on() {
break
}
if len(line) == 1 {
c.err(t, "empty define not allowed")
break
}
c.define(line[1:])
case idElif:
switch cs.tos() {
case condIfOff:
if _, ok := c.constExpr(line[1:]); ok {
return cs.pop().push(condIfOn)
}
case condIfOn:
return cs.pop().push(condIfSkip)
case condIfSkip:
// nop
default:
panic(fmt.Errorf("%v: %v", c.position(t), cs.tos()))
}
case idElse:
switch cs.tos() {
case condIfOff:
return cs.pop().push(condIfOn)
case condIfOn:
return cs.pop().push(condIfOff)
case condIfSkip:
// nop
default:
panic(fmt.Errorf("%v: %v", c.position(t), cs.tos()))
}
case idError:
if !cs.on() {
break
}
panic(fmt.Errorf("%v: ERROR: %v", c.position(t), toksDump(line, "")))
case idIf:
if !cs.on() {
return cs.push(condIfSkip)
}
switch _, ok := c.constExpr(line[1:]); {
case ok:
return cs.push(condIfOn)
default:
return cs.push(condIfOff)
}
case idIfdef:
if !cs.on() {
return cs.push(condIfSkip)
}
line = trimAllSpace(line[1:])
if len(line) == 0 {
c.err(t, "empty #ifdef not allowed")
break
}
if len(line) > 1 {
c.err(t, "extra tokens after #ifdef not allowed")
break
}
if line[0].Rune != IDENTIFIER {
c.err(line[0], "expected identifier")
break
}
if _, ok := c.macros[line[0].Val]; ok {
return cs.push(condIfOn)
}
return cs.push(condIfOff)
case idIfndef:
if !cs.on() {
return cs.push(condIfSkip)
}
line = trimAllSpace(line[1:])
if len(line) == 0 {
c.err(t, "empty #ifndef not allowed")
break
}
if len(line) > 1 {
c.err(t, "extra tokens after #ifndef not allowed")
break
}
if line[0].Rune != IDENTIFIER {
c.err(line[0], "expected identifier")
break
}
if _, ok := c.macros[line[0].Val]; ok {
return cs.push(condIfOff)
}
return cs.push(condIfOn)
case
idIncludeNext,
idInclude:
if !cs.on() {
break
}
line = trimAllSpace(line[1:])
if len(line) == 0 {
c.err(t, "empty include not allowed")
break
}