File: Tab.cs

package info (click to toggle)
coco-cs 20110419-5.2
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 256 kB
  • sloc: cs: 3,416; makefile: 55; sh: 1
file content (1218 lines) | stat: -rwxr-xr-x 38,387 bytes parent folder | download | duplicates (3)
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
/*-------------------------------------------------------------------------
Tab.cs -- Symbol Table Management
Compiler Generator Coco/R,
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
extended by M. Loeberbauer & A. Woess, Univ. of Linz
with improvements by Pat Terry, Rhodes University

This program is free software; you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation; either version 2, or (at your option) any 
later version.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License 
for more details.

You should have received a copy of the GNU General Public License along 
with this program; if not, write to the Free Software Foundation, Inc., 
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

As an exception, it is allowed to write an extension of Coco/R that is
used as a plugin in non-free software.

If not otherwise stated, any source code generated by Coco/R (other than 
Coco/R itself) does not fall under the GNU General Public License.
-------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Text;
using System.Collections;

namespace at.jku.ssw.Coco {

public class Position {  // position of source code stretch (e.g. semantic action, resolver expressions)
	public readonly int beg;      // start relative to the beginning of the file
	public readonly int end;      // end of stretch
	public readonly int col;      // column number of start position
	public readonly int line;     // line number of start position
	
	public Position(int beg, int end, int col, int line) {
		this.beg = beg; this.end = end; this.col = col; this.line = line;
	}
}


//=====================================================================
// Symbol
//=====================================================================
	
public class Symbol {
	
	// token kinds
	public const int fixedToken    = 0; // e.g. 'a' ('b' | 'c') (structure of literals)
	public const int classToken    = 1;	// e.g. digit {digit}   (at least one char class)
	public const int litToken      = 2; // e.g. "while"
	public const int classLitToken = 3; // e.g. letter {letter} but without literals that have the same structure
	
	public int      n;           // symbol number
	public int      typ;         // t, nt, pr, unknown, rslv /* ML 29_11_2002 slv added */ /* AW slv --> rslv */
	public string   name;        // symbol name
	public Node     graph;       // nt: to first node of syntax graph
	public int      tokenKind;   // t:  token kind (fixedToken, classToken, ...)
	public bool     deletable;   // nt: true if nonterminal is deletable
	public bool     firstReady;  // nt: true if terminal start symbols have already been computed
	public BitArray first;       // nt: terminal start symbols
	public BitArray follow;      // nt: terminal followers
	public BitArray nts;         // nt: nonterminals whose followers have to be added to this sym
	public int      line;        // source text line number of item in this node
	public Position attrPos;     // nt: position of attributes in source text (or null)
	public Position semPos;      // pr: pos of semantic action in source text (or null)
	                             // nt: pos of local declarations in source text (or null)

	public Symbol(int typ, string name, int line) {
		this.typ = typ; this.name = name; this.line = line;
	}
}


//=====================================================================
// Node
//=====================================================================

public class Node {
	// constants for node kinds
	public const int t    =  1;  // terminal symbol
	public const int pr   =  2;  // pragma
	public const int nt   =  3;  // nonterminal symbol
	public const int clas =  4;  // character class
	public const int chr  =  5;  // character
	public const int wt   =  6;  // weak terminal symbol
	public const int any  =  7;  // 
	public const int eps  =  8;  // empty
	public const int sync =  9;  // synchronization symbol
	public const int sem  = 10;  // semantic action: (. .)
	public const int alt  = 11;  // alternative: |
	public const int iter = 12;  // iteration: { }
	public const int opt  = 13;  // option: [ ]
	public const int rslv = 14;  // resolver expr
	
	public const int normalTrans  = 0;		// transition codes
	public const int contextTrans = 1;
	
	public int      n;			// node number
	public int      typ;		// t, nt, wt, chr, clas, any, eps, sem, sync, alt, iter, opt, rslv
	public Node     next;		// to successor node
	public Node     down;		// alt: to next alternative
	public Node     sub;		// alt, iter, opt: to first node of substructure
	public bool     up;			// true: "next" leads to successor in enclosing structure
	public Symbol   sym;		// nt, t, wt: symbol represented by this node
	public int      val;		// chr:  ordinal character value
													// clas: index of character class
	public int      code;		// chr, clas: transition code
	public BitArray set;		// any, sync: the set represented by this node
	public Position pos;		// nt, t, wt: pos of actual attributes
	                            // sem:       pos of semantic action in source text
	                            // rslv:       pos of resolver in source text
	public int      line;		// source text line number of item in this node
	public State    state;	// DFA state corresponding to this node
													// (only used in DFA.ConvertToStates)

	public Node(int typ, Symbol sym, int line) {
		this.typ = typ; this.sym = sym; this.line = line;
	}
}

//=====================================================================
// Graph 
//=====================================================================

public class Graph {	
	public Node l;	// left end of graph = head
	public Node r;	// right end of graph = list of nodes to be linked to successor graph
	
	public Graph() {
		l = null; r = null;
	}
	
	public Graph(Node left, Node right) {
		l = left; r = right;
	}
	
	public Graph(Node p) {
		l = p; r = p;
	}
}

