Repository navigation
Expand file tree
/
Copy pathScope.cpp
More file actions
122 lines (95 loc) · 2.4 KB
/
Copy pathScope.cpp
File metadata and controls
122 lines (95 loc) · 2.4 KB
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
/*
* File: Scope.cpp
*
* Description: This file contains the member function definitions for
* scopes in Simple C.
*
* We didn't allocate the symbols we're given, so we don't
* deallocate them. That's the rule. You have to do that
* yourself. Besides, it's possible that they're hanging
* around other places, like abstract syntax trees.
*
* Extra functionality:
* - retrieving the vector of symbols
*/
# include <cassert>
# include "Scope.h"
/*
* Function: Scope::Scope (constructor)
*
* Description: Initialize this scope object.
*/
Scope::Scope(Scope *enclosing)
: _enclosing(enclosing)
{
}
/*
* Function: Scope::insert
*
* Description: Insert the given symbol into this scope. It had better not
* already be inserted, or we fail big time.
*/
void Scope::insert(Symbol *symbol)
{
assert(find(symbol->name()) == nullptr);
_symbols.push_back(symbol);
}
/*
* Function: Scope::find
*
* Description: Find and return the symbol with the given name in this
* scope. If no such symbol is found, return a null pointer.
*/
Symbol *Scope::find(const string &name) const
{
for (unsigned i = 0; i < _symbols.size(); i ++)
if (name == _symbols[i]->name())
return _symbols[i];
return NULL;
}
/*
* Function: Scope::remove
*
* Description: Remove the symbol with the given name from this scope.
* Yes, I know, I duplicated the search logic from above.
* And, yes, I still didn't use an iterator. So sue me.
*/
void Scope::remove(const string &name)
{
for (unsigned i = 0; i < _symbols.size(); i ++)
if (name == _symbols[i]->name())
_symbols.erase(_symbols.begin() + i);
}
/*
* Function: Scope::lookup
*
* Description: Find and return the nearest symbol with the given name,
* starting the search in the given scope and moving into the
* enclosing scopes. If no such symbol is found, return a
* null pointer.
*/
Symbol *Scope::lookup(const string &name) const
{
Symbol *symbol;
if ((symbol = find(name)) != nullptr)
return symbol;
return _enclosing != nullptr ? _enclosing->lookup(name) : nullptr;
}
/*
* Function: Scope::enclosing (accessor)
*
* Description: Return the enclosing scope of this scope.
*/
Scope *Scope::enclosing() const
{
return _enclosing;
}
/*
* Function: Scope::symbols (accessor)
*
* Description: Return the list of symbols in this scope.
*/
const Symbols &Scope::symbols() const
{
return _symbols;
}