var.ml 2 KB
Newer Older
1

2
module V = struct
3
  type t = { id : string; repr : string }
4
5
  let dump ppf t = 
    let r = if t.repr = t.id then "" else Format.sprintf ";repr=%s" t.repr in
6
    Format.fprintf ppf "{id=%s;%s}" t.id r
7
8
9
  let compare x y = Pervasives.compare x.id y.id
  let equal x y = Pervasives.compare x.id y.id = 0
  let hash x = Hashtbl.hash x.id
10
11
  let check _ = ()

12
  let make_id ?repr id =
13
    match repr with
14
15
    |None -> { id = id ; repr = id }
    |Some r -> { id = id ; repr = r }
16
end
17

18
type var = [ `Var of V.t ]
19
type t = var
20
21

let id (`Var x) = x.V.id
22
let dump ppf (`Var x) = Format.fprintf ppf "%a" V.dump x
23
let pp ppf (`Var x) = Format.fprintf ppf "'%s" x.V.repr
24
let compare (`Var x) (`Var y) = V.compare x y
25
let equal v1 v2 = (compare v1 v2) = 0
26
let hash (`Var x) = V.hash x
27
let check _ = ()
28

29
let mk ?repr id = `Var (V.make_id ?repr id)
30
31
32
33
let fresh : ?pre: string -> unit -> [> var ] =
  let counter = ref 0 in
  fun ?(pre="_fresh_") -> fun _ ->
    let id = (Printf.sprintf "%s%d" pre !counter) in
34
    let v = mk id in
35
36
37
    incr counter;
    v
;;
38

Pietro Abate's avatar
Pietro Abate committed
39
module Set = struct
40
  include Set.Make(struct type t = var let compare = compare end) 
41
42
43
  let dump ppf s = Utils.pp_list ~sep:";" ~delim:("{","}") dump ppf (elements s)
  let pp ppf s = Utils.pp_list ~sep:";" ~delim:("{","}") pp ppf (elements s)
  let printf = pp Format.std_formatter
44
45
  let is_empty s = equal s empty
  let from_list l = List.fold_left (fun acc x -> add x acc) empty l
Pietro Abate's avatar
Pietro Abate committed
46
end
47

48
type 'a pairvar = [ `Atm of 'a | var ]
49
50
module type MAKE = functor (X : Custom.T) -> Custom.T with type t = X.t pairvar

51
52
module Make (X : Custom.T) = struct
  type t = X.t pairvar
53
  let hash = function `Atm t -> X.hash t | `Var x -> V.hash x
54
55
56
  let check = function `Atm t -> X.check t | `Var _ -> ()
  let compare t1 t2 =
    match t1,t2 with
57
    |`Var x, `Var y -> compare (`Var x) (`Var y)
58
59
60
61
62
    |`Atm x, `Atm y -> X.compare x y
    |`Var _, `Atm _ -> -1
    |`Atm _, `Var _ -> 1

  let equal t1 t2 = (compare t1 t2) = 0
63

64
65
  let dump ppf = function
    |`Atm x -> X.dump ppf x
Pietro Abate's avatar
Pietro Abate committed
66
    |`Var x -> dump ppf (`Var x)
67
end