001/* 002 * Copyright (c) 2012-2021 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others 003 * 004 * This program and the accompanying materials are made available under the 005 * terms of the Eclipse Public License 2.0 which is available at 006 * http://www.eclipse.org/legal/epl-2.0. 007 * 008 * SPDX-License-Identifier: EPL-2.0 009 */ 010 011package org.eclipse.golo.compiler; 012 013public class PositionInSourceCode { 014 015 private final int startLine; 016 private final int startColumn; 017 private final int endLine; 018 private final int endColumn; 019 020 private static final PositionInSourceCode UNDEFINED = new PositionInSourceCode(0, 0, 0, 0) { 021 @Override 022 public boolean isUndefined() { 023 return true; 024 } 025 026 @Override 027 public String toString() { 028 return "undefined"; 029 } 030 }; 031 032 private PositionInSourceCode(int startLine, int startColumn, int endLine, int endColumn) { 033 this.startLine = startLine; 034 this.endLine = endLine; 035 this.startColumn = startColumn; 036 this.endColumn = endColumn; 037 } 038 039 public static PositionInSourceCode undefined() { 040 return UNDEFINED; 041 } 042 043 public static PositionInSourceCode of(PositionInSourceCode pos) { 044 if (pos == null) { 045 return UNDEFINED; 046 } 047 return pos; 048 } 049 050 public static PositionInSourceCode of(int line, int column) { 051 return of(line, column, line, column); 052 } 053 054 public static PositionInSourceCode of(int startLine, int startColumn, int endLine, int endColumn) { 055 if (startLine <= 0 && endLine <= 0 && startColumn <= 0 && endColumn <= 0) { 056 return UNDEFINED; 057 } 058 return new PositionInSourceCode(startLine, startColumn, endLine, endColumn); 059 } 060 061 public int getStartLine() { 062 return startLine; 063 } 064 065 public int getStartColumn() { 066 return startColumn; 067 } 068 069 public int getEndLine() { 070 return endLine; 071 } 072 073 public int getEndColumn() { 074 return endColumn; 075 } 076 077 public boolean isUndefined() { 078 return false; 079 } 080 081 @Override 082 public String toString() { 083 if (startLine == endLine && startColumn == endColumn) { 084 return String.format("{line=%d, column=%d}", startLine, startColumn); 085 } 086 return String.format("{from=%d;%d, to=%d;%d}", startLine, startColumn, endLine, endColumn); 087 } 088 089 @Override 090 public boolean equals(Object o) { 091 if (this == o) { return true; } 092 if (o == null || getClass() != o.getClass()) { return false; } 093 PositionInSourceCode that = (PositionInSourceCode) o; 094 return startColumn == that.startColumn 095 && startLine == that.startLine 096 && endLine == that.endLine 097 && endColumn == that.endColumn; 098 } 099 100 @Override 101 public int hashCode() { 102 return java.util.Objects.hash(startLine, startColumn, endLine, endColumn); 103 } 104}