-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTerminates.C
100 lines (77 loc) · 2.26 KB
/
Terminates.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
/****************************************************************
Terminates.C
Copyright (C)2013 William H. Majoros ([email protected]).
This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
License (GPL) version 3, as described at www.opensource.org.
****************************************************************/
#include <iostream>
#include "Terminates.H"
using namespace std;
using namespace BOOM;
const int HASH_SIZE=499;
Terminates::Terminates(SCFG &G)
: G(G), nonterminals(G.getNonterminals()),
productions(*G.getProductionSet())
{
init();
while(iterate());
}
Terminates::~Terminates()
{
delete table;
delete &productions;
}
bool Terminates::operator[](GrammarSymbol *s)
{
if(table->isDefined(*s)) return (*table)[*s];
return false;
}
void Terminates::init()
{
table=new HashMap<GrammarSymbol,bool>(HASH_SIZE);
int n=nonterminals.size();
for(int i=0 ; i<n ; ++i) {
GrammarSymbol *s=nonterminals[i];
(*table)[*s]=false;
Vector<Production*> &prods=productions.lookup(s);
for(Vector<Production*>::iterator cur=prods.begin(), end=prods.end() ;
cur!=end ; ++cur)
if((*cur)->isTerminalOrNull()) { (*table)[*s]=true; break; }
}
}
bool Terminates::iterate()
{
HashMap<GrammarSymbol,bool> *newTable=
new HashMap<GrammarSymbol,bool>(HASH_SIZE);
int n=nonterminals.size();
bool changes=false;
for(int i=0 ; i<n ; ++i) {
GrammarSymbol *s=nonterminals[i];
if((*table)[*s]) { (*newTable)[*s]=true; continue; }
(*newTable)[*s]=false;
Vector<Production*> &prods=productions.lookup(s);
for(Vector<Production*>::iterator cur=prods.begin(), end=prods.end() ;
cur!=end ; ++cur) {
Production *prod=*cur;
Vector<GrammarSymbol*> &rhs=prod->getRHS();
bool thisProd=true;
for(Vector<GrammarSymbol*>::iterator cur=rhs.begin(), end=rhs.end() ;
cur!=end ; ++cur) {
GrammarSymbol *t=*cur;
if(t->isNonterminal() && !(*table)[*t]) thisProd=false;
}
if(thisProd) { (*newTable)[*s]=true; changes=true; break; }
}
}
delete table;
table=newTable;
return changes;
}
void Terminates::dump()
{
int n=nonterminals.size();
for(int i=0 ; i<n ; ++i) {
GrammarSymbol *s=nonterminals[i];
cout<<s->getLexeme()<<" : "<<((*table)[*s]?"true":"false")<<endl;
}
}