-
Notifications
You must be signed in to change notification settings - Fork 10
/
report.c
1998 lines (1892 loc) · 58.9 KB
/
report.c
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
/*
** Procedures for generating reports and tables in the LEMON parser generator.
*/
/* Generate a filename with the given suffix. Space to hold the
** name comes from malloc() and must be freed by the calling
** function.
*/
PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
{
char *name;
char *cp;
char *filename = lemp->filename;
int sz;
if( outputDir ){
cp = strrchr(filename, '/');
if( cp ) filename = cp + 1;
}
sz = lemonStrlen(filename);
sz += lemonStrlen(suffix);
if( outputDir ) sz += lemonStrlen(outputDir) + 1;
sz += 5;
name = (char*)malloc( sz );
if( name==0 ){
fprintf(stderr,"Can't allocate space for a filename.\n");
exit(1);
}
name[0] = 0;
if( outputDir ){
lemon_strcpy(name, outputDir);
lemon_strcat(name, "/");
}
lemon_strcat(name,filename);
cp = strrchr(name,'.');
if( cp ) *cp = 0;
lemon_strcat(name,suffix);
return name;
}
/* Open a file with a name based on the name of the input file,
** but with a different (specified) suffix, and return a pointer
** to the stream */
PRIVATE FILE *file_open(
struct lemon *lemp,
const char *suffix,
const char *mode
){
FILE *fp;
if( lemp->outname ) free(lemp->outname);
lemp->outname = file_makename(lemp, suffix);
fp = fopen(lemp->outname,mode);
if( fp==0 && *mode=='w' ){
fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
lemp->errorcnt++;
return 0;
}
return fp;
}
/* Print the text of a rule
*/
void rule_print(FILE *out, struct rule *rp){
int i, j;
fprintf(out, "%s",rp->lhs->name);
/* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
fprintf(out," ::=");
for(i=0; i<rp->nrhs; i++){
struct symbol *sp = rp->rhs[i];
if( sp->type==MULTITERMINAL ){
fprintf(out," %s", sp->subsym[0]->name);
for(j=1; j<sp->nsubsym; j++){
fprintf(out,"|%s", sp->subsym[j]->name);
}
}else{
fprintf(out," %s", sp->name);
}
/* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
}
}
/* Duplicate the input file without comments and without actions
** on rules */
void Reprint(struct lemon *lemp)
{
struct rule *rp;
struct symbol *sp;
int i, j, maxlen, len, ncolumns, skip;
printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
maxlen = 10;
for(i=0; i<lemp->nsymbol; i++){
sp = lemp->symbols[i];
len = lemonStrlen(sp->name);
if( len>maxlen ) maxlen = len;
}
ncolumns = 76/(maxlen+5);
if( ncolumns<1 ) ncolumns = 1;
skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
for(i=0; i<skip; i++){
printf("//");
for(j=i; j<lemp->nsymbol; j+=skip){
sp = lemp->symbols[j];
assert( sp->index==j );
printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
}
printf("\n");
}
for(rp=lemp->rule; rp; rp=rp->next){
rule_print(stdout, rp);
printf(".");
if( rp->precsym ) printf(" [%s]",rp->precsym->name);
/* if( rp->code ) printf("\n %s",rp->code); */
printf("\n");
}
}
/* Print a single rule.
*/
void RulePrint(FILE *fp, struct rule *rp, int iCursor){
struct symbol *sp;
int i, j;
fprintf(fp,"%s ::=",rp->lhs->name);
for(i=0; i<=rp->nrhs; i++){
if( i==iCursor ) fprintf(fp," *");
if( i==rp->nrhs ) break;
sp = rp->rhs[i];
if( sp->type==MULTITERMINAL ){
fprintf(fp," %s", sp->subsym[0]->name);
for(j=1; j<sp->nsubsym; j++){
fprintf(fp,"|%s",sp->subsym[j]->name);
}
}else{
fprintf(fp," %s", sp->name);
}
}
}
/* Print the rule for a configuration.
*/
void ConfigPrint(FILE *fp, struct config *cfp){
RulePrint(fp, cfp->rp, cfp->dot);
}
/* #define TEST */
#if 0
/* Print a set */
PRIVATE void SetPrint(out,set,lemp)
FILE *out;
char *set;
struct lemon *lemp;
{
int i;
char *spacer;
spacer = "";
fprintf(out,"%12s[","");
for(i=0; i<lemp->nterminal; i++){
if( SetFind(set,i) ){
fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
spacer = " ";
}
}
fprintf(out,"]\n");
}
/* Print a plink chain */
PRIVATE void PlinkPrint(out,plp,tag)
FILE *out;
struct plink *plp;
char *tag;
{
while( plp ){
fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
ConfigPrint(out,plp->cfp);
fprintf(out,"\n");
plp = plp->next;
}
}
#endif
/* Print an action to the given file descriptor. Return FALSE if
** nothing was actually printed.
*/
int PrintAction(
struct action *ap, /* The action to print */
FILE *fp, /* Print the action here */
int indent /* Indent by this amount */
){
int result = 1;
switch( ap->type ){
case SHIFT: {
struct state *stp = ap->x.stp;
fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
break;
}
case REDUCE: {
struct rule *rp = ap->x.rp;
fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
RulePrint(fp, rp, -1);
break;
}
case SHIFTREDUCE: {
struct rule *rp = ap->x.rp;
fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
RulePrint(fp, rp, -1);
break;
}
case ACCEPT:
fprintf(fp,"%*s accept",indent,ap->sp->name);
break;
case ERROR:
fprintf(fp,"%*s error",indent,ap->sp->name);
break;
case SRCONFLICT:
case RRCONFLICT:
fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
indent,ap->sp->name,ap->x.rp->iRule);
break;
case SSCONFLICT:
fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
indent,ap->sp->name,ap->x.stp->statenum);
break;
case SH_RESOLVED:
if( showPrecedenceConflict ){
fprintf(fp,"%*s shift %-7d -- dropped by precedence",
indent,ap->sp->name,ap->x.stp->statenum);
}else{
result = 0;
}
break;
case RD_RESOLVED:
if( showPrecedenceConflict ){
fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
indent,ap->sp->name,ap->x.rp->iRule);
}else{
result = 0;
}
break;
case NOT_USED:
result = 0;
break;
}
if( result && ap->spOpt ){
fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
}
return result;
}
/* Generate the "*.out" log file */
void ReportOutput(struct lemon *lemp)
{
int i, n;
struct state *stp;
struct config *cfp;
struct action *ap;
struct rule *rp;
FILE *fp;
fp = file_open(lemp,".out","wb");
if( fp==0 ) return;
for(i=0; i<lemp->nxstate; i++){
stp = lemp->sorted[i];
fprintf(fp,"State %d:\n",stp->statenum);
if( lemp->basisflag ) cfp=stp->bp;
else cfp=stp->cfp;
while( cfp ){
char buf[20];
if( cfp->dot==cfp->rp->nrhs ){
lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
fprintf(fp," %5s ",buf);
}else{
fprintf(fp," ");
}
ConfigPrint(fp,cfp);
fprintf(fp,"\n");
#if 0
SetPrint(fp,cfp->fws,lemp);
PlinkPrint(fp,cfp->fplp,"To ");
PlinkPrint(fp,cfp->bplp,"From");
#endif
if( lemp->basisflag ) cfp=cfp->bp;
else cfp=cfp->next;
}
fprintf(fp,"\n");
for(ap=stp->ap; ap; ap=ap->next){
if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
}
fprintf(fp,"\n");
}
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Symbols:\n");
fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
for(i=0; i<lemp->nsymbol; i++){
int j;
struct symbol *sp;
sp = lemp->symbols[i];
fprintf(fp, " %3d: %s", i, sp->name);
if( sp->type==NONTERMINAL ){
fprintf(fp, ":");
if( sp->lambda ){
fprintf(fp, " <lambda>");
}
for(j=0; j<lemp->nterminal; j++){
if( sp->firstset && SetFind(sp->firstset, j) ){
fprintf(fp, " %s", lemp->symbols[j]->name);
}
}
}
if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
fprintf(fp, "\n");
}
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Syntax-only Symbols:\n");
fprintf(fp, "The following symbols never carry semantic content.\n\n");
for(i=n=0; i<lemp->nsymbol; i++){
int w;
struct symbol *sp = lemp->symbols[i];
if( sp->bContent ) continue;
w = (int)strlen(sp->name);
if( n>0 && n+w>75 ){
fprintf(fp,"\n");
n = 0;
}
if( n>0 ){
fprintf(fp, " ");
n++;
}
fprintf(fp, "%s", sp->name);
n += w;
}
if( n>0 ) fprintf(fp, "\n");
fprintf(fp, "----------------------------------------------------\n");
fprintf(fp, "Rules:\n");
for(rp=lemp->rule; rp; rp=rp->next){
fprintf(fp, "%4d: ", rp->iRule);
rule_print(fp, rp);
fprintf(fp,".");
if( rp->precsym ){
fprintf(fp," [%s precedence=%d]",
rp->precsym->name, rp->precsym->prec);
}
fprintf(fp,"\n");
}
fclose(fp);
return;
}
/* Search for the file "name" which is in the same directory as
** the executable */
PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
{
const char *pathlist;
char *pathbufptr = 0;
char *pathbuf = 0;
char *path,*cp;
char c;
#ifdef __WIN32__
cp = strrchr(argv0,'\\');
#else
cp = strrchr(argv0,'/');
#endif
if( cp ){
c = *cp;
*cp = 0;
path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
*cp = c;
}else{
pathlist = getenv("PATH");
if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
if( (pathbuf != 0) && (path!=0) ){
pathbufptr = pathbuf;
lemon_strcpy(pathbuf, pathlist);
while( *pathbuf ){
cp = strchr(pathbuf,':');
if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
c = *cp;
*cp = 0;
lemon_sprintf(path,"%s/%s",pathbuf,name);
*cp = c;
if( c==0 ) pathbuf[0] = 0;
else pathbuf = &cp[1];
if( access(path,modemask)==0 ) break;
}
}
free(pathbufptr);
}
return path;
}
/* Given an action, compute the integer value for that action
** which is to be put in the action table of the generated machine.
** Return negative if no action should be generated.
*/
PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
{
int act;
switch( ap->type ){
case SHIFT: act = ap->x.stp->statenum; break;
case SHIFTREDUCE: {
/* Since a SHIFT is inherient after a prior REDUCE, convert any
** SHIFTREDUCE action with a nonterminal on the LHS into a simple
** REDUCE action: */
if( ap->sp->index>=lemp->nterminal
&& (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index)
){
act = lemp->minReduce + ap->x.rp->iRule;
}else{
act = lemp->minShiftReduce + ap->x.rp->iRule;
}
break;
}
case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
case ERROR: act = lemp->errAction; break;
case ACCEPT: act = lemp->accAction; break;
default: act = -1; break;
}
return act;
}
#define LINESIZE 1000
/* The next cluster of routines are for reading the template file
** and writing the results to the generated parser */
/* The first function transfers data from "in" to "out" until
** a line is seen which begins with "%%". The line number is
** tracked.
**
** if name!=0, then any word that begin with "Parse" is changed to
** begin with *name instead.
*/
PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
{
int i, iStart;
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
iStart = 0;
if( name ){
for(i=0; line[i]; i++){
if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
&& (i==0 || !ISALPHA(line[i-1]))
){
if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
fprintf(out,"%s",name);
i += 4;
iStart = i+1;
}
}
}
fprintf(out,"%s",&line[iStart]);
}
}
/* Skip forward past the header of the template file to the first "%%"
*/
PRIVATE void tplt_skip_header(FILE *in, int *lineno)
{
char line[LINESIZE];
while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
(*lineno)++;
}
}
/* The next function finds the template file and opens it, returning
** a pointer to the opened file. */
PRIVATE FILE *tplt_open(struct lemon *lemp)
{
static char templatename[] = "lempar.c";
char buf[1000];
FILE *in;
char *tpltname;
char *toFree = 0;
char *cp;
/* first, see if user specified a template filename on the command line. */
if (user_templatename != 0) {
if( access(user_templatename,004)==-1 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
user_templatename);
lemp->errorcnt++;
return 0;
}
in = fopen(user_templatename,"rb");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",
user_templatename);
lemp->errorcnt++;
return 0;
}
return in;
}
cp = strrchr(lemp->filename,'.');
if( cp ){
lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
}else{
lemon_sprintf(buf,"%s.lt",lemp->filename);
}
if( access(buf,004)==0 ){
tpltname = buf;
}else if( access(templatename,004)==0 ){
tpltname = templatename;
}else{
toFree = tpltname = pathsearch(lemp->argv0,templatename,0);
}
if( tpltname==0 ){
fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
templatename);
lemp->errorcnt++;
return 0;
}
in = fopen(tpltname,"rb");
if( in==0 ){
fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
lemp->errorcnt++;
}
free(toFree);
return in;
}
/* Print a #line directive line to the output file. */
PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
{
fprintf(out,"#line %d \"",lineno);
while( *filename ){
if( *filename == '\\' ) putc('\\',out);
putc(*filename,out);
filename++;
}
fprintf(out,"\"\n");
}
/* Print a string to the file and keep the linenumber up to date */
PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
{
if( str==0 ) return;
while( *str ){
putc(*str,out);
if( *str=='\n' ) (*lineno)++;
str++;
}
if( str[-1]!='\n' ){
putc('\n',out);
(*lineno)++;
}
if (!lemp->nolinenosflag) {
(*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
}
return;
}
/*
** The following routine emits code for the destructor for the
** symbol sp
*/
void emit_destructor_code(
FILE *out,
struct symbol *sp,
struct lemon *lemp,
int *lineno
){
char *cp = 0;
if( sp->type==TERMINAL ){
cp = lemp->tokendest;
if( cp==0 ) return;
fprintf(out,"{\n"); (*lineno)++;
}else if( sp->destructor ){
cp = sp->destructor;
fprintf(out,"{\n"); (*lineno)++;
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,sp->destLineno,lemp->filename);
}
}else if( lemp->vardest ){
cp = lemp->vardest;
if( cp==0 ) return;
fprintf(out,"{\n"); (*lineno)++;
}else{
assert( 0 ); /* Cannot happen */
}
for(; *cp; cp++){
if( *cp=='$' && cp[1]=='$' ){
fprintf(out,"(yypminor->yy%d)",sp->dtnum);
cp++;
continue;
}
if( *cp=='\n' ) (*lineno)++;
fputc(*cp,out);
}
fprintf(out,"\n"); (*lineno)++;
if (!lemp->nolinenosflag) {
(*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
}
fprintf(out,"}\n"); (*lineno)++;
return;
}
/*
** Return TRUE (non-zero) if the given symbol has a destructor.
*/
int has_destructor(struct symbol *sp, struct lemon *lemp)
{
int ret;
if( sp->type==TERMINAL ){
ret = lemp->tokendest!=0;
}else{
ret = lemp->vardest!=0 || sp->destructor!=0;
}
return ret;
}
/*
** Append text to a dynamically allocated string. If zText is 0 then
** reset the string to be empty again. Always return the complete text
** of the string (which is overwritten with each call).
**
** n bytes of zText are stored. If n==0 then all of zText up to the first
** \000 terminator is stored. zText can contain up to two instances of
** %d. The values of p1 and p2 are written into the first and second
** %d.
**
** If n==-1, then the previous character is overwritten.
*/
PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
static char empty[1] = { 0 };
static char *z = 0;
static int alloced = 0;
static int used = 0;
int c;
char zInt[40];
if( zText==0 ){
if( used==0 && z!=0 ) z[0] = 0;
used = 0;
return z;
}
if( n<=0 ){
if( n<0 ){
used += n;
assert( used>=0 );
}
n = lemonStrlen(zText);
}
if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
alloced = n + sizeof(zInt)*2 + used + 200;
z = (char *) realloc(z, alloced);
}
if( z==0 ) return empty;
while( n-- > 0 ){
c = *(zText++);
if( c=='%' && n>0 && zText[0]=='d' ){
lemon_sprintf(zInt, "%d", p1);
p1 = p2;
lemon_strcpy(&z[used], zInt);
used += lemonStrlen(&z[used]);
zText++;
n--;
}else{
z[used++] = (char)c;
}
}
z[used] = 0;
return z;
}
/*
** Write and transform the rp->code string so that symbols are expanded.
** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
**
** Return 1 if the expanded code requires that "yylhsminor" local variable
** to be defined.
*/
PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
char *cp, *xp;
int i;
int rc = 0; /* True if yylhsminor is used */
int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
char lhsused = 0; /* True if the LHS element has been used */
char lhsdirect; /* True if LHS writes directly into stack */
char used[MAXRHS]; /* True for each RHS element which is used */
char zLhs[50]; /* Convert the LHS symbol into this string */
char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
for(i=0; i<rp->nrhs; i++) used[i] = 0;
lhsused = 0;
if( rp->code==0 ){
static char newlinestr[2] = { '\n', '\0' };
rp->code = newlinestr;
rp->line = rp->ruleline;
rp->noCode = 1;
}else{
rp->noCode = 0;
}
if( rp->nrhs==0 ){
/* If there are no RHS symbols, then writing directly to the LHS is ok */
lhsdirect = 1;
}else if( rp->rhsalias[0]==0 ){
/* The left-most RHS symbol has no value. LHS direct is ok. But
** we have to call the destructor on the RHS symbol first. */
lhsdirect = 1;
if( has_destructor(rp->rhs[0],lemp) ){
append_str(0,0,0,0);
append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
rp->rhs[0]->index,1-rp->nrhs);
rp->codePrefix = Strsafe(append_str(0,0,0,0));
rp->noCode = 0;
}
}else if( rp->lhsalias==0 ){
/* There is no LHS value symbol. */
lhsdirect = 1;
}else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
/* The LHS symbol and the left-most RHS symbol are the same, so
** direct writing is allowed */
lhsdirect = 1;
lhsused = 1;
used[0] = 1;
if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
ErrorMsg(lemp->filename,rp->ruleline,
"%s(%s) and %s(%s) share the same label but have "
"different datatypes.",
rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
lemp->errorcnt++;
}
}else{
lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
rp->lhsalias, rp->rhsalias[0]);
zSkip = strstr(rp->code, zOvwrt);
if( zSkip!=0 ){
/* The code contains a special comment that indicates that it is safe
** for the LHS label to overwrite left-most RHS label. */
lhsdirect = 1;
}else{
lhsdirect = 0;
}
}
if( lhsdirect ){
sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
}else{
rc = 1;
sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
}
append_str(0,0,0,0);
/* This const cast is wrong but harmless, if we're careful. */
for(cp=(char *)rp->code; *cp; cp++){
if( cp==zSkip ){
append_str(zOvwrt,0,0,0);
cp += lemonStrlen(zOvwrt)-1;
dontUseRhs0 = 1;
continue;
}
if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
char saved;
for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
saved = *xp;
*xp = 0;
if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
append_str(zLhs,0,0,0);
cp = xp;
lhsused = 1;
}else{
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
if( i==0 && dontUseRhs0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s used after '%s'.",
rp->rhsalias[0], zOvwrt);
lemp->errorcnt++;
}else if( cp!=rp->code && cp[-1]=='@' ){
/* If the argument is of the form @X then substituted
** the token number of X, not the value of X */
append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
}else{
struct symbol *sp = rp->rhs[i];
int dtnum;
if( sp->type==MULTITERMINAL ){
dtnum = sp->subsym[0]->dtnum;
}else{
dtnum = sp->dtnum;
}
append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
}
cp = xp;
used[i] = 1;
break;
}
}
}
*xp = saved;
}
append_str(cp, 1, 0, 0);
} /* End loop */
/* Main code generation completed */
cp = append_str(0,0,0,0);
if( cp && cp[0] ) rp->code = Strsafe(cp);
append_str(0,0,0,0);
/* Check to make sure the LHS has been used */
if( rp->lhsalias && !lhsused ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label \"%s\" for \"%s(%s)\" is never used.",
rp->lhsalias,rp->lhs->name,rp->lhsalias);
lemp->errorcnt++;
}
/* Generate destructor code for RHS minor values which are not referenced.
** Generate error messages for unused labels and duplicate labels.
*/
for(i=0; i<rp->nrhs; i++){
if( rp->rhsalias[i] ){
if( i>0 ){
int j;
if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"%s(%s) has the same label as the LHS but is not the left-most "
"symbol on the RHS.",
rp->rhs[i]->name, rp->rhsalias[i]);
lemp->errorcnt++;
}
for(j=0; j<i; j++){
if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s used for multiple symbols on the RHS of a rule.",
rp->rhsalias[i]);
lemp->errorcnt++;
break;
}
}
}
if( !used[i] ){
ErrorMsg(lemp->filename,rp->ruleline,
"Label %s for \"%s(%s)\" is never used.",
rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
lemp->errorcnt++;
}
}else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
rp->rhs[i]->index,i-rp->nrhs+1);
}
}
/* If unable to write LHS values directly into the stack, write the
** saved LHS value now. */
if( lhsdirect==0 ){
append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
append_str(zLhs, 0, 0, 0);
append_str(";\n", 0, 0, 0);
}
/* Suffix code generation complete */
cp = append_str(0,0,0,0);
if( cp && cp[0] ){
rp->codeSuffix = Strsafe(cp);
rp->noCode = 0;
}
return rc;
}
/*
** Generate code which executes when the rule "rp" is reduced. Write
** the code to "out". Make sure lineno stays up-to-date.
*/
PRIVATE void emit_code(
FILE *out,
struct rule *rp,
struct lemon *lemp,
int *lineno
){
const char *cp;
/* Setup code prior to the #line directive */
if( rp->codePrefix && rp->codePrefix[0] ){
fprintf(out, "{%s", rp->codePrefix);
for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
}
/* Generate code to do the reduce action */
if( rp->code ){
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,rp->line,lemp->filename);
}
fprintf(out,"{%s",rp->code);
for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
fprintf(out,"}\n"); (*lineno)++;
if( !lemp->nolinenosflag ){
(*lineno)++;
tplt_linedir(out,*lineno,lemp->outname);
}
}
/* Generate breakdown code that occurs after the #line directive */
if( rp->codeSuffix && rp->codeSuffix[0] ){
fprintf(out, "%s", rp->codeSuffix);
for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
}
if( rp->codePrefix ){
fprintf(out, "}\n"); (*lineno)++;
}
return;
}
/*
** Print the definition of the union used for the parser's data stack.
** This union contains fields for every possible data type for tokens
** and nonterminals. In the process of computing and printing this
** union, also set the ".dtnum" field of every terminal and nonterminal
** symbol.
*/
void print_stack_union(
FILE *out, /* The output stream */
struct lemon *lemp, /* The main info structure for this parser */
int *plineno, /* Pointer to the line number */
int mhflag /* True if generating makeheaders output */
){
int lineno; /* The line number of the output */
char **types; /* A hash table of datatypes */
int arraysize; /* Size of the "types" array */
int maxdtlength; /* Maximum length of any ".datatype" field. */
char *stddt; /* Standardized name for a datatype */
int i,j; /* Loop counters */
unsigned hash; /* For hashing the name of a type */
const char *name; /* Name of the parser */
/* Allocate and initialize types[] and allocate stddt[] */
arraysize = lemp->nsymbol * 2;
types = (char**)calloc( arraysize, sizeof(char*) );
if( types==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
for(i=0; i<arraysize; i++) types[i] = 0;
maxdtlength = 0;
if( lemp->vartype ){
maxdtlength = lemonStrlen(lemp->vartype);
}
for(i=0; i<lemp->nsymbol; i++){
int len;
struct symbol *sp = lemp->symbols[i];
if( sp->datatype==0 ) continue;
len = lemonStrlen(sp->datatype);
if( len>maxdtlength ) maxdtlength = len;
}
stddt = (char*)malloc( maxdtlength*2 + 1 );
if( stddt==0 ){
fprintf(stderr,"Out of memory.\n");
exit(1);
}
/* Build a hash table of datatypes. The ".dtnum" field of each symbol
** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
** used for terminal symbols. If there is no %default_type defined then
** 0 is also used as the .dtnum value for nonterminals which do not specify
** a datatype using the %type directive.
*/
for(i=0; i<lemp->nsymbol; i++){
struct symbol *sp = lemp->symbols[i];
char *cp;
if( sp==lemp->errsym ){
sp->dtnum = arraysize+1;
continue;
}
if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
sp->dtnum = 0;
continue;
}
cp = sp->datatype;
if( cp==0 ) cp = lemp->vartype;
j = 0;
while( ISSPACE(*cp) ) cp++;
while( *cp ) stddt[j++] = *cp++;
while( j>0 && ISSPACE(stddt[j-1]) ) j--;
stddt[j] = 0;
if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
sp->dtnum = 0;
continue;
}
hash = 0;
for(j=0; stddt[j]; j++){
hash = hash*53 + stddt[j];
}
hash = (hash & 0x7fffffff)%arraysize;
while( types[hash] ){
if( strcmp(types[hash],stddt)==0 ){
sp->dtnum = hash + 1;
break;
}