//=====================================================================
// Sets 
//=====================================================================

public class Sets {
	
	public static int Elements(BitArray s) {
		int max = s.Count;
		int n = 0;
		for (int i=0; i<max; i++)
			if (s[i]) n++;
		return n;
	}
	
	public static bool Equals(BitArray a, BitArray b) {
		int max = a.Count;
		for (int i=0; i<max; i++)
			if (a[i] != b[i]) return false;
		return true;
	}
	
	public static bool Intersect(BitArray a, BitArray b) { // a * b != {}
		int max = a.Count;
		for (int i=0; i<max; i++)
			if (a[i] && b[i]) return true;
		return false;
	}
	
	public static void Subtract(BitArray a, BitArray b) { // a = a - b
		BitArray c = (BitArray) b.Clone();
		a.And(c.Not());
	}
	
}

//=====================================================================
// CharClass
//=====================================================================

public class CharClass {	
	public int n;       	// class number
	public string name;		// class name
	public CharSet set;	// set representing the class

	public CharClass(string name, CharSet s) {
		this.name = name; this.set = s;
	}
}


//=====================================================================
// Tab
//=====================================================================

public class Tab {
	public Position semDeclPos;       // position of global semantic declarations
	public CharSet ignored;           // characters ignored by the scanner
	public bool[] ddt = new bool[10]; // debug and test switches
	public Symbol gramSy;             // root nonterminal; filled by ATG
	public Symbol eofSy;              // end of file symbol
	public Symbol noSym;              // used in case of an error
	public BitArray allSyncSets;      // union of all synchronisation sets
	public Hashtable literals;        // symbols that are used as literals
	
	public string srcName;            // name of the atg file (including path)
	public string srcDir;             // directory path of the atg file
	public string nsName;             // namespace for generated files
	public string frameDir;           // directory containing the frame files
	public string outDir;             // directory for generated files
	public bool checkEOF = true;      // should coco generate a check for EOF at
	                                  //   the end of Parser.Parse():
	public bool emitLines;            // emit #line pragmas for semantic actions
	                                  //   in the generated parser

	BitArray visited;                 // mark list for graph traversals
	Symbol curSy;                     // current symbol in computation of sets
	
	Parser parser;                    // other Coco objects
	TextWriter trace;
	Errors errors;

	public Tab(Parser parser) {
		this.parser = parser;
		trace = parser.trace;
		errors = parser.errors;
		eofSy = NewSym(Node.t, "EOF", 0);
		dummyNode = NewNode(Node.eps, null, 0);
		literals = new Hashtable();
	}

	//---------------------------------------------------------------------
	//  Symbol list management
	//---------------------------------------------------------------------
	
	public ArrayList terminals = new ArrayList();
	public ArrayList pragmas = new ArrayList();
	public ArrayList nonterminals = new ArrayList();
	
	string[] tKind = {"fixedToken", "classToken", "litToken", "classLitToken"};
	
	public Symbol NewSym(int typ, string name, int line) {
		if (name.Length == 2 && name[0] == '"') {
			parser.SemErr("empty token not allowed"); name = "???";
		}
		Symbol sym = new Symbol(typ, name, line);
		switch (typ) {
			case Node.t:  sym.n = terminals.Count; terminals.Add(sym); break;
			case Node.pr: pragmas.Add(sym); break;
			case Node.nt: sym.n = nonterminals.Count; nonterminals.Add(sym); break;
		}
		return sym;
	}

	public Symbol FindSym(string name) {
		foreach (Symbol s in terminals)
			if (s.name == name) return s;
		foreach (Symbol s in nonterminals)
			if (s.name == name) return s;
		return null;
	}
	
	int Num(Node p) {
		if (p == null) return 0; else return p.n;
	}
	
	void PrintSym(Symbol sym) {
		trace.Write("{0,3} {1,-14} {2}", sym.n, Name(sym.name), nTyp[sym.typ]);
		if (sym.attrPos==null) trace.Write(" false "); else trace.Write(" true  ");
		if (sym.typ == Node.nt) {
			trace.Write("{0,5}", Num(sym.graph));
			if (sym.deletable) trace.Write(" true  "); else trace.Write(" false ");
		} else
			trace.Write("            ");
		trace.WriteLine("{0,5} {1}", sym.line, tKind[sym.tokenKind]);
	}

	public void PrintSymbolTable() {
		trace.WriteLine("Symbol Table:");
		trace.WriteLine("------------"); trace.WriteLine();
		trace.WriteLine(" nr name          typ  hasAt graph  del    line tokenKind");
		foreach (Symbol sym in terminals) PrintSym(sym);
		foreach (Symbol sym in pragmas) PrintSym(sym);
		foreach (Symbol sym in nonterminals) PrintSym(sym);
		trace.WriteLine();
		trace.WriteLine("Literal Tokens:");
		trace.WriteLine("--------------");
		foreach (DictionaryEntry e in literals) {
			trace.WriteLine("_" + ((Symbol)e.Value).name + " = " + e.Key + ".");
		}
		trace.WriteLine();
	}
	
