Source file position.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
type t =
    {
        line: int;              (* Line number i.e. number of newlines since
                                   start of the file. *)

        byte_bol: int;          (* Byte position at the start of the line. *)

        byte_col: int;          (* Byte position in the current line. *)

        correction: int;        (* Byte column + correction = character column
                                 *)
    }


type range = t * t



let line (p: t): int =
    p.line


let byte_offset_bol (p: t): int =
    p.byte_bol


let byte_column p =
    p.byte_col


let byte_offset (p: t): int =
    p.byte_bol + p.byte_col


let column (p:t): int =
    p.byte_col + p.correction


let start: t = {
    line       = 0;
    byte_bol   = 0;
    byte_col   = 0;
    correction = 0;
}





let advance (byte_width: int) (width: int) (p: t): t =
    {
        p with
        byte_col   = p.byte_col + byte_width;
        correction = p.correction + width - byte_width;
    }



let newline (byte_width: int) (p: t): t =
    {
        line       = p.line + 1;
        byte_col   = 0;
        byte_bol   = p.byte_bol + p.byte_col + byte_width;
        correction = 0;
    }



let next (c: char) (p: t): t =
    if c = '\n' then
        {
            line     = p.line + 1;
            byte_bol = p.byte_bol + p.byte_col + 1;
            byte_col = 0;
            correction = 0;
        }
    else
        {
            p with
            byte_col   =
                p.byte_col + 1;
            correction =
                if c = '\t' then
                    p.correction + 3
                else if c < ' ' then
                    p.correction - 1
                else
                    p.correction
        }






let correct (cor: int) (p: t): t =
    {
        p with
        correction = p.correction + cor
    }



let is_less_equal (p1: t) (p2: t): bool =
    let l1, l2 = line p1, line p2
    and c1, c2 = column p1, column p2
    in
    (
        l1 < l2
        ||
        (l1 = l2 && c1 <= c2)
    )


let is_valid_range ((p1,p2): range): bool =
    is_less_equal p1 p2


let merge ((p1, _): range) ((_, p2): range): range =
    assert (is_less_equal p1 p2);
    p1, p2