View Javadoc
1   /*
2    * Copyright 2019-2022 Foreseeti AB <https://foreseeti.com>
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.mal_lang.lib;
18  
19  import java.util.Objects;
20  
21  public class Position implements Comparable<Position> {
22    public final String filename;
23    public final int line;
24    public final int col;
25  
26    public Position(String filename, int line, int col) {
27      this.filename = filename;
28      this.line = line;
29      this.col = col;
30    }
31  
32    public Position(Position pos) {
33      this.filename = pos.filename;
34      this.line = pos.line;
35      this.col = pos.col;
36    }
37  
38    public String posString() {
39      return String.format("<%s:%d:%d>", filename, line, col);
40    }
41  
42    @Override
43    public String toString() {
44      return posString();
45    }
46  
47    @Override
48    public int hashCode() {
49      return Objects.hash(filename, line, col);
50    }
51  
52    @Override
53    public boolean equals(Object obj) {
54      if (obj == null) {
55        return false;
56      }
57      if (!(obj instanceof Position)) {
58        return false;
59      }
60      var other = (Position) obj;
61      return this.filename.equals(other.filename) && this.line == other.line && this.col == other.col;
62    }
63  
64    @Override
65    public int compareTo(Position o) {
66      int cmp = this.filename.compareTo(o.filename);
67      if (cmp != 0) {
68        return cmp;
69      }
70      cmp = Integer.compare(this.line, o.line);
71      if (cmp != 0) {
72        return cmp;
73      }
74      return Integer.compare(this.col, o.col);
75    }
76  }