	public void PrintSet(BitArray s, int indent) {
		int col, len;
		col = indent;
		foreach (Symbol sym in terminals) {
			if (s[sym.n]) {
				len = sym.name.Length;
				if (col + len >= 80) {
					trace.WriteLine();
					for (col = 1; col < indent; col++) trace.Write(" ");
				}
				trace.Write("{0} ", sym.name);
				col += len + 1;
			}
		}
		if (col == indent) trace.Write("-- empty set --");
		trace.WriteLine();
	}
	
	//---------------------------------------------------------------------
	//  Syntax graph management
	//---------------------------------------------------------------------
	
	public ArrayList nodes = new ArrayList();
	public string[] nTyp =
		{"    ", "t   ", "pr  ", "nt  ", "clas", "chr ", "wt  ", "any ", "eps ",
		 "sync", "sem ", "alt ", "iter", "opt ", "rslv"};
	Node dummyNode;
	
	public Node NewNode(int typ, Symbol sym, int line) {
		Node node = new Node(typ, sym, line);
		node.n = nodes.Count;
		nodes.Add(node);
		return node;
	}
	
	public Node NewNode(int typ, Node sub) {
		Node node = NewNode(typ, null, 0);
		node.sub = sub;
		return node;
	}
	
	public Node NewNode(int typ, int val, int line) {
		Node node = NewNode(typ, null, line);
		node.val = val;
		return node;
	}
	
	public void MakeFirstAlt(Graph g) {
		g.l = NewNode(Node.alt, g.l); g.l.line = g.l.sub.line;
		g.r.up = true;
		g.l.next = g.r;
		g.r = g.l;
	}
	
	// The result will be in g1
	public void MakeAlternative(Graph g1, Graph g2) {
		g2.l = NewNode(Node.alt, g2.l); g2.l.line = g2.l.sub.line;
		g2.l.up = true;
		g2.r.up = true;
		Node p = g1.l; while (p.down != null) p = p.down;
		p.down = g2.l;
		p = g1.r; while (p.next != null) p = p.next;
		// append alternative to g1 end list
		p.next = g2.l;
		// append g2 end list to g1 end list
		g2.l.next = g2.r;
	}
	
	// The result will be in g1
	public void MakeSequence(Graph g1, Graph g2) {
		Node p = g1.r.next; g1.r.next = g2.l; // link head node
		while (p != null) {  // link substructure
			Node q = p.next; p.next = g2.l;
			p = q;
		}
		g1.r = g2.r;
	}
	
	public void MakeIteration(Graph g) {
		g.l = NewNode(Node.iter, g.l);
		g.r.up = true;
		Node p = g.r;
		g.r = g.l;
		while (p != null) {
			Node q = p.next; p.next = g.l;
			p = q;
		}
	}
	
	public void MakeOption(Graph g) {
		g.l = NewNode(Node.opt, g.l);
		g.r.up = true;
		g.l.next = g.r;
		g.r = g.l;
	}
	
	public void Finish(Graph g) {
		Node p = g.r;
		while (p != null) {
			Node q = p.next; p.next = null;
			p = q;
		}
	}
	
	public void DeleteNodes() {
		nodes = new ArrayList();
		dummyNode = NewNode(Node.eps, null, 0);
	}
	
	public Graph StrToGraph(string str) {
		string s = Unescape(str.Substring(1, str.Length-2));
		if (s.Length == 0) parser.SemErr("empty token not allowed");
		Graph g = new Graph();
		g.r = dummyNode;
		for (int i = 0; i < s.Length; i++) {
			Node p = NewNode(Node.chr, (int)s[i], 0);
			g.r.next = p; g.r = p;
		}
		g.l = dummyNode.next; dummyNode.next = null;
		return g;
	}
	
  public void SetContextTrans(Node p) { // set transition code in the graph rooted at p
    while (p != null) {
      if (p.typ == Node.chr || p.typ == Node.clas) {
        p.code = Node.contextTrans;
      } else if (p.typ == Node.opt || p.typ == Node.iter) {
        SetContextTrans(p.sub);
      } else if (p.typ == Node.alt) {
        SetContextTrans(p.sub); SetContextTrans(p.down);
      }
      if (p.up) break;
      p = p.next;
    }
  }
	
	//------------ graph deletability check -----------------

	public static bool DelGraph(Node p) {
		return p == null || DelNode(p) && DelGraph(p.next);
	}
	
	public static bool DelSubGraph(Node p) {
		return p == null || DelNode(p) && (p.up || DelSubGraph(p.next));
	}
	
	public static bool DelNode(Node p) {
		if (p.typ == Node.nt) return p.sym.deletable;
		else if (p.typ == Node.alt) return DelSubGraph(p.sub) || p.down != null && DelSubGraph(p.down);
		else return p.typ == Node.iter || p.typ == Node.opt || p.typ == Node.sem 
			|| p.typ == Node.eps || p.typ == Node.rslv || p.typ == Node.sync;
	}
	
	//----------------- graph printing ----------------------
	
	string Ptr(Node p, bool up) {
		string ptr = (p == null) ? "0" : p.n.ToString();
		return (up) ? ("-" + ptr) : ptr;
	}
	
