Source file location.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
type point = int
type zone = { a : point; b : point }
type t = zone option
type 'a with_location = { value : 'a; location : t }
type 'a w = 'a with_location = { value : 'a; location : t }

let make a b =
  if a < 0 || b < 0 then Fmt.invalid_arg "A point must be positive";
  if a > b then Fmt.invalid_arg "[a] must be lower or equal to [b]";
  Some { a; b }

let some zone = Some zone
let none = None

let union a b =
  match (a, b) with
  | None, None -> None
  | Some _, None -> a
  | None, Some _ -> b
  | Some { a; b }, Some { a = x; b = y } ->
      let a = (min : int -> int -> int) a x in
      let b = (max : int -> int -> int) b y in
      Some { a; b }

let pp ppf = function
  | Some { a; b } -> Fmt.pf ppf "%d:%d" a b
  | None -> Fmt.string ppf "<none>"

let left = function Some { a; _ } -> Some a | None -> None

let left_exn t =
  match left t with
  | Some left -> left
  | None -> Fmt.invalid_arg "<dummy location>"

let right = function Some { b; _ } -> Some b | None -> None

let right_exn t =
  match right t with
  | Some right -> right
  | None -> Fmt.invalid_arg "<dummy location>"

let length = function Some { a; b } -> Some (b - a) | None -> None

let length_exn t =
  match length t with
  | Some length -> length
  | None -> Fmt.invalid_arg "<dummy location>"

let without_location : 'a with_location -> 'a = fun { value; _ } -> value
let location { location; _ } = location
let with_location ~location v = { value = v; location }
let inj = with_location
let prj = without_location