Download The Compiler Generator Coco/R
Transcript
37
B.2 TL.cs (symbol table)
namespace Taste {
class Entry { // symbol table entries
public string name;
// name of the entry
public int
type;
// type of the entry (NONE for procs)
public Entry next;
// to next entry in same scope
public int
kind;
// vars, procs, scopes
public int
adr;
// address in memory or start of proc
public int
level;
// nesting level of declaration
public Entry locals;
// scopes: to locally declared entries
public int
nextAdr;
// scopes: next free address in this scope
}
class TL {
// symbol table handler
// types
public const int NONE = 0;
public const int INT = 1;
public const int BOOL = 2;
// entry kinds
public const int vars
= 0;
public const int procs = 1;
public const int scopes = 2;
public static int curLevel; // nesting level of current scope
static Entry undefEntry;
// entry node for erroneous symbols
static Entry topScope;
// topmost procedure scope
public static void EnterScope () {
Entry scope = new Entry();
scope.name = ""; scope.type = NONE; scope.kind = scopes;
scope.locals = null; scope.nextAdr = 3;
scope.next = topScope; topScope = scope;
curLevel++;
}
public static void LeaveScope () {
topScope = topScope.next; curLevel--;
}
public static int DataSpace () {
return topScope.nextAdr - 3;
}
public static Entry NewEntry (string name, int kind) {
Entry p, entry = new Entry();
entry.name = name; entry.type = NONE; entry.kind = kind;
entry.level = curLevel;
p = topScope.locals;
while (p != null) {
if (p.name.Equals(name)) Parser.SemErr("name declared twice");
p = p.next;
}
entry.next = topScope.locals; topScope.locals = entry;
if (kind == vars) {
entry.adr = topScope.nextAdr;
topScope.nextAdr++;
}
return entry;
}