Mercurial > lcfOS
annotate python/ks/symboltable.py @ 182:e9b27f7193e3
Replace clear function by function also supported in python 3.2
author | Windel Bouwman |
---|---|
date | Sat, 18 May 2013 18:24:42 +0200 |
parents | 91af0e40f868 |
children |
rev | line source |
---|---|
1 | 1 from .nodes import * |
2 | |
3 class SymbolTable: | |
4 """ | |
5 Symbol table for a current scope. | |
6 It has functions: | |
7 - hasname for checking for a name in current scope or above | |
8 - addSymbol to add an object | |
9 """ | |
10 def __init__(self, parent=None): | |
11 self.parent = parent | |
12 self.syms = {} | |
13 | |
14 def __repr__(self): | |
15 return 'Symboltable with {0} symbols\n'.format(len(self.syms)) | |
16 | |
17 def printTable(self, indent=0): | |
18 for name in self.syms: | |
19 print(self.syms[name]) | |
20 | |
21 def getAllLocal(self, cls): | |
22 """ Get all local objects of a specific type """ | |
23 r = [] | |
24 for key in self.syms.keys(): | |
25 sym = self.syms[key] | |
26 if issubclass(type(sym), cls): | |
27 r.append(sym) | |
28 return r | |
29 | |
30 def getLocal(self, cls, name): | |
31 if name in self.syms.keys(): | |
32 sym = self.syms[name] | |
33 if isinstance(sym, cls): | |
34 return sym | |
35 else: | |
36 Error('Wrong type found') | |
37 else: | |
38 Error('Symbol not found') | |
39 | |
40 # Retrieving of specific classes of items: | |
41 def get(self, cls, name): | |
42 if self.hasSymbol(name): | |
43 sym = self.getSymbol(name) | |
44 if issubclass(type(sym), cls): | |
45 return sym | |
46 raise SymbolException('type {0} undefined'.format(typename)) | |
47 | |
48 def has(self, cls, name): | |
49 if self.hasSymbol(name): | |
50 sym = self.getSymbol(name) | |
51 if issubclass(type(sym), cls): | |
52 return True | |
53 return False | |
54 | |
55 # Adding and retrieving of symbols in general: | |
56 def addSymbol(self, sym): | |
57 if sym.name in self.syms.keys(): | |
58 raise Exception('Symbol "{0}" redefined'.format(sym.name)) | |
59 else: | |
60 self.syms[sym.name] = sym | |
61 | |
62 def getSymbol(self, name): | |
63 if name in self.syms.keys(): | |
64 return self.syms[name] | |
65 else: | |
66 if self.parent: | |
67 return self.parent.getSymbol(name) | |
68 else: | |
182
e9b27f7193e3
Replace clear function by function also supported in python 3.2
Windel Bouwman
parents:
146
diff
changeset
|
69 raise Exception('Symbol "{0}" undeclared!'.format(name)) |
1 | 70 |
71 def hasSymbol(self, name): | |
72 if name in self.syms.keys(): | |
73 return True | |
74 else: | |
75 if self.parent: | |
76 return self.parent.hasSymbol(name) | |
77 else: | |
78 return False | |
79 |