summaryrefslogtreecommitdiff
path: root/BaseTools/Source/C/VfrCompile/Pccts/h/PCCTSAST.cpp
blob: a8249cdac0a26110238e83806d3d0b63441c8b19 (plain)
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
/*
 * PCCTSAST.C
 *
 * SOFTWARE RIGHTS
 *
 * We reserve no LEGAL rights to SORCERER -- SORCERER is in the public
 * domain.  An individual or company may do whatever they wish with
 * source code distributed with SORCERER or the code generated by
 * SORCERER, including the incorporation of SORCERER, or its output, into
 * commerical software.
 *
 * We encourage users to develop software with SORCERER.  However, we do
 * ask that credit is given to us for developing SORCERER.  By "credit",
 * we mean that if you incorporate our source code into one of your
 * programs (commercial product, research project, or otherwise) that you
 * acknowledge this fact somewhere in the documentation, research report,
 * etc...  If you like SORCERER and have developed a nice tool with the
 * output, please mention that you developed it using SORCERER.  In
 * addition, we ask that this header remain intact in our source code.
 * As long as these guidelines are kept, we expect to continue enhancing
 * this system and expect to make other tools available as they are
 * completed.
 *
 * SORCERER 1.00B14 and ANTLR 1.33
 * Terence Parr
 * Parr Research Corporation
 * AHPCRC, University of Minnesota
 * 1992-2000
 */

#define ANTLR_SUPPORT_CODE

#include "pcctscfg.h"

#include "PCCTSAST.h"
#include "pccts_stdarg.h"

PCCTS_NAMESPACE_STD

#include <ctype.h>

//#include "SList.h"

               /* String Scanning/Parsing Stuff */

const char *PCCTS_AST::scan_token_tbl[] = {     /* MR20 const */
	"invalid",	/*	0 */
	"LPAREN",	/*	1 */
	"RPAREN",	/*	2 */
	"PERCENT",	/*	3 */
	"INT",		/*	4 */
	"COLON",	/*	5 */
	"POUND",	/*	6 */
	"PERIOD",	/*	7 */
};

void PCCTS_AST::
addChild(PCCTS_AST *t)
{
	if ( t==NULL ) return;
	PCCTS_AST *s = down();
	if ( s!=NULL )
	{
		while ( s->right()!=NULL ) s = s->right();
		s->setRight(t);
	}
	else
		this->setDown(t);
}

void PCCTS_AST::
lisp(FILE *f)
{
	if ( down() != NULL ) /* MR23 */ printMessage(f," (");
	lisp_action(f);
	if ( down()!=NULL ) down()->lisp(f);
	if ( down() != NULL ) /* MR23 */ printMessage(f," )");
	if ( right()!=NULL ) right()->lisp(f);
}

/* build a tree (root child1 child2 ... NULL)
 * If root is NULL, simply make the children siblings and return ptr
 * to 1st sibling (child1).  If root is not single node, return NULL.
 *
 * Siblings that are actually sibling lists themselves are handled
 * correctly.  For example #( NULL, #( NULL, A, B, C), D) results
 * in the tree ( NULL A B C D ).
 *
 * Requires at least two parameters with the last one being NULL.  If
 * both are NULL, return NULL.
 *
 * The down() and right() down/right pointers are used to make the tree.
 */
PCCTS_AST *PCCTS_AST::
make(PCCTS_AST *rt, ...)
{
	va_list ap;
	register PCCTS_AST *child, *sibling=NULL, *tail=NULL /*MR23*/, *w;
	PCCTS_AST *root;

	va_start(ap, rt);
	root = rt;

	if ( root != NULL )
		if ( root->down() != NULL ) return NULL;
	child = va_arg(ap, PCCTS_AST *);
	while ( child != NULL )
	{
		/* find end of child */
		for (w=child; w->right()!=NULL; w=w->right()) {;}
		if ( sibling == NULL ) {sibling = child; tail = w;}
		else {tail->setRight(child); tail = w;}
		child = va_arg(ap, PCCTS_AST *);
	}
	if ( root==NULL ) root = sibling;
	else root->setDown(sibling);
	va_end(ap);
	return root;
}

/* The following push and pop routines are only used by ast_find_all() */

