-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrammar.cpp
703 lines (571 loc) · 18.6 KB
/
grammar.cpp
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
// ****************************************************************************
// ****************************************************************************
// grammar.cpp
// ****************************************************************************
//
// ****************************************************************************
// ****************************************************************************
// ****************************************************************************
// Includes
// ****************************************************************************
#include "common.h"
// ****************************************************************************
// Initialize Static Members
// ****************************************************************************
NTermVec NonTerm::m_nTerms;
VDVec VarDef::m_varDefs;
FDVec FuncDef::m_funcDefs;
// ****************************************************************************
// ProdEle()
// ****************************************************************************
ProdEle::ProdEle(Terminal* term)
: m_term(term),
m_isTerm(true)
{
}
ProdEle::ProdEle(NonTerm* nTerm)
: m_nonTerm(nTerm),
m_isTerm(false)
{
}
// ****************************************************************************
// Terminal()
// ****************************************************************************
Terminal::Terminal(Token::Type type)
: m_tType(type),
m_spelling("")
{
}
Terminal::Terminal(Token::Type type,
const comString& spelling)
: m_tType(type),
m_spelling(spelling)
{
}
// ****************************************************************************
// NonTerm::NonTerm()
// ****************************************************************************
NonTerm::NonTerm(const comString& name,
bool scopeEdge)
: m_name(name),
m_scopeEdge(scopeEdge)
{
m_nTerms.append(this);
}
// ****************************************************************************
// NonTerm::addProduction()
// ****************************************************************************
void
NonTerm::addProduction(Production* prod)
{
m_productions.append(prod);
}
void
NonTerm::addProduction(Terminal* term)
{
Production* prod = new Production();
m_productions.append(prod);
prod->add(term);
}
void
NonTerm::addProduction(NonTerm* nTerm)
{
Production* prod = new Production();
m_productions.append(prod);
prod->add(nTerm);
}
// ****************************************************************************
// NonTerm::dumpGrammar()
//
// This method prints out the nonterminals and their productions which compose
// the grammar constructed for the parser.
// ****************************************************************************
void
NonTerm::dumpGrammar()
{
printf("Dumping grammar to file.");
FILE* file = fopen("grammar.out", "w");
comString printable("");
for (UINT i = 0; i < m_nTerms.getNumEntries(); i++) {
NonTerm* nTerm = m_nTerms[i];
fprintf(file, "%s\n", (const char*) nTerm->m_name);
for (UINT j = 0; j < nTerm->m_productions.getNumEntries(); j++) {
Production* prod = nTerm->m_productions[j];
fprintf(file, "\t%s\n", (const char*) prod->printable(printable));
for (UINT k = 0; k < prod->getTransSchemes().getNumEntries(); k++)
fprintf(file, "\t\t%s\n", (const char*) prod->getTransSchemes()[k]->printable(printable));
}
}
fclose(file);
}
// ****************************************************************************
// ProdEle::toString()
// ****************************************************************************
const comString&
ProdEle::toString()
{
if (m_isTerm)
return ((m_term->m_spelling != "") ? m_term->m_spelling : Token::getTypeName(m_term->m_tType));
else
return m_nonTerm->getName();
}
// ****************************************************************************
// Production::printable()
// ****************************************************************************
comString&
Production::printable(comString& buf)
{
char printBuffer[128];
char* loc = printBuffer;
for (UINT i = 0; i < getNumEntries(); i++)
loc += sprintf(loc, "%s ", (const char*) m_data[i]->toString());
*(loc - 1) = '\0';
buf = printBuffer;
return buf;
}
// ****************************************************************************
// ParseTree::ParseTree()
// ****************************************************************************
ParseTree::ParseTree(NonTerm* nTerm)
: m_prodEle(nTerm),
m_numChildren(0),
m_production(NULL),
m_token(NULL),
m_type(Translator::None),
m_scopeEdge(nTerm->isScopeEdge())
{
for (UINT i = 0; i < PT_MAX_CHILDREN; i++)
m_children[i] = NULL;
}
ParseTree::ParseTree(Terminal* term,
Token* token)
: m_prodEle(term),
m_numChildren(0),
m_production(NULL),
m_token(token),
m_type(Translator::None),
m_scopeEdge(false)
{
for (UINT i = 0; i < PT_MAX_CHILDREN; i++)
m_children[i] = NULL;
}
// ****************************************************************************
// Terminal::matches()
// ****************************************************************************
bool
Terminal::matches(const Token* token)
{
if (token->getType() != m_tType)
return false;
if (m_spelling != "")
return m_spelling == token->getSpelling();
return true;
}
// ****************************************************************************
// ParseTree::addChild()
// ****************************************************************************
void
ParseTree::addChild(ParseTree* child)
{
if (m_numChildren == PT_MAX_CHILDREN) {
fprintf(stderr, "Attempted to add too many children.\n");
Global::fail();
}
m_children[m_numChildren++] = child;
child->m_parent = this;
}
// ****************************************************************************
// ParseTree::~ParseTree()
// ****************************************************************************
ParseTree::~ParseTree()
{
for (UINT i = 0; i < m_numChildren; i++)
delete m_children[i];
}
// ****************************************************************************
// ParseTree::cullChildren()
// ****************************************************************************
void
ParseTree::cullChildren()
{
for (UINT i = 0; i < m_numChildren; i++)
delete m_children[i];
m_numChildren = 0;
}
// ****************************************************************************
// ParseTree::print()
// ****************************************************************************
void
ParseTree::print(const comString& filename)
{
FILE* file = fopen((const char*) filename, "w");
this->print(0, file);
fclose(file);
}
void
ParseTree::print(UINT level,
FILE* file)
{
comString printable("");
for (UINT i = 0; i < level; i++)
fprintf(file, "\t");
fprintf(file, "%s (%s):", (const char*) m_prodEle.toString(), (const char*) Translator::typeToString(m_type));
if (m_production)
fprintf(file, " %s\n", (const char*) m_production->printable(printable));
else if (m_token)
fprintf(file, " %s\n", (const char*) m_token->printable(printable));
else
fprintf(file, "\n");
if (m_scopeEdge) {
for (UINT i = 0; i < level; i++)
fprintf(file, "\t");
fprintf(file, "v=v=v=v=v=v=v=v=v=v=v=v= SCOPE EDGE =v=v=v=v=v=v=v=v=v=v=v=v\n");
}
for (UINT i = 0; i < m_numChildren; i++)
m_children[i]->print(level + 1, file);
if (m_scopeEdge) {
for (UINT i = 0; i < level; i++)
fprintf(file, "\t");
fprintf(file, "^=^=^=^=^=^=^=^=^=^=^=^= SCOPE EDGE =^=^=^=^=^=^=^=^=^=^=^=^\n");
}
}
// ****************************************************************************
// ParseTree::typeCheck()
// ****************************************************************************
void
ParseTree::typeCheck()
{
UINT line = -1;
typeCheck(line);
}
void
ParseTree::typeCheck(UINT& lastLine)
{
if (m_numChildren) {
// If this node is a regular node, just recurse into the children.
if (!m_production->isDeclarator() && !m_production->isFuncDeclarator() && !m_production->isFuncInvocation()) {
for (UINT i = 0; i < m_numChildren; i++)
m_children[i]->typeCheck(lastLine);
} else if (m_production->isDeclarator()) {
// If this is a variable declarator, perform special declarator
// processing to add the new variable's declaration.
comString spelling;
Translator::Type type;
for (UINT i = 0; i < m_numChildren; i++) {
// Do not try and identify the type of identifiers.
if (!m_children[i]->isTerminal() || m_children[i]->getToken()->getType() != Token::Identifier)
m_children[i]->typeCheck(lastLine);
// Get the information required for the declaration.
if (m_children[i]->isTerminal()) {
if (m_children[i]->getToken()->getType() == Token::Identifier)
spelling = m_children[i]->getToken()->getSpelling();
else if (m_children[i]->getToken()->getType() == Token::PrimType)
type = m_children[i]->m_type;
}
}
// Finally, add the variable declaration.
addVarDef(spelling, type);
return;
} else if (m_production->isFuncDeclarator()) {
// If this is a function declarator, perform special declarator
// processing to add the new variable's declaration.
Translator::buildFunction(this, lastLine);
return;
} else if (m_production->isFuncInvocation()) {
// If this is a function invokation, do not try to check the types automatically.
Translator::typeCheckFunction(this, lastLine);
return;
}
for (UINT i = 0; i < m_production->getTransSchemes().getNumEntries(); i++) {
PrVec& pre = m_production->getTransSchemes()[i]->getPreVec();
bool match = true;
for (UINT j = 0; pre.getNumEntries() && j < pre.getNumEntries() - 1; j++) {
if (pre[j]->m_type != Translator::Any && pre[j]->m_type != m_children[pre[j]->m_index]->m_type) {
match = false;
break;
}
}
if (match) {
m_scheme = m_production->getTransSchemes()[i];
break;
}
}
if (!m_scheme) {
comString buf;
fprintf(stderr, "Type error in production \"%s\" originating from line %d.\n", (const char*) m_production->printable(buf), lastLine);
fprintf(stderr, "Could not match >");
for (UINT j = 0; j < m_numChildren; j++)
fprintf(stderr, "%s ", (const char*) Translator::typeToString(m_children[j]->m_type));
printf("< to schemes\n");
for (UINT j = 0; j < m_production->getTransSchemes().getNumEntries(); j++)
fprintf(stderr, "\t\"%s\"\n", (const char*) m_production->getTransSchemes()[j]->printable(buf));
Global::fail();
}
PrVec& pre = m_scheme->getPreVec();
if (pre.getNumEntries())
m_type = pre[pre.getNumEntries() - 1]->m_type;
else
m_type = Translator::None;
} else {
if (!m_token)
m_type = Translator::None;
else {
switch(m_token->getType()) {
case Token::BoolConst:
m_type = Translator::Bool;
break;
case Token::RealConst:
m_type = Translator::Float;
break;
case Token::IntConst:
m_type = Translator::Int;
break;
case Token::StrConst:
m_type = Translator::Str;
break;
case Token::Identifier:
{
VarDef* vd = findVarDef(m_token->getSpelling());
if (vd) {
m_type = vd->m_type;
} else {
fprintf(stderr, "Identifier \"%s\" on line %d not declared in this scope.\n",
(const char*) m_token->getSpelling(),
m_token->getLine());
Global::fail();
}
}
break;
case Token::PrimType:
m_type = Translator::getPrimType(m_token->getSpelling());
break;
default:
m_type = Translator::None;
break;
}
lastLine = m_token->getLine();
}
}
}
// ****************************************************************************
// Production::Production()
// ****************************************************************************
Production::Production()
: m_declarator(false),
m_fDeclarator(false),
m_funcInv(false)
{
}
// ****************************************************************************
// Production::~Production()
// ****************************************************************************
Production::~Production()
{
for (UINT i = 0; i < getNumEntries(); i++)
delete m_data[i];
}
// ****************************************************************************
// Production::matches()
// ****************************************************************************
bool
Production::matches(Production* o)
{
if (o->getNumEntries() != getNumEntries()
|| o->m_declarator != m_declarator
|| o->m_fDeclarator != m_fDeclarator
|| o->m_funcInv != m_funcInv)
return false;
for (UINT i = 0; i < getNumEntries(); i++) {
if (o->get(i)->m_isTerm != this->get(i)->m_isTerm)
return false;
if (this->get(i)->m_isTerm) {
if (this->get(i)->m_term != o->get(i)->m_term)
return false;
} else {
if (this->get(i)->m_nonTerm != o->get(i)->m_nonTerm)
return false;
}
}
return true;
}
// ****************************************************************************
// VarDef::VarDef()
// ****************************************************************************
VarDef::VarDef(const comString& rName,
const comString& oName,
Translator::Type type)
: m_preName(rName),
m_postName(oName),
m_type(type)
{
m_varDefs.append(this);
}
// ****************************************************************************
// ParseTree::addvarDef()
// ****************************************************************************
void
ParseTree::addVarDef(const comString& identifier,
Translator::Type type,
bool found)
{
// If the production associated with this node of the parse tree is a scope
// edge, this node can hold the var def. Otherwise pass it on up to the
// parent.
if (m_scopeEdge) {
// If this is the first edge found, ignore it and go to the next one.
// We do this because let statements are themselves in scope edges and
// therefore require this hack to make it so declarations exist outside
// the let statements.
if (found) {
// We construct the post translation identifier by taking the pointer
// to this node (which is by definition unique for each node) and
// appending the pretranslation identifier to it. This should give us an
// identifier that looks something like "x034841829_identifierName"
char buf[128];
sprintf(buf, "v%p_%s", this, (const char*) identifier);
m_varDefs.append(new VarDef(identifier, buf, type));
} else {
m_parent->addVarDef(identifier, type, true);
}
} else {
m_parent->addVarDef(identifier, type, found);
}
}
// ****************************************************************************
// ParseTree::findVarDef()
// ****************************************************************************
VarDef*
ParseTree::findVarDef(const comString& identifier)
{
// If the production associated with this node of the parse tree is a scope
// edge, this node may have the var def. If this is not found here or this
// node is not a scope edge, ask the parent node for the definition.
if (m_scopeEdge) {
VarDef* ret = NULL;
for (UINT i = 0; i < m_varDefs.getNumEntries(); i++) {
if (m_varDefs[i]->m_preName == identifier) {
ret = m_varDefs[i];
break;
}
}
if (ret)
return ret;
}
// If this node has no parent, indicate that there is no definition.
if (!m_parent)
return NULL;
return m_parent->findVarDef(identifier);
}
// ****************************************************************************
// VarDef::printVarDefHeader()
// ****************************************************************************
void
VarDef::printVarDefHeader(FILE* file)
{
VarDef* def = NULL;
comString decl;
for (UINT i = 0; i < m_varDefs.getNumEntries(); i++) {
def = m_varDefs[i];
switch (def->m_type) {
case Translator::Int:
case Translator::Bool:
decl = "variable";
break;
case Translator::Float:
decl = "fvariable";
break;
case Translator::Str:
decl = "2variable";
break;
default:
fprintf(stderr, "Encountered variable with improper type.\n");
Global::fail();
break;
}
fprintf(file, "\n%s %s", (const char*) decl, (const char*) def->m_postName);
}
}
// ****************************************************************************
// FuncDef::FuncDef()
// ****************************************************************************
FuncDef::FuncDef(const comString& rName,
const comString& oName,
Translator::Type type,
ParseTree* tree)
: m_preName(rName),
m_postName(oName),
m_type(type),
m_definition(tree)
{
m_funcDefs.append(this);
}
// ****************************************************************************
// ParseTree::addFuncDef()
// ****************************************************************************
void
ParseTree::addFuncDef(FuncDef* def,
bool found)
{
// If the production associated with this node of the parse tree is a scope
// edge, this node can hold the Func def. Otherwise pass it on up to the
// parent.
if (m_scopeEdge) {
// If this is the first edge found, ignore it and go to the next one.
// We do this because let statements are themselves in scope edges and
// therefore require this hack to make it so declarations exist outside
// the let statements.
if (found) {
m_funcDefs.append(def);
} else {
m_parent->addFuncDef(def, true);
}
} else {
m_parent->addFuncDef(def, found);
}
}
// ****************************************************************************
// ParseTree::findFuncDef()
// ****************************************************************************
FuncDef*
ParseTree::findFuncDef(const comString& identifier)
{
// If the production associated with this node of the parse tree is a scope
// edge, this node may have the Func def. If this is not found here or this
// node is not a scope edge, ask the parent node for the definition.
if (m_scopeEdge) {
FuncDef* ret = NULL;
for (UINT i = 0; i < m_funcDefs.getNumEntries(); i++) {
if (m_funcDefs[i]->m_preName == identifier) {
ret = m_funcDefs[i];
break;
}
}
if (ret)
return ret;
}
// If this node has no parent, indicate that there is no definition.
if (!m_parent)
return NULL;
return m_parent->findFuncDef(identifier);
}
// ****************************************************************************
// FuncDef::printFuncDefHeader()
// ****************************************************************************
void
FuncDef::printFuncDefHeader(FILE* file)
{
FuncDef* def = NULL;
for (UINT i = 0; i < m_funcDefs.getNumEntries(); i++) {
def = m_funcDefs[i];
// Function definition's definition pointers point to productions that
// look like
// let ( ( id FUNLIST ) ( type FUNTYPE ) ) EXPR EXPRLIST
// So the last and second to last nodes under this one will be the
// actual definition.
fprintf(file, "\n: %s ", (const char*) def->m_postName);
Translator::run(def->m_definition->getChild(11), file);
Translator::run(def->m_definition->getChild(12), file);
fprintf(file, "; ");
}
fprintf(file, "\n");
}