	string Pos(Position pos) {
		if (pos == null) return "     "; else return String.Format("{0,5}", pos.beg);
	}
	
	public string Name(string name) {
		return (name + "           ").Substring(0, 12);
		// found no simpler way to get the first 12 characters of the name
		// padded with blanks on the right
	}
	
	public void PrintNodes() {
		trace.WriteLine("Graph nodes:");
		trace.WriteLine("----------------------------------------------------");
		trace.WriteLine("   n type name          next  down   sub   pos  line");
		trace.WriteLine("                               val  code");
		trace.WriteLine("----------------------------------------------------");
		foreach (Node p in nodes) {
			trace.Write("{0,4} {1} ", p.n, nTyp[p.typ]);
			if (p.sym != null)
				trace.Write("{0,12} ", Name(p.sym.name));
			else if (p.typ == Node.clas) {
				CharClass c = (CharClass)classes[p.val];
				trace.Write("{0,12} ", Name(c.name));
			} else trace.Write("             ");
			trace.Write("{0,5} ", Ptr(p.next, p.up));
			switch (p.typ) {
				case Node.t: case Node.nt: case Node.wt:
					trace.Write("             {0,5}", Pos(p.pos)); break;
				case Node.chr:
					trace.Write("{0,5} {1,5}       ", p.val, p.code); break;
				case Node.clas:
					trace.Write("      {0,5}       ", p.code); break;
				case Node.alt: case Node.iter: case Node.opt:
					trace.Write("{0,5} {1,5}       ", Ptr(p.down, false), Ptr(p.sub, false)); break;
				case Node.sem:
					trace.Write("             {0,5}", Pos(p.pos)); break;
				case Node.eps: case Node.any: case Node.sync:
					trace.Write("                  "); break;
			}
			trace.WriteLine("{0,5}", p.line);
		}
		trace.WriteLine();
	}
	

	//---------------------------------------------------------------------
	//  Character class management
	//---------------------------------------------------------------------
	
	public ArrayList classes = new ArrayList();
	public int dummyName = 'A';

	public CharClass NewCharClass(string name, CharSet s) {
		if (name == "#") name = "#" + (char)dummyName++;
		CharClass c = new CharClass(name, s);
		c.n = classes.Count;
		classes.Add(c);
		return c;
	}

	public CharClass FindCharClass(string name) {
		foreach (CharClass c in classes)
			if (c.name == name) return c;
		return null;
	}
	
	public CharClass FindCharClass(CharSet s) {
		foreach (CharClass c in classes)
			if (s.Equals(c.set)) return c;
		return null;
	}
	
	public CharSet CharClassSet(int i) {
		return ((CharClass)classes[i]).set;
	}
	
	//----------- character class printing

	string Ch(int ch) {
		if (ch < ' ' || ch >= 127 || ch == '\'' || ch == '\\') return ch.ToString();
		else return String.Format("'{0}'", (char)ch);
	}
	
	void WriteCharSet(CharSet s) {
		for (CharSet.Range r = s.head; r != null; r = r.next)
			if (r.from < r.to) { trace.Write(Ch(r.from) + ".." + Ch(r.to) + " "); }
			else { trace.Write(Ch(r.from) + " "); }
	}
	
	public void WriteCharClasses () {
		foreach (CharClass c in classes) {
			trace.Write("{0,-10}: ", c.name);
			WriteCharSet(c.set);
			trace.WriteLine();
		}
		trace.WriteLine();
	}
	

	//---------------------------------------------------------------------
	//  Symbol set computations
	//---------------------------------------------------------------------

	/* Computes the first set for the graph rooted at p */
	BitArray First0(Node p, BitArray mark) {
		BitArray fs = new BitArray(terminals.Count);
		while (p != null && !mark[p.n]) {
			mark[p.n] = true;
			switch (p.typ) {
				case Node.nt: {
					if (p.sym.firstReady) fs.Or(p.sym.first);
					else fs.Or(First0(p.sym.graph, mark));
					break;
				}
				case Node.t: case Node.wt: {
					fs[p.sym.n] = true; break;
				}
				case Node.any: {
					fs.Or(p.set); break;
				}
				case Node.alt: {
					fs.Or(First0(p.sub, mark));
					fs.Or(First0(p.down, mark));
					break;
				}
				case Node.iter: case Node.opt: {
					fs.Or(First0(p.sub, mark));
					break;
				}
			}
			if (!DelNode(p)) break;
			p = p.next;
		}
		return fs;
	}
	
	public BitArray First(Node p) {
		BitArray fs = First0(p, new BitArray(nodes.Count));
		if (ddt[3]) {
			trace.WriteLine(); 
			if (p != null) trace.WriteLine("First: node = {0}", p.n);
			else trace.WriteLine("First: node = null");
			PrintSet(fs, 0);
		}
		return fs;
	}

	void CompFirstSets() {
		foreach (Symbol sym in nonterminals) {
			sym.first = new BitArray(terminals.Count);
			sym.firstReady = false;
		}
		foreach (Symbol sym in nonterminals) {
			sym.first = First(sym.graph);
			sym.firstReady = true;
		}
	}
	