void PCCTS_AST::
_push(PCCTS_AST **st, int *sp, PCCTS_AST *e)
{
	(*sp)--;
	require((*sp)>=0, "stack overflow");
	st[(*sp)] = e;
}

PCCTS_AST *PCCTS_AST::
_pop(PCCTS_AST **st, int *sp)
{
	PCCTS_AST *e = st[*sp];
	(*sp)++;
	require((*sp)<=MaxTreeStackDepth, "stack underflow");
	return e;
}

/* Find all occurrences of u in t.
 * 'cursor' must be initialized to 't'.  It eventually
 * returns NULL when no more occurrences of 'u' are found.
 */
PCCTS_AST *PCCTS_AST::
ast_find_all(PCCTS_AST *u, PCCTS_AST **cursor)
{
	PCCTS_AST *sib;
	/*** static ***/ PCCTS_AST *template_stack[MaxTreeStackDepth];  /* MR23 Remove "static" */
	/*** static ***/ int tsp = MaxTreeStackDepth;                   /* MR23 Remove "static" */

////static int nesting = 0;                                         /* MR23 Not referenced */

	if ( *cursor == NULL ) return NULL;
	if ( *cursor!=this ) sib = *cursor;
	else {
		/* else, first time--start at top of template 't' */
		tsp = MaxTreeStackDepth;
		sib = this;
		/* bottom of stack is always a NULL--"cookie" indicates "done" */
		_push(template_stack, &tsp, NULL);
	}

keep_looking:
	if ( sib==NULL )	/* hit end of sibling list */
	{
		sib = _pop(template_stack, &tsp);
		if ( sib == NULL ) { *cursor = NULL; return NULL; }
	}

	if ( sib->type() != u->type() )
	{
		/* look for another match */
		if ( sib->down()!=NULL )
		{
			if ( sib->right()!=NULL ) _push(template_stack, &tsp, sib->right());
			sib=sib->down();
			goto keep_looking;
		}
		/* nothing below to try, try next sibling */
		sib=sib->right();
		goto keep_looking;
	}

	/* found a matching root node, try to match what's below */
	if ( match_partial(sib, u) )
	{
		/* record sibling cursor so we can pick up next from there */
		if ( sib->down()!=NULL )
		{
			if ( sib->right()!=NULL ) _push(template_stack, &tsp, sib->right());
			*cursor = sib->down();
		}
		else if ( sib->right()!=NULL ) *cursor = sib->right();
		else *cursor = _pop(template_stack, &tsp);
		return sib;
	}

	/* no match, keep searching */
	if ( sib->down()!=NULL )
	{
		if ( sib->right()!=NULL ) _push(template_stack, &tsp, sib->right());
		sib=sib->down();
	}
	else sib = sib->right();	/* else, try to right if zip below */
	goto keep_looking;
}

/* are two trees exactly alike? */
int PCCTS_AST::
match(PCCTS_AST *u)
{
	PCCTS_AST *t = this;
	PCCTS_AST *sib;

	if ( u==NULL ) return 0;

	for (sib=t; sib!=NULL&&u!=NULL; sib=sib->right(), u=u->right())
	{
		if ( sib->type() != u->type() ) return 0;
		if ( sib->down()!=NULL )
			if ( !sib->down()->match(u->down()) ) return 0;
	}
	return 1;
}

/* Is 'u' a subtree of 't' beginning at the root? */
int PCCTS_AST::
match_partial(PCCTS_AST *t, PCCTS_AST *u)
{
	PCCTS_AST *sib;

	if ( u==NULL ) return 1;
	if ( t==NULL ) return 0; /* MR23 removed unreachable code */

	for (sib=t; sib!=NULL&&u!=NULL; sib=sib->right(), u=u->right())
	{
		if ( sib->type() != u->type() ) return 0;
		if ( sib->down()!=NULL )
			if ( !match_partial(sib->down(), u->down()) ) return 0;
	}
	return 1;
}

#ifdef _MSC_VER  // MR23
//Turn off "unreachable code" warning
#pragma warning(disable : 4702)
#endif
/* Walk the template tree 't' (matching against 'this'), filling in the
 * 'labels' array, and setting 'n' according to how many labels were matched.
 */
