var.ml 2.22 KB
Newer Older
1

2
module V = struct
3
4
5
6
  type t = { fresh : bool; id : string; repr : string }
  let dump ppf t = 
    let r = if t.repr = t.id then "" else Format.sprintf ";repr=%s" t.repr in
    Format.fprintf ppf "{id=%s;fresh=%b%s}" t.id t.fresh 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
13
14
15
  let make_id ?(fresh=false) ?repr id =
    match repr with
    |None -> { id = id ; fresh = fresh ; repr = id }
    |Some r -> { id = id ; fresh = fresh ; repr = r }
16
end
17

18
type var = [ `Var of V.t ]
19
type t = var
20
let dump ppf (`Var x) = Format.fprintf ppf "%a" V.dump x
21
let pp ppf (`Var x) = Format.fprintf ppf "'%s" x.V.repr
22
let compare (`Var x) (`Var y) = V.compare x y
23
let equal v1 v2 = (compare v1 v2) = 0
24
let hash (`Var x) = V.hash x
25
let check _ = ()
26

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

37
38
let id (`Var x) = x.V.id
let is_fresh (`Var x) = x.V.fresh
39

Pietro Abate's avatar
Pietro Abate committed
40
module Set = struct
41
  include Set.Make(struct type t = var let compare = compare end) 
Pietro Abate's avatar
Pietro Abate committed
42
43
44
45
46
47
48
49
50
  let aux_print sep printer ppf s =
    let rec aux ppf = function
      |[] -> ()
      |[h] -> printer ppf h
      |h::l -> Format.fprintf ppf "%a %s %a" printer h sep aux l
    in
    aux ppf (elements s)

  let dump ppf s = aux_print ";" dump ppf s
51
  let pp ppf s = aux_print ";" pp ppf s
52
53
  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
54
end
55

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

59
60
module Make (X : Custom.T) = struct
  type t = X.t pairvar
61
  let hash = function `Atm t -> X.hash t | `Var x -> V.hash x
62
63
64
  let check = function `Atm t -> X.check t | `Var _ -> ()
  let compare t1 t2 =
    match t1,t2 with
65
    |`Var x, `Var y -> compare (`Var x) (`Var y)
66
67
68
69
70
    |`Atm x, `Atm y -> X.compare x y
    |`Var _, `Atm _ -> -1
    |`Atm _, `Var _ -> 1

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

72
73
  let dump ppf = function
    |`Atm x -> X.dump ppf x
Pietro Abate's avatar
Pietro Abate committed
74
    |`Var x -> dump ppf (`Var x)
75
end