	void CompFollow(Node p) {
		while (p != null && !visited[p.n]) {
			visited[p.n] = true;
			if (p.typ == Node.nt) {
				BitArray s = First(p.next);
				p.sym.follow.Or(s);
				if (DelGraph(p.next))
					p.sym.nts[curSy.n] = true;
			} else if (p.typ == Node.opt || p.typ == Node.iter) {
				CompFollow(p.sub);
			} else if (p.typ == Node.alt) {
				CompFollow(p.sub); CompFollow(p.down);
			}
			p = p.next;
		}
	}
	
	void Complete(Symbol sym) {
		if (!visited[sym.n]) {
			visited[sym.n] = true;
			foreach (Symbol s in nonterminals) {
				if (sym.nts[s.n]) {
					Complete(s);
					sym.follow.Or(s.follow);
					if (sym == curSy) sym.nts[s.n] = false;
				}
			}
		}
	}
	
	void CompFollowSets() {
		foreach (Symbol sym in nonterminals) {
			sym.follow = new BitArray(terminals.Count);
			sym.nts = new BitArray(nonterminals.Count);
		}
		gramSy.follow[eofSy.n] = true;
		visited = new BitArray(nodes.Count);
		foreach (Symbol sym in nonterminals) { // get direct successors of nonterminals
			curSy = sym;
			CompFollow(sym.graph);
		}
		foreach (Symbol sym in nonterminals) { // add indirect successors to followers
			visited = new BitArray(nonterminals.Count);
			curSy = sym;
			Complete(sym);
		}
	}
	
	Node LeadingAny(Node p) {
		if (p == null) return null;
		Node a = null;
		if (p.typ == Node.any) a = p;
		else if (p.typ == Node.alt) {
			a = LeadingAny(p.sub);
			if (a == null) a = LeadingAny(p.down);
		}
		else if (p.typ == Node.opt || p.typ == Node.iter) a = LeadingAny(p.sub);
		if (a == null && DelNode(p) && !p.up) a = LeadingAny(p.next);
		return a;
	}
	
	void FindAS(Node p) { // find ANY sets
		Node a;
		while (p != null) {
			if (p.typ == Node.opt || p.typ == Node.iter) {
				FindAS(p.sub);
				a = LeadingAny(p.sub);
				if (a != null) Sets.Subtract(a.set, First(p.next));
			} else if (p.typ == Node.alt) {
				BitArray s1 = new BitArray(terminals.Count);
				Node q = p;
				while (q != null) {
					FindAS(q.sub);
					a = LeadingAny(q.sub);
					if (a != null)
						Sets.Subtract(a.set, First(q.down).Or(s1));
					else
						s1.Or(First(q.sub));
					q = q.down;
				}
			}

			// Remove alternative terminals before ANY, in the following
			// examples a and b must be removed from the ANY set:
			// [a] ANY, or {a|b} ANY, or [a][b] ANY, or (a|) ANY, or
			// A = [a]. A ANY
			if (DelNode(p)) {
				a = LeadingAny(p.next);
				if (a != null) {
					Node q = (p.typ == Node.nt) ? p.sym.graph : p.sub;
					Sets.Subtract(a.set, First(q));
				}
			}

			if (p.up) break;
			p = p.next;
		}
	}
	
	void CompAnySets() {
		foreach (Symbol sym in nonterminals) FindAS(sym.graph);
	}
	
	public BitArray Expected(Node p, Symbol curSy) {
		BitArray s = First(p);
		if (DelGraph(p)) s.Or(curSy.follow);
		return s;
	}

	// does not look behind resolvers; only called during LL(1) test and in CheckRes
	public BitArray Expected0(Node p, Symbol curSy) {
		if (p.typ == Node.rslv) return new BitArray(terminals.Count);
		else return Expected(p, curSy);
	}

	void CompSync(Node p) {
		while (p != null && !visited[p.n]) {
			visited[p.n] = true;
			if (p.typ == Node.sync) {
				BitArray s = Expected(p.next, curSy);
				s[eofSy.n] = true;
				allSyncSets.Or(s);
				p.set = s;
			} else if (p.typ == Node.alt) {
				CompSync(p.sub); CompSync(p.down);
			} else if (p.typ == Node.opt || p.typ == Node.iter)
				CompSync(p.sub);
			p = p.next;
		}
	}
	
	void CompSyncSets() {
		allSyncSets = new BitArray(terminals.Count);
		allSyncSets[eofSy.n] = true;
		visited = new BitArray(nodes.Count);
		foreach (Symbol sym in nonterminals) {
			curSy = sym;
			CompSync(curSy.graph);
		}
	}
	
	public void SetupAnys() {
		foreach (Node p in nodes)
			if (p.typ == Node.any) {
				p.set = new BitArray(terminals.Count, true);
				p.set[eofSy.n] = false;
			}
	}
	
	public void CompDeletableSymbols() {
		bool changed;
		do {
			changed = false;
			foreach (Symbol sym in nonterminals)
				if (!sym.deletable && sym.graph != null && DelGraph(sym.graph)) {
					sym.deletable = true; changed = true;
				}
		} while (changed);
		foreach (Symbol sym in nonterminals)
			if (sym.deletable) errors.Warning("  " + sym.name + " deletable");
	}
	