int PCCTS_AST::
scanmatch(ScanAST *t, PCCTS_AST **labels[], int *n)
{
	ScanAST *sib;
	PCCTS_AST *u = this;

	if ( u==NULL ) return 0;

	for (sib=t; sib!=NULL&&u!=NULL; sib=sib->right(), u=u->right())
	{
		/* make sure tokens match; token of '0' means wildcard match */
		if ( sib->type() != u->type() && sib->type()!=0 ) return 0;
		/* we have a matched token here; set label pointers if exists */
		if ( sib->label_num>0 )
		{
			require(labels!=NULL, "label found in template, but no array of labels");
			(*n)++;
			*(labels[sib->label_num-1]) = u;
		}
		/* match what's below if something there and current node is not wildcard */
		if ( sib->down()!=NULL && sib->type()!=0 )
		{
			if ( sib->down()==NULL ) 
			{
				if ( u->down()!=NULL ) 
					return 0; 
				else 
					return 1;
			}
			if ( !u->down()->scanmatch(sib->down(), labels, n) ) return 0;
		}
	}
	return 1;
}
#ifdef _MSC_VER  // MR23
#pragma warning(default : 4702)
#endif

void PCCTS_AST::
insert_after(PCCTS_AST *b)
{
	PCCTS_AST *end;
	if ( b==NULL ) return;
	/* find end of b's child list */
	for (end=b; end->right()!=NULL; end=end->right()) {;}
	end->setRight(this->right());
	this->setRight(b);
}

void PCCTS_AST::
append(PCCTS_AST *b)
{
	PCCTS_AST *end;
	require(b!=NULL, "append: NULL input tree");
	/* find end of child list */
	for (end=this; end->right()!=NULL; end=end->right()) {;}
	end->setRight(b);
}

PCCTS_AST *PCCTS_AST::
tail()
{
	PCCTS_AST *end;
	/* find end of child list */
	for (end=this; end->right()!=NULL; end=end->right()) {;}
	return end;
}

PCCTS_AST *PCCTS_AST::
bottom()
{
	PCCTS_AST *end;
	/* find end of child list */
	for (end=this; end->down()!=NULL; end=end->down()) {;}
	return end;
}

PCCTS_AST *PCCTS_AST::
cut_between(PCCTS_AST *a, PCCTS_AST *b)
{
	PCCTS_AST *end, *ret;
	if (a==NULL||b==NULL) return NULL;
	/* find node pointing to b */
	for (end=a; end->right()!=NULL&&end->right()!=b; end=end->right())
		{;}
	if (end->right()==NULL) return NULL; //ast_cut_between: a,b not connected
	end->setRight(NULL);	/* don't want it point to 'b' anymore */
	ret = a->right();
	a->setRight(b);
	return ret;
}

#ifdef NOT_YET
SList *PCCTS_AST::
to_slist()
{
	SList *list = new SList;
	PCCTS_AST *p;

	for (p=this; p!=NULL; p=p->right())
	{
		list->add(p);
	}
	return list;
}
#endif

void PCCTS_AST::
tfree()
{
	PCCTS_AST *t = this;
    if ( t->down()!=NULL ) t->down()->tfree();
    if ( t->right()!=NULL ) t->right()->tfree();
    delete t;
}

int PCCTS_AST::
nsiblings()
{
	PCCTS_AST *t = this;
	int n=0;

	while ( t!=NULL )
	{
		n++;
		t = t->right();
	}
	return n;
}

PCCTS_AST *PCCTS_AST::
sibling_index(int i)
{
	PCCTS_AST *t = this;
	int j=1;
	require(i>0, "sibling_index: i<=0");

	while ( t!=NULL )
	{
		if ( j==i ) return t;
		j++;
		t = t->right();
	}
	return NULL;
}

/* Assume this is a root node of a tree--
 * duplicate that node and what's below; ignore siblings of root node.
 */

// MR9 23-Sep-97 RJV
// MR9
// MR9 RJV: Original version only duplicated the node and down elements.
// MR9      Made copies of the pointers to sibling.
// MR9      Changed call "down()->deepCopy()" to "down()->deepCopyBushy()"
// MR9

PCCTS_AST *PCCTS_AST::
deepCopy()
{
	PCCTS_AST *u = this->shallowCopy();
	if ( down()!=NULL ) u->setDown(down()->deepCopyBushy());
    u->setRight(NULL);
	return u;
}

