-
Notifications
You must be signed in to change notification settings - Fork 1
/
symboltable.ml
85 lines (63 loc) · 1.71 KB
/
symboltable.ml
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
(*
Symbol table utility classes
*)
class ['a] symbol_table = object
val mutable table : (string, 'a) Hashtbl.t = Hashtbl.create 0
method put (k : string) (v : 'a) =
Hashtbl.add table k v
method get (k : string) : 'a =
try
Hashtbl.find table k
with
| Not_found -> failwith (k ^ " not found")
method get_opt (k : string) : 'a option =
try
Some (Hashtbl.find table k)
with
| Not_found -> None
method contains (k : string) : bool =
Hashtbl.mem table k
method iter f =
Hashtbl.iter f table
method set_table t =
table <- t
method size = Hashtbl.length table
method clone =
let clone_table : 'a symbol_table = new symbol_table in
let clone_hash = Hashtbl.copy table in
clone_table#set_table clone_hash;
clone_table
end
(* A stack of symbol tables to manage nested scopes *)
(* TODO make more efficient - roll my own stack? *)
class ['a] symbol_table_manager = object
val stack : 'a symbol_table Stack.t = Stack.create ()
method push (s : 'a symbol_table) =
Stack.push s stack
method pop =
Stack.pop stack
method top =
Stack.top stack
method lookup_opt name : 'a option =
let sl = ref [] in
Stack.iter (fun x -> sl := x :: !sl) stack;
let rec loop = function
| [] -> None
| h :: t ->
(match h#get_opt (name) with
| Some v -> Some v
| None -> loop (t))
in
loop (!sl)
method lookup name : 'a =
let sl = ref [] in
Stack.iter (fun x -> sl := x :: !sl) stack;
let rec loop = function
| [] -> raise Not_found
| h :: t ->
(match h#get_opt (name) with
| Some v -> v
| None -> loop (t))
in
loop (!sl)
end