	public void RenumberPragmas() {
		int n = terminals.Count;
		foreach (Symbol sym in pragmas) sym.n = n++;
	}

	public void CompSymbolSets() {
		CompDeletableSymbols();
		CompFirstSets();
		CompAnySets();
		CompFollowSets();
		CompSyncSets();
		if (ddt[1]) {
			trace.WriteLine();
			trace.WriteLine("First & follow symbols:");
			trace.WriteLine("----------------------"); trace.WriteLine();
			foreach (Symbol sym in nonterminals) {
				trace.WriteLine(sym.name);
				trace.Write("first:   "); PrintSet(sym.first, 10);
				trace.Write("follow:  "); PrintSet(sym.follow, 10);
				trace.WriteLine();
			}
		}
		if (ddt[4]) {
			trace.WriteLine();
			trace.WriteLine("ANY and SYNC sets:");
			trace.WriteLine("-----------------");
			foreach (Node p in nodes)
				if (p.typ == Node.any || p.typ == Node.sync) {
					trace.Write("{0,4} {1,4}: ", p.n, nTyp[p.typ]);
					PrintSet(p.set, 11);
				}
		}
	}
	
	//---------------------------------------------------------------------
	//  String handling
	//---------------------------------------------------------------------
	
	char Hex2Char(string s) {
		int val = 0;
		for (int i = 0; i < s.Length; i++) {
			char ch = s[i];
			if ('0' <= ch && ch <= '9') val = 16 * val + (ch - '0');
			else if ('a' <= ch && ch <= 'f') val = 16 * val + (10 + ch - 'a');
			else if ('A' <= ch && ch <= 'F') val = 16 * val + (10 + ch - 'A');
			else parser.SemErr("bad escape sequence in string or character");
		}
		if (val > char.MaxValue) /* pdt */
			parser.SemErr("bad escape sequence in string or character");
		return (char)val;
	}

	string Char2Hex(char ch) {
		StringWriter w = new StringWriter();
		w.Write("\\u{0:x4}", (int)ch);
		return w.ToString();
	}

	public string Unescape (string s) {
		/* replaces escape sequences in s by their Unicode values. */
		StringBuilder buf = new StringBuilder();
		int i = 0;
		while (i < s.Length) {
			if (s[i] == '\\') {
				switch (s[i+1]) {
					case '\\': buf.Append('\\'); i += 2; break;
					case '\'': buf.Append('\''); i += 2; break;
					case '\"': buf.Append('\"'); i += 2; break;
					case 'r': buf.Append('\r'); i += 2; break;
					case 'n': buf.Append('\n'); i += 2; break;
					case 't': buf.Append('\t'); i += 2; break;
					case '0': buf.Append('\0'); i += 2; break;
					case 'a': buf.Append('\a'); i += 2; break;
					case 'b': buf.Append('\b'); i += 2; break;
					case 'f': buf.Append('\f'); i += 2; break;
					case 'v': buf.Append('\v'); i += 2; break;
					case 'u': case 'x':
						if (i + 6 <= s.Length) {
							buf.Append(Hex2Char(s.Substring(i+2, 4))); i += 6; break;
						} else {
							parser.SemErr("bad escape sequence in string or character"); i = s.Length; break;
						}
					default: parser.SemErr("bad escape sequence in string or character"); i += 2; break;
				}
			} else {
				buf.Append(s[i]);
				i++;
			}
		}
		return buf.ToString();
	}

	public string Escape (string s) {
		StringBuilder buf = new StringBuilder();
		foreach (char ch in s) {
			switch(ch) {
				case '\\': buf.Append("\\\\"); break;
				case '\'': buf.Append("\\'"); break;
				case '\"': buf.Append("\\\""); break;
				case '\t': buf.Append("\\t"); break;
				case '\r': buf.Append("\\r"); break;
				case '\n': buf.Append("\\n"); break;
				default:
					if (ch < ' ' || ch > '\u007f') buf.Append(Char2Hex(ch));
					else buf.Append(ch);
					break;
			}
		}
		return buf.ToString();
	}
			
	//---------------------------------------------------------------------
	//  Grammar checks
	//---------------------------------------------------------------------
	
	public bool GrammarOk() {
		bool ok = NtsComplete() 
			&& AllNtReached() 
			&& NoCircularProductions()
			&& AllNtToTerm();
    if (ok) { CheckResolvers(); CheckLL1(); }
    return ok;
	}

	//--------------- check for circular productions ----------------------
	
	class CNode {	// node of list for finding circular productions
		public Symbol left, right;
	
		public CNode (Symbol l, Symbol r) {
			left = l; right = r;
		}
	}

	void GetSingles(Node p, ArrayList singles) {
		if (p == null) return;  // end of graph
		if (p.typ == Node.nt) {
			if (p.up || DelGraph(p.next)) singles.Add(p.sym);
		} else if (p.typ == Node.alt || p.typ == Node.iter || p.typ == Node.opt) {
			if (p.up || DelGraph(p.next)) {
				GetSingles(p.sub, singles);
				if (p.typ == Node.alt) GetSingles(p.down, singles);
			}
		}
		if (!p.up && DelNode(p)) GetSingles(p.next, singles);
	}
	