/* Copy all nodes including siblings of root. */
PCCTS_AST *PCCTS_AST::
deepCopyBushy()
{
	PCCTS_AST *u = this->shallowCopy();
	/* copy the rest of the tree */
	if ( down()!=NULL ) u->setDown(down()->deepCopyBushy());
	if ( right()!=NULL ) u->setRight(right()->deepCopyBushy());
	return u;
}

void PCCTS_AST::
scanast_free(ScanAST *t)
{
    if ( t == NULL ) return;
    scanast_free( t->down() );
    scanast_free( t->right() );
    free( (char *) t );							// MR1
}

/*
 * scan
 *
 * This function is like scanf(): it attempts to match a template
 * against an input tree.  A variable number of tree pointers
 * may be set according to the '%i' labels in the template string.
 * For example:
 *
 *   t->ast_scan("#( 6 #(5 %1:4 %2:3) #(1 %3:3 %4:3) )",
 *            &w, &x, &y, &z);
 *
 * Naturally, you'd want this converted from
 *
 *	 t->ast_scan("#( RangeOp #(Minus %1:IConst %2:Var) #(Plus %3:Var %4Var) )",
 *			  &w, &x, &y, &z);
 *
 * by SORCERER.
 *
 * This function call must be done withing a SORCERER file because SORCERER
 * must convert the token references to the associated token number.
 *
 * This functions parses the template and creates trees which are then
 * matched against the input tree.  The labels are set as they are
 * encountered; hence, partial matches may leave some pointers set
 * and some NULL.  This routines initializes all argument pointers to NULL
 * at the beginning.
 *
 * This function returns the number of labels matched.
 */
int PCCTS_AST::
ast_scan(char *templ, ...)
{
	va_list ap;
	ScanAST *tmpl;
	int n, i, found=0;
	PCCTS_AST ***label_ptrs=NULL;

	va_start(ap, templ);

	/* make a ScanAST tree out of the template */
	tmpl = stringparser_parse_scanast(templ, &n);

	/* make an array out of the labels */
	if ( n>0 )
	{
		label_ptrs = (PCCTS_AST ***) calloc(n, sizeof(PCCTS_AST **));
		require(label_ptrs!=NULL, "scan: out of memory");
		for (i=1; i<=n; i++)
		{
			label_ptrs[i-1] = va_arg(ap, PCCTS_AST **);
			*(label_ptrs[i-1]) = NULL;
		}
	}

	/* match the input tree against the template */
	scanmatch(tmpl, label_ptrs, &found);

	scanast_free(tmpl);
	free( (char *) label_ptrs);					// MR1

	return found;
}

ScanAST *PCCTS_AST::
new_scanast(int tok)
{
    ScanAST *p = (ScanAST *) calloc(1, sizeof(ScanAST));
//
//  7-Apr-97 133MR1
//
    if ( p == NULL )
        panic("out of memory\n");			// MR23
	p->_token = tok;
	return p;
}

ScanAST *PCCTS_AST::
stringparser_parse_scanast(char *templ, int *num_labels)
{
	StringLexer lex;
	StringParser parser;
	ScanAST *t;

	stringlexer_init(&lex, templ);
	stringparser_init(&parser, &lex);
	t = stringparser_parse_tree(&parser);
	*num_labels = parser.num_labels;
	return t;
}

void PCCTS_AST::
stringparser_match(StringParser *parser, int token)
{
	if ( parser->token != token ) panic("bad tree in scan()");
}

/*
 * Match a tree of the form:
 *		(root child1 child2 ... childn)
 * or,
 *		node
 *
 * where the elements are integers or labeled integers.
 */
ScanAST *PCCTS_AST::
stringparser_parse_tree(StringParser *parser)
{
	ScanAST *t=NULL, *root, *child, *last=NULL /*MR23*/;

	if ( parser->token != __POUND )
	{
		return stringparser_parse_element(parser);
	}
	stringparser_match(parser,__POUND);
	parser->token = stringscan_gettok(parser->lexer);
	stringparser_match(parser,__LPAREN);
	parser->token = stringscan_gettok(parser->lexer);
	root = stringparser_parse_element(parser);
	while ( parser->token != __RPAREN )
	{
		child = stringparser_parse_element(parser);
		if ( t==NULL ) { t = child; last = t; }
		else { last->_right = child; last = child; }
	}
	stringparser_match(parser,__RPAREN);
	parser->token = stringscan_gettok(parser->lexer);
	root->_down = t;
	return root;
}

