summaryrefslogtreecommitdiff
path: root/src/Identifiers.ml
blob: 5cf92c095975334189e68b47b3220de53a5f5805 (plain)
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
86
87
exception IntegerOverflow of unit

type gen_int = int [@@deriving of_yojson]
(** This definition is used only to derive a proper int deserialization function *)

type 'a gen_list = 'a list [@@deriving of_yojson]
(** This definition is used only to derive a proper list deserialization function *)

(** Signature for a module describing an identifier.
    
    We often need identifiers (for definitions, variables, etc.) and in
    order to make sure we don't mix them, we use a generative functor
    (see [IdGen]).
*)
module type Id = sig
  type id

  type 'a vector

  val zero : id

  val incr : id -> id

  val to_string : id -> string

  val id_of_yojson : Yojson.Safe.t -> (id, string) Result.result

  val vector_of_yojson :
    (Yojson.Safe.t -> ('a, string) Result.result) ->
    Yojson.Safe.t ->
    ('a vector, string) Result.result

  (* TODO: remove *)
  (* module Map : Map.S with type key = id *)
end

(** Generative functor for identifiers.

    See [Id].
*)
module IdGen () : Id = struct
  type id = int

  type 'a vector = 'a list

  let zero = 0

  let incr x =
    (* Identifiers should never overflow (because max_int is a really big
     * value - but we really want to make sure we detect overflows if
     * they happen *)
    if x == max_int then raise (IntegerOverflow ()) else x + 1

  let to_string = string_of_int

  let id_of_yojson json = gen_int_of_yojson json

  let vector_of_yojson a_of_yojson json = gen_list_of_yojson a_of_yojson json

  (* TODO: how to make this work? *)
  (* (module Ord : Map.OrderedType = struct
       type t = id

       let compare t1 t2 = t2 - t1
     end)

     module IdMap = Map.Make (Ord) *)

  (* module Map = Map.Make (struct
       type t = id

       let compare = Stdlib.compare
     end) *)

  (* let ord =
        (module struct
          type t = id

          let compare = Stdlib.compare
        end)

     module Map = Map.Make (ord) *)
end

type name = string list
(** A name such as: `std::collections::vector` (which would be represented as
    [["std"; "collections"; "vector"]]) *)