	public bool NoCircularProductions() {
		bool ok, changed, onLeftSide, onRightSide;
		ArrayList list = new ArrayList();
		foreach (Symbol sym in nonterminals) {
			ArrayList singles = new ArrayList();
			GetSingles(sym.graph, singles); // get nonterminals s such that sym-->s
			foreach (Symbol s in singles) list.Add(new CNode(sym, s));
		}
		do {
			changed = false;
			for (int i = 0; i < list.Count; i++) {
				CNode n = (CNode)list[i];
				onLeftSide = false; onRightSide = false;
				foreach (CNode m in list) {
					if (n.left == m.right) onRightSide = true;
					if (n.right == m.left) onLeftSide = true;
				}
				if (!onLeftSide || !onRightSide) {
					list.Remove(n); i--; changed = true;
				}
			}
		} while(changed);
		ok = true;
		foreach (CNode n in list) {
			ok = false;
			errors.SemErr("  " + n.left.name + " --> " + n.right.name);
		}
		return ok;
	}
	
	//--------------- check for LL(1) errors ----------------------
	
	void LL1Error(int cond, Symbol sym) {
		string s = "  LL1 warning in " + curSy.name + ": ";
		if (sym != null) s += sym.name + " is ";
		switch (cond) {
			case 1: s += "start of several alternatives"; break;
			case 2: s += "start & successor of deletable structure"; break;
			case 3: s += "an ANY node that matches no symbol"; break;
			case 4: s += "contents of [...] or {...} must not be deletable"; break;
		}
		errors.Warning(s);
	}
	
	void CheckOverlap(BitArray s1, BitArray s2, int cond) {
		foreach (Symbol sym in terminals) {
			if (s1[sym.n] && s2[sym.n]) LL1Error(cond, sym);
		}
	}
	
	void CheckAlts(Node p) {
		BitArray s1, s2;
		while (p != null) {
			if (p.typ == Node.alt) {
				Node q = p;
				s1 = new BitArray(terminals.Count);
				while (q != null) { // for all alternatives
					s2 = Expected0(q.sub, curSy);
					CheckOverlap(s1, s2, 1);
					s1.Or(s2);
					CheckAlts(q.sub);
					q = q.down;
				}
			} else if (p.typ == Node.opt || p.typ == Node.iter) {
				if (DelSubGraph(p.sub)) LL1Error(4, null); // e.g. [[...]]
				else {
					s1 = Expected0(p.sub, curSy);
					s2 = Expected(p.next, curSy);
					CheckOverlap(s1, s2, 2);
				}
				CheckAlts(p.sub);
			} else if (p.typ == Node.any) {
				if (Sets.Elements(p.set) == 0) LL1Error(3, null);
				// e.g. {ANY} ANY or [ANY] ANY or ( ANY | ANY )
			}
			if (p.up) break;
			p = p.next;
		}
	}

	public void CheckLL1() {
		foreach (Symbol sym in nonterminals) {
			curSy = sym;
			CheckAlts(curSy.graph);
		}
	}
	
	//------------- check if resolvers are legal  --------------------
	
	void ResErr(Node p, string msg) {
		errors.Warning(p.line, p.pos.col, msg);
	}
	
	void CheckRes(Node p, bool rslvAllowed) {
		while (p != null) {
			switch (p.typ) {
				case Node.alt:
					BitArray expected = new BitArray(terminals.Count);
					for (Node q = p; q != null; q = q.down)
						expected.Or(Expected0(q.sub, curSy));
					BitArray soFar = new BitArray(terminals.Count);
					for (Node q = p; q != null; q = q.down) {
						if (q.sub.typ == Node.rslv) {
						  BitArray fs = Expected(q.sub.next, curSy);
							if (Sets.Intersect(fs, soFar))
								ResErr(q.sub, "Warning: Resolver will never be evaluated. " +
								"Place it at previous conflicting alternative.");
							if (!Sets.Intersect(fs, expected))
								ResErr(q.sub, "Warning: Misplaced resolver: no LL(1) conflict.");
						} else soFar.Or(Expected(q.sub, curSy));
						CheckRes(q.sub, true);
					}
					break;
				case Node.iter: case Node.opt:
					if (p.sub.typ == Node.rslv) {
						BitArray fs = First(p.sub.next);
						BitArray fsNext = Expected(p.next, curSy);
						if (!Sets.Intersect(fs, fsNext)) 
							ResErr(p.sub, "Warning: Misplaced resolver: no LL(1) conflict.");
					}
					CheckRes(p.sub, true);
					break;
				case Node.rslv:
					if (!rslvAllowed)
						ResErr(p, "Warning: Misplaced resolver: no alternative.");
					break;
			}
			if (p.up) break;
			p = p.next;
			rslvAllowed = false;
		}
	}
	
	public void CheckResolvers() {
		foreach (Symbol sym in nonterminals) {
			curSy = sym;
			CheckRes(curSy.graph, false);
		}
	}

	//------------- check if every nts has a production --------------------
	
