-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathyacc.go
3595 lines (3188 loc) · 68.9 KB
/
yacc.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
/*
Derived from Inferno's utils/iyacc/yacc.c
http://code.google.com/p/inferno-os/source/browse/utils/iyacc/yacc.c
This copyright NOTICE applies to all files in this directory and
subdirectories, unless another copyright notice appears in a given
file or subdirectory. If you take substantial code from this software to use in
other programs, you must somehow include with it an appropriate
copyright notice that includes the copyright notice and the other
notices below. It is fine (and often tidier) to do that in a separate
file such as NOTICE, LICENCE or COPYING.
Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
Portions Copyright © 1997-1999 Vita Nuova Limited
Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
Portions Copyright © 2004,2006 Bruce Ellis
Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
Portions Copyright © 2009 The Go Authors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package main
// yacc
// major difference is lack of stem ("y" variable)
//
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"strconv"
"strings"
"unicode"
)
// the following are adjustable
// according to memory size
const (
ACTSIZE = 240000
NSTATES = 16000
TEMPSIZE = 16000
SYMINC = 50 // increase for non-term or term
RULEINC = 50 // increase for max rule length prodptr[i]
PRODINC = 100 // increase for productions prodptr
WSETINC = 50 // increase for working sets wsets
STATEINC = 200 // increase for states statemem
PRIVATE = 0xE000 // unicode private use
// relationships which must hold:
// TEMPSIZE >= NTERMS + NNONTERM + 1;
// TEMPSIZE >= NSTATES;
//
NTBASE = 010000
ERRCODE = 8190
ACCEPTCODE = 8191
YYLEXUNK = 3
TOKSTART = 4 //index of first defined token
)
// no, left, right, binary assoc.
const (
NOASC = iota
LASC
RASC
BASC
)
// flags for state generation
const (
DONE = iota
MUSTDO
MUSTLOOKAHEAD
)
// flags for a rule having an action, and being reduced
const (
ACTFLAG = 1 << (iota + 2)
REDFLAG
)
// output parser flags
const yyFlag = -1000
// parse tokens
const (
IDENTIFIER = PRIVATE + iota
MARK
TERM
LEFT
RIGHT
BINARY
PREC
LCURLY
IDENTCOLON
NUMBER
START
TYPEDEF
TYPENAME
UNION
ERROR
)
const ENDFILE = 0
const EMPTY = 1
const WHOKNOWS = 0
const OK = 1
const NOMORE = -1000
// macros for getting associativity and precedence levels
func ASSOC(i int) int { return i & 3 }
func PLEVEL(i int) int { return (i >> 4) & 077 }
func TYPE(i int) int { return (i >> 10) & 077 }
// macros for setting associativity and precedence levels
func SETASC(i, j int) int { return i | j }
func SETPLEV(i, j int) int { return i | (j << 4) }
func SETTYPE(i, j int) int { return i | (j << 10) }
// I/O descriptors
var finput *bufio.Reader // input file
var stderr *bufio.Writer
var ftable *bufio.Writer // y.go file
var fcode = &bytes.Buffer{} // saved code
var foutput *bufio.Writer // y.output file
var fmtImported bool // output file has recorded an import of "fmt"
var oflag string // -o [y.go] - y.go file
var vflag string // -v [y.output] - y.output file
var lflag bool // -l - disable line directives
var prefix string // name prefix for identifiers, default yy
func init() {
flag.StringVar(&oflag, "o", "y.go", "parser output")
flag.StringVar(&prefix, "p", "yy", "name prefix to use in generated code")
flag.StringVar(&vflag, "v", "y.output", "create parsing tables")
flag.BoolVar(&lflag, "l", false, "disable line directives")
}
var initialstacksize = 16
// communication variables between various I/O routines
var infile string // input file name
var numbval int // value of an input number
var tokname string // input token name, slop for runes and 0
var tokflag = false
// structure declarations
type Lkset []int
type Pitem struct {
prod []int
off int // offset within the production
first int // first term or non-term in item
prodno int // production number for sorting
}
type Item struct {
pitem Pitem
look Lkset
}
type Symb struct {
name string
noconst bool
value int
}
type Wset struct {
pitem Pitem
flag int
ws Lkset
}
// storage of types
var ntypes int // number of types defined
var typeset = make(map[int]string) // pointers to type tags
// token information
var ntokens = 0 // number of tokens
var tokset []Symb
var toklev []int // vector with the precedence of the terminals
// nonterminal information
var nnonter = -1 // the number of nonterminals
var nontrst []Symb
var start int // start symbol
// state information
var nstate = 0 // number of states
var pstate = make([]int, NSTATES+2) // index into statemem to the descriptions of the states
var statemem []Item
var tystate = make([]int, NSTATES) // contains type information about the states
var tstates []int // states generated by terminal gotos
var ntstates []int // states generated by nonterminal gotos
var mstates = make([]int, NSTATES) // chain of overflows of term/nonterm generation lists
var lastred int // number of last reduction of a state
var defact = make([]int, NSTATES) // default actions of states
// lookahead set information
var nolook = 0 // flag to turn off lookahead computations
var tbitset = 0 // size of lookahead sets
var clset Lkset // temporary storage for lookahead computations
// working set information
var wsets []Wset
var cwp int
// storage for action table
var amem []int // action table storage
var memp int // next free action table position
var indgo = make([]int, NSTATES) // index to the stored goto table
// temporary vector, indexable by states, terms, or ntokens
var temp1 = make([]int, TEMPSIZE) // temporary storage, indexed by terms + ntokens or states
var lineno = 1 // current input line number
var fatfl = 1 // if on, error is fatal
var nerrors = 0 // number of errors
// assigned token type values
var extval = 0
// grammar rule information
var nprod = 1 // number of productions
var prdptr [][]int // pointers to descriptions of productions
var levprd []int // precedence levels for the productions
var rlines []int // line number for this rule
// statistics collection variables
var zzgoent = 0
var zzgobest = 0
var zzacent = 0
var zzexcp = 0
var zzclose = 0
var zzrrconf = 0
var zzsrconf = 0
var zzstate = 0
// optimizer arrays
var yypgo [][]int
var optst [][]int
var ggreed []int
var pgo []int
var maxspr int // maximum spread of any entry
var maxoff int // maximum offset into a array
var maxa int
// storage for information about the nonterminals
var pres [][][]int // vector of pointers to productions yielding each nonterminal
var pfirst []Lkset
var pempty []int // vector of nonterminals nontrivially deriving e
// random stuff picked out from between functions
var indebug = 0 // debugging flag for cpfir
var pidebug = 0 // debugging flag for putitem
var gsdebug = 0 // debugging flag for stagen
var cldebug = 0 // debugging flag for closure
var pkdebug = 0 // debugging flag for apack
var g2debug = 0 // debugging for go2gen
var adb = 0 // debugging for callopt
type Resrv struct {
name string
value int
}
var resrv = []Resrv{
{"binary", BINARY},
{"left", LEFT},
{"nonassoc", BINARY},
{"prec", PREC},
{"right", RIGHT},
{"start", START},
{"term", TERM},
{"token", TERM},
{"type", TYPEDEF},
{"union", UNION},
{"struct", UNION},
{"error", ERROR},
}
type Error struct {
lineno int
tokens []string
msg string
}
var errors []Error
type Row struct {
actions []int
defaultAction int
}
var stateTable []Row
var zznewstate = 0
const EOF = -1
func main() {
setup() // initialize and read productions
tbitset = (ntokens + 32) / 32
cpres() // make table of which productions yield a given nonterminal
cempty() // make a table of which nonterminals can match the empty string
cpfir() // make a table of firsts of nonterminals
stagen() // generate the states
yypgo = make([][]int, nnonter+1)
optst = make([][]int, nstate)
output() // write the states and the tables
go2out()
hideprod()
summary()
callopt()
others()
exit(0)
}
func setup() {
var j, ty int
stderr = bufio.NewWriter(os.Stderr)
foutput = nil
flag.Parse()
if flag.NArg() != 1 {
usage()
}
if initialstacksize < 1 {
// never set so cannot happen
fmt.Fprintf(stderr, "yacc: stack size too small\n")
usage()
}
yaccpar = strings.Replace(yaccpartext, "$$", prefix, -1)
openup()
fmt.Fprintf(ftable, "// Code generated by goyacc %s. DO NOT EDIT.\n", strings.Join(os.Args[1:], " "))
defin(0, "$end")
extval = PRIVATE // tokens start in unicode 'private use'
defin(0, "error")
defin(1, "$accept")
defin(0, "$unk")
i := 0
t := gettok()
outer:
for {
switch t {
default:
errorf("syntax error tok=%v", t-PRIVATE)
case MARK, ENDFILE:
break outer
case ';':
// Do nothing.
case START:
t = gettok()
if t != IDENTIFIER {
errorf("bad %%start construction")
}
start = chfind(1, tokname)
case ERROR:
lno := lineno
var tokens []string
for {
t := gettok()
if t == ':' {
break
}
if t != IDENTIFIER && t != IDENTCOLON {
errorf("bad syntax in %%error")
}
tokens = append(tokens, tokname)
if t == IDENTCOLON {
break
}
}
if gettok() != IDENTIFIER {
errorf("bad syntax in %%error")
}
errors = append(errors, Error{lno, tokens, tokname})
case TYPEDEF:
t = gettok()
if t != TYPENAME {
errorf("bad syntax in %%type")
}
ty = numbval
for {
t = gettok()
switch t {
case IDENTIFIER:
t = chfind(1, tokname)
if t < NTBASE {
j = TYPE(toklev[t])
if j != 0 && j != ty {
errorf("type redeclaration of token %s",
tokset[t].name)
} else {
toklev[t] = SETTYPE(toklev[t], ty)
}
} else {
j = nontrst[t-NTBASE].value
if j != 0 && j != ty {
errorf("type redeclaration of nonterminal %v",
nontrst[t-NTBASE].name)
} else {
nontrst[t-NTBASE].value = ty
}
}
continue
case ',':
continue
}
break
}
continue
case UNION:
cpyunion()
case LEFT, BINARY, RIGHT, TERM:
// nonzero means new prec. and assoc.
lev := t - TERM
if lev != 0 {
i++
}
ty = 0
// get identifiers so defined
t = gettok()
// there is a type defined
if t == TYPENAME {
ty = numbval
t = gettok()
}
for {
switch t {
case ',':
t = gettok()
continue
case ';':
// Do nothing.
case IDENTIFIER:
j = chfind(0, tokname)
if j >= NTBASE {
errorf("%v defined earlier as nonterminal", tokname)
}
if lev != 0 {
if ASSOC(toklev[j]) != 0 {
errorf("redeclaration of precedence of %v", tokname)
}
toklev[j] = SETASC(toklev[j], lev)
toklev[j] = SETPLEV(toklev[j], i)
}
if ty != 0 {
if TYPE(toklev[j]) != 0 {
errorf("redeclaration of type of %v", tokname)
}
toklev[j] = SETTYPE(toklev[j], ty)
}
t = gettok()
if t == NUMBER {
tokset[j].value = numbval
t = gettok()
}
continue
}
break
}
continue
case LCURLY:
cpycode()
}
t = gettok()
}
if t == ENDFILE {
errorf("unexpected EOF before %%")
}
fmt.Fprintf(fcode, "switch %snt {\n", prefix)
moreprod()
prdptr[0] = []int{NTBASE, start, 1, 0}
nprod = 1
curprod := make([]int, RULEINC)
t = gettok()
if t != IDENTCOLON {
errorf("bad syntax on first rule")
}
if start == 0 {
prdptr[0][1] = chfind(1, tokname)
}
// read rules
// put into prdptr array in the format
// target
// followed by id's of terminals and non-terminals
// followed by -nprod
for t != MARK && t != ENDFILE {
mem := 0
// process a rule
rlines[nprod] = lineno
ruleline := lineno
if t == '|' {
curprod[mem] = prdptr[nprod-1][0]
mem++
} else if t == IDENTCOLON {
curprod[mem] = chfind(1, tokname)
if curprod[mem] < NTBASE {
lerrorf(ruleline, "token illegal on LHS of grammar rule")
}
mem++
} else {
lerrorf(ruleline, "illegal rule: missing semicolon or | ?")
}
// read rule body
t = gettok()
for {
for t == IDENTIFIER {
curprod[mem] = chfind(1, tokname)
if curprod[mem] < NTBASE {
levprd[nprod] = toklev[curprod[mem]]
}
mem++
if mem >= len(curprod) {
ncurprod := make([]int, mem+RULEINC)
copy(ncurprod, curprod)
curprod = ncurprod
}
t = gettok()
}
if t == PREC {
if gettok() != IDENTIFIER {
lerrorf(ruleline, "illegal %%prec syntax")
}
j = chfind(2, tokname)
if j >= NTBASE {
lerrorf(ruleline, "nonterminal "+nontrst[j-NTBASE].name+" illegal after %%prec")
}
levprd[nprod] = toklev[j]
t = gettok()
}
if t != '=' {
break
}
levprd[nprod] |= ACTFLAG
fmt.Fprintf(fcode, "\n\tcase %v:", nprod)
fmt.Fprintf(fcode, "\n\t\t%sDollar = %sS[%spt-%v:%spt+1]", prefix, prefix, prefix, mem-1, prefix)
cpyact(curprod, mem)
// action within rule...
t = gettok()
if t == IDENTIFIER {
// make it a nonterminal
j = chfind(1, fmt.Sprintf("$$%v", nprod))
//
// the current rule will become rule number nprod+1
// enter null production for action
//
prdptr[nprod] = make([]int, 2)
prdptr[nprod][0] = j
prdptr[nprod][1] = -nprod
// update the production information
nprod++
moreprod()
levprd[nprod] = levprd[nprod-1] & ^ACTFLAG
levprd[nprod-1] = ACTFLAG
rlines[nprod] = lineno
// make the action appear in the original rule
curprod[mem] = j
mem++
if mem >= len(curprod) {
ncurprod := make([]int, mem+RULEINC)
copy(ncurprod, curprod)
curprod = ncurprod
}
}
}
for t == ';' {
t = gettok()
}
curprod[mem] = -nprod
mem++
// check that default action is reasonable
if ntypes != 0 && (levprd[nprod]&ACTFLAG) == 0 &&
nontrst[curprod[0]-NTBASE].value != 0 {
// no explicit action, LHS has value
tempty := curprod[1]
if tempty < 0 {
lerrorf(ruleline, "must return a value, since LHS has a type")
}
if tempty >= NTBASE {
tempty = nontrst[tempty-NTBASE].value
} else {
tempty = TYPE(toklev[tempty])
}
if tempty != nontrst[curprod[0]-NTBASE].value {
lerrorf(ruleline, "default action causes potential type clash")
}
}
moreprod()
prdptr[nprod] = make([]int, mem)
copy(prdptr[nprod], curprod)
nprod++
moreprod()
levprd[nprod] = 0
}
if TEMPSIZE < ntokens+nnonter+1 {
errorf("too many tokens (%d) or non-terminals (%d)", ntokens, nnonter)
}
//
// end of all rules
// dump out the prefix code
//
fmt.Fprintf(fcode, "\n\t}")
// put out non-literal terminals
for i := TOKSTART; i <= ntokens; i++ {
// non-literals
if !tokset[i].noconst {
fmt.Fprintf(ftable, "const %v = %v\n", tokset[i].name, tokset[i].value)
}
}
// put out names of tokens
ftable.WriteRune('\n')
fmt.Fprintf(ftable, "var %sToknames = [...]string{\n", prefix)
for i := 1; i <= ntokens; i++ {
fmt.Fprintf(ftable, "\t%q,\n", tokset[i].name)
}
fmt.Fprintf(ftable, "}\n")
// put out names of states.
// commented out to avoid a huge table just for debugging.
// re-enable to have the names in the binary.
ftable.WriteRune('\n')
fmt.Fprintf(ftable, "var %sStatenames = [...]string{\n", prefix)
// for i:=TOKSTART; i<=ntokens; i++ {
// fmt.Fprintf(ftable, "\t%q,\n", tokset[i].name);
// }
fmt.Fprintf(ftable, "}\n")
ftable.WriteRune('\n')
fmt.Fprintf(ftable, "const %sEofCode = 1\n", prefix)
fmt.Fprintf(ftable, "const %sErrCode = 2\n", prefix)
fmt.Fprintf(ftable, "const %sInitialStackSize = %v\n", prefix, initialstacksize)
//
// copy any postfix code
//
if t == MARK {
if !lflag {
fmt.Fprintf(ftable, "\n//line %v:%v\n", infile, lineno)
}
for {
c := getrune(finput)
if c == EOF {
break
}
ftable.WriteRune(c)
}
}
}
//
// allocate enough room to hold another production
//
func moreprod() {
n := len(prdptr)
if nprod >= n {
nn := n + PRODINC
aprod := make([][]int, nn)
alevprd := make([]int, nn)
arlines := make([]int, nn)
copy(aprod, prdptr)
copy(alevprd, levprd)
copy(arlines, rlines)
prdptr = aprod
levprd = alevprd
rlines = arlines
}
}
//
// define s to be a terminal if nt==0
// or a nonterminal if nt==1
//
func defin(nt int, s string) int {
val := 0
if nt != 0 {
nnonter++
if nnonter >= len(nontrst) {
anontrst := make([]Symb, nnonter+SYMINC)
copy(anontrst, nontrst)
nontrst = anontrst
}
nontrst[nnonter] = Symb{name: s}
return NTBASE + nnonter
}
// must be a token
ntokens++
if ntokens >= len(tokset) {
nn := ntokens + SYMINC
atokset := make([]Symb, nn)
atoklev := make([]int, nn)
copy(atoklev, toklev)
copy(atokset, tokset)
tokset = atokset
toklev = atoklev
}
tokset[ntokens].name = s
toklev[ntokens] = 0
// establish value for token
// single character literal
if s[0] == '\'' || s[0] == '"' {
q, err := strconv.Unquote(s)
if err != nil {
errorf("invalid token: %s", err)
}
rq := []rune(q)
if len(rq) != 1 {
errorf("character token too long: %s", s)
}
val = int(rq[0])
if val == 0 {
errorf("token value 0 is illegal")
}
tokset[ntokens].noconst = true
} else {
val = extval
extval++
if s[0] == '$' {
tokset[ntokens].noconst = true
}
}
tokset[ntokens].value = val
return ntokens
}
var peekline = 0
func gettok() int {
var i int
var match, c rune
tokname = ""
for {
lineno += peekline
peekline = 0
c = getrune(finput)
for c == ' ' || c == '\n' || c == '\t' || c == '\v' || c == '\r' {
if c == '\n' {
lineno++
}
c = getrune(finput)
}
// skip comment -- fix
if c != '/' {
break
}
lineno += skipcom()
}
switch c {
case EOF:
if tokflag {
fmt.Printf(">>> ENDFILE %v\n", lineno)
}
return ENDFILE
case '{':
ungetrune(finput, c)
if tokflag {
fmt.Printf(">>> ={ %v\n", lineno)
}
return '='
case '<':
// get, and look up, a type name (union member name)
c = getrune(finput)
for c != '>' && c != EOF && c != '\n' {
tokname += string(c)
c = getrune(finput)
}
if c != '>' {
errorf("unterminated < ... > clause")
}
for i = 1; i <= ntypes; i++ {
if typeset[i] == tokname {
numbval = i
if tokflag {
fmt.Printf(">>> TYPENAME old <%v> %v\n", tokname, lineno)
}
return TYPENAME
}
}
ntypes++
numbval = ntypes
typeset[numbval] = tokname
if tokflag {
fmt.Printf(">>> TYPENAME new <%v> %v\n", tokname, lineno)
}
return TYPENAME
case '"', '\'':
match = c
tokname = string(c)
for {
c = getrune(finput)
if c == '\n' || c == EOF {
errorf("illegal or missing ' or \"")
}
if c == '\\' {
tokname += string('\\')
c = getrune(finput)
} else if c == match {
if tokflag {
fmt.Printf(">>> IDENTIFIER \"%v\" %v\n", tokname, lineno)
}
tokname += string(c)
return IDENTIFIER
}
tokname += string(c)
}
case '%':
c = getrune(finput)
switch c {
case '%':
if tokflag {
fmt.Printf(">>> MARK %%%% %v\n", lineno)
}
return MARK
case '=':
if tokflag {
fmt.Printf(">>> PREC %%= %v\n", lineno)
}
return PREC
case '{':
if tokflag {
fmt.Printf(">>> LCURLY %%{ %v\n", lineno)
}
return LCURLY
}
getword(c)
// find a reserved word
for i := range resrv {
if tokname == resrv[i].name {
if tokflag {
fmt.Printf(">>> %%%v %v %v\n", tokname,
resrv[i].value-PRIVATE, lineno)
}
return resrv[i].value
}
}
errorf("invalid escape, or illegal reserved word: %v", tokname)
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
numbval = int(c - '0')
for {
c = getrune(finput)
if !isdigit(c) {
break
}
numbval = numbval*10 + int(c-'0')
}
ungetrune(finput, c)
if tokflag {
fmt.Printf(">>> NUMBER %v %v\n", numbval, lineno)
}
return NUMBER
default:
if isword(c) || c == '.' || c == '$' {
getword(c)
break
}
if tokflag {
fmt.Printf(">>> OPERATOR %v %v\n", string(c), lineno)
}
return int(c)
}
// look ahead to distinguish IDENTIFIER from IDENTCOLON
c = getrune(finput)
for c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\r' || c == '/' {
if c == '\n' {
peekline++
}
// look for comments
if c == '/' {
peekline += skipcom()
}
c = getrune(finput)
}
if c == ':' {
if tokflag {
fmt.Printf(">>> IDENTCOLON %v: %v\n", tokname, lineno)
}
return IDENTCOLON
}
ungetrune(finput, c)
if tokflag {
fmt.Printf(">>> IDENTIFIER %v %v\n", tokname, lineno)
}
return IDENTIFIER
}
func getword(c rune) {