KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SymTab


1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  * Copyright (C) 2001 Gerwin Klein <lsf@jflex.de> *
3  * Copyright (C) 2001 Bernhard Rumpe <rumpe@in.tum.de> *
4  * All rights reserved. *
5  * *
6  * This program is free software; you can redistribute it and/or modify *
7  * it under the terms of the GNU General Public License. See the file *
8  * COPYRIGHT for more information. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License along *
16  * with this program; if not, write to the Free Software Foundation, Inc., *
17  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
18  * *
19  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

20
21
22 import java.util.*;
23
24 /**
25  * Symbol table for the interpreter, contains information about
26  * variables and functions.
27  *
28  * For every binding location of a name a symbol will be created.
29  * The symbol tables are connected hierarchically by pointers to
30  * the predecessor. Lookup takes predecessors into account.
31  */

32 public class SymTab {
33   Hashtable h; // contains the liste of words
34
// key: String, value: SymtabEntry
35

36   SymTab pred; // predecessor symbol table (if exists)
37

38   public SymTab() {
39     this(null);
40   }
41
42   public SymTab(SymTab p) {
43     h = new Hashtable();
44     pred = p;
45   }
46
47   public boolean enter(String JavaDoc s, SymtabEntry e) {
48     Object JavaDoc value = lookup(s);
49     h.put(s, e);
50     return(value==null);
51   }
52
53   public SymtabEntry lookup(String JavaDoc s) {
54     Object JavaDoc value = h.get(s);
55     if (value==null && pred!=null)
56       value = pred.lookup(s);
57     return ((SymtabEntry)value);
58   }
59
60   public String JavaDoc toString() { // for output with print
61
String JavaDoc res = "symbol table\n=============\n";
62     Enumeration e = h.keys();
63     String JavaDoc key;
64     
65     while(e.hasMoreElements()) {
66       key = (String JavaDoc)e.nextElement();
67       res += key+" \t"+h.get(key)+"\n";
68     }
69
70     if (pred!=null) res+="++ predecessor!\n";
71     return(res);
72   }
73
74   public int size() {
75     return(h.size());
76   }
77 }
78
79
Popular Tags