	public bool NtsComplete() {
		bool complete = true;
		foreach (Symbol sym in nonterminals) {
			if (sym.graph == null) {
				complete = false;
				errors.SemErr("  No production for " + sym.name);
			}
		}
		return complete;
	}
	
	//-------------- check if every nts can be reached  -----------------
	
	void MarkReachedNts(Node p) {
		while (p != null) {
			if (p.typ == Node.nt && !visited[p.sym.n]) { // new nt reached
				visited[p.sym.n] = true;
				MarkReachedNts(p.sym.graph);
			} else if (p.typ == Node.alt || p.typ == Node.iter || p.typ == Node.opt) {
				MarkReachedNts(p.sub);
				if (p.typ == Node.alt) MarkReachedNts(p.down);
			}
			if (p.up) break;
			p = p.next;
		}
	}
	
	public bool AllNtReached() {
		bool ok = true;
		visited = new BitArray(nonterminals.Count);
		visited[gramSy.n] = true;
		MarkReachedNts(gramSy.graph);
		foreach (Symbol sym in nonterminals) {
			if (!visited[sym.n]) {
				ok = false;
				errors.Warning("  " + sym.name + " cannot be reached");
			}
		}
		return ok;
	}
	
	//--------- check if every nts can be derived to terminals  ------------
	
	bool IsTerm(Node p, BitArray mark) { // true if graph can be derived to terminals
		while (p != null) {
			if (p.typ == Node.nt && !mark[p.sym.n]) return false;
			if (p.typ == Node.alt && !IsTerm(p.sub, mark) 
			&& (p.down == null || !IsTerm(p.down, mark))) return false;
			if (p.up) break;
			p = p.next;
		}
		return true;
	}
	
	public bool AllNtToTerm() {
		bool changed, ok = true;
		BitArray mark = new BitArray(nonterminals.Count);
		// a nonterminal is marked if it can be derived to terminal symbols
		do {
			changed = false;
			foreach (Symbol sym in nonterminals)
				if (!mark[sym.n] && IsTerm(sym.graph, mark)) {
					mark[sym.n] = true; changed = true;
				}
		} while (changed);
		foreach (Symbol sym in nonterminals)
			if (!mark[sym.n]) {
				ok = false;
				errors.SemErr("  " + sym.name + " cannot be derived to terminals");
			}
		return ok;
	}
	
	//---------------------------------------------------------------------
	//  Cross reference list
	//---------------------------------------------------------------------
	
	public void XRef() {
		SortedList xref = new SortedList(new SymbolComp());
		// collect lines where symbols have been defined
		foreach (Symbol sym in nonterminals) {
			ArrayList list = (ArrayList)xref[sym];
			if (list == null) {list = new ArrayList(); xref[sym] = list;}
			list.Add(- sym.line);
		}
		// collect lines where symbols have been referenced
		foreach (Node n in nodes) {
			if (n.typ == Node.t || n.typ == Node.wt || n.typ == Node.nt) {
				ArrayList list = (ArrayList)xref[n.sym];
				if (list == null) {list = new ArrayList(); xref[n.sym] = list;}
				list.Add(n.line);
			}
		}
		// print cross reference list
		trace.WriteLine();
		trace.WriteLine("Cross reference list:");
		trace.WriteLine("--------------------"); trace.WriteLine();
		foreach (Symbol sym in xref.Keys) {
			trace.Write("  {0,-12}", Name(sym.name));
			ArrayList list = (ArrayList)xref[sym];
			int col = 14;
			foreach (int line in list) {
				if (col + 5 > 80) {
					trace.WriteLine();
					for (col = 1; col <= 14; col++) trace.Write(" ");
				}
				trace.Write("{0,5}", line); col += 5;
			}
			trace.WriteLine();
		}
		trace.WriteLine(); trace.WriteLine();
	}
	
	public void SetDDT(string s) {
		s = s.ToUpper();
		foreach (char ch in s) {
			if ('0' <= ch && ch <= '9') ddt[ch - '0'] = true;
			else switch (ch) {
				case 'A' : ddt[0] = true; break; // trace automaton
				case 'F' : ddt[1] = true; break; // list first/follow sets
				case 'G' : ddt[2] = true; break; // print syntax graph
				case 'I' : ddt[3] = true; break; // trace computation of first sets
				case 'J' : ddt[4] = true; break; // print ANY and SYNC sets
				case 'P' : ddt[8] = true; break; // print statistics
				case 'S' : ddt[6] = true; break; // list symbol table
				case 'X' : ddt[7] = true; break; // list cross reference table
				default : break;
			}
		}
	}

	public void SetOption(string s) {
		string[] option = s.Split(new char[] {'='}, 2);
		string name = option[0], value = option[1];
		if ("$namespace".Equals(name)) {
			if (nsName == null) nsName = value;
		} else if ("$checkEOF".Equals(name)) {
			checkEOF = "true".Equals(value);
		}
	}

	class SymbolComp : IComparer {
		public int Compare(Object x, Object y)  {
			return ((Symbol) x).name.CompareTo(((Symbol) y).name);
		}
	}

} // end Tab

} // end namespace