001 package org.codehaus.groovy.antlr;
002
003 import antlr.collections.AST;
004 import antlr.*;
005
006 import java.util.List;
007 import java.util.ArrayList;
008
009 /**
010 * We have an AST subclass so we can track source information.
011 * Very odd that ANTLR doesn't do this by default.
012 *
013 * @author Mike Spille
014 * @author Jeremy Rayner <groovy@ross-rayner.com>
015 */
016 public class GroovySourceAST extends CommonAST implements Comparable {
017 private int line;
018 private int col;
019 private int lineLast;
020 private int colLast;
021 private String snippet;
022
023 public GroovySourceAST() {
024 }
025
026 public GroovySourceAST(Token t) {
027 super(t);
028 }
029
030 public void initialize(AST ast) {
031 super.initialize(ast);
032 line = ast.getLine();
033 col = ast.getColumn();
034 }
035
036 public void initialize(Token t) {
037 super.initialize(t);
038 line = t.getLine();
039 col = t.getColumn();
040 }
041
042 public void setLast(Token last) {
043 lineLast = last.getLine();
044 colLast = last.getColumn();
045 }
046
047 public int getLineLast() {
048 return lineLast;
049 }
050
051 public void setLineLast(int lineLast) {
052 this.lineLast = lineLast;
053 }
054
055 public int getColumnLast() {
056 return colLast;
057 }
058
059 public void setColumnLast(int colLast) {
060 this.colLast = colLast;
061 }
062
063 public void setLine(int line) {
064 this.line = line;
065 }
066
067 public int getLine() {
068 return (line);
069 }
070
071 public void setColumn(int column) {
072 this.col = column;
073 }
074
075 public int getColumn() {
076 return (col);
077 }
078
079 public void setSnippet(String snippet) {
080 this.snippet = snippet;
081 }
082
083 public String getSnippet() {
084 return snippet;
085 }
086
087 public int compareTo(Object object) {
088 if (object == null) {
089 return 0;
090 }
091 if (!(object instanceof AST)) {
092 return 0;
093 }
094 AST that = (AST) object;
095
096 // todo - possibly check for line/col with values of 0 or less...
097
098 if (this.getLine() < that.getLine()) {
099 return -1;
100 }
101 if (this.getLine() > that.getLine()) {
102 return 1;
103 }
104
105 if (this.getColumn() < that.getColumn()) {
106 return -1;
107 }
108 if (this.getColumn() > that.getColumn()) {
109 return 1;
110 }
111
112 return 0;
113 }
114
115 public GroovySourceAST childAt(int position) {
116 List list = new ArrayList();
117 AST child = this.getFirstChild();
118 while (child != null) {
119 list.add(child);
120 child = child.getNextSibling();
121 }
122 try {
123 return (GroovySourceAST)list.get(position);
124 } catch (IndexOutOfBoundsException e) {
125 return null;
126 }
127 }
128
129 public GroovySourceAST childOfType(int type) {
130 AST child = this.getFirstChild();
131 while (child != null) {
132 if (child.getType() == type) { return (GroovySourceAST)child; }
133 child = child.getNextSibling();
134 }
135 return null;
136 }
137
138 }