ScanAST *PCCTS_AST::
stringparser_parse_element(StringParser *parser)
{
	char ebuf[100];
	int label = 0;

	if ( parser->token == __POUND )
	{
		return stringparser_parse_tree(parser);
	}
	if ( parser->token == __PERCENT )
	{
		parser->token = stringscan_gettok(parser->lexer);
		stringparser_match(parser,__INT);
		label = atoi(parser->lexer->text);
		parser->num_labels++;
		if ( label==0 ) panic("%%0 is an invalid label");
		parser->token = stringscan_gettok(parser->lexer);
		stringparser_match(parser,__COLON);
		parser->token = stringscan_gettok(parser->lexer);
		/* can label tokens and wildcards */
		if ( parser->token != __INT && parser->token != __PERIOD )
			panic("can only label tokens");
	}
	if ( parser->token == __INT )
	{
		ScanAST *p = new_scanast(atoi(parser->lexer->text));
		parser->token = stringscan_gettok(parser->lexer);
		p->label_num = label;
		return p;
	}
	if ( parser->token == __PERIOD )
	{
		ScanAST *p = new_scanast(0);	/* token of 0 is wildcard */
		parser->token = stringscan_gettok(parser->lexer);
		p->label_num = label;
		return p;
	}
	sprintf(ebuf, "mismatch token in scan(): %s", scan_token_str(parser->token));
	panic(ebuf);
	return NULL;
}

void PCCTS_AST::
stringparser_init(StringParser *parser, StringLexer *input)
{
	parser->lexer = input;
	parser->token = stringscan_gettok(parser->lexer);
	parser->num_labels = 0;
}

void PCCTS_AST::
stringlexer_init(StringLexer *scanner, char *input)
{
	scanner->text[0]='\0';
	scanner->input = input;
	scanner->p = input;
	stringscan_advance(scanner);
}

void PCCTS_AST::
stringscan_advance(StringLexer *scanner)
{
	if ( *(scanner->p) == '\0' ) scanner->c = __StringScanEOF;
	scanner->c = *(scanner->p)++;
}

int PCCTS_AST::
stringscan_gettok(StringLexer *scanner)
{
	char *index = &scanner->text[0];
	char ebuf[100]; /* MR23 Remove static */

	while ( isspace(scanner->c) ) { stringscan_advance(scanner); }
	if ( isdigit(scanner->c) )
	{
		int tok = __INT;
		while ( isdigit(scanner->c) ) {
			*index++ = (char) /* static_cast<char> */ (scanner->c);     // MR23
			stringscan_advance(scanner);
		}
		*index = '\0';
		return tok;
	}
	switch ( scanner->c )
	{
		case '#' : stringscan_advance(scanner); return __POUND;
		case '(' : stringscan_advance(scanner); return __LPAREN;
		case ')' : stringscan_advance(scanner); return __RPAREN;
		case '%' : stringscan_advance(scanner); return __PERCENT;
		case ':' : stringscan_advance(scanner); return __COLON;
		case '.' : stringscan_advance(scanner); return __PERIOD;
		case '\0' : return __StringScanEOF;
		case __StringScanEOF : return __StringScanEOF;
		default  :
			sprintf(ebuf, "invalid char in scan: '%c'", scanner->c);
			panic(ebuf);
	}
	return __StringScanEOF;	// never reached
}

const char *PCCTS_AST:: /* MR20 const */
scan_token_str(int t)
{
	if ( VALID_SCAN_TOKEN(t) ) return scan_token_tbl[t];
	else if ( t==__StringScanEOF ) return "<end-of-string>";
	else return "<invalid-token>";
}

//MR23
int PCCTS_AST::printMessage(FILE* pFile, const char* pFormat, ...)
{
	va_list marker;
	va_start( marker, pFormat );
  	int iRet = vfprintf(pFile, pFormat, marker);
	va_end( marker );
	return iRet;
}