1 /* 2 * Copyright 2003-2007 the original author or authors. 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 * http://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.codehaus.groovy.antlr; 18 19 /** 20 * Process to decorate antlr AST with ending line/col info, and if 21 * possible the snipppet of source from the start/end line/col for each node. 22 * 23 * @author <a href="mailto:groovy@ross-rayner.com">Jeremy Rayner</a> 24 * @version $Revision: 21223 $ 25 */ 26 27 import antlr.collections.AST; 28 import java.util.*; 29 30 public class AntlrASTProcessSnippets implements AntlrASTProcessor{ 31 32 public AntlrASTProcessSnippets() { 33 } 34 35 /** 36 * decorate antlr AST with ending line/col info, and if 37 * possible the snipppet of source from the start/end line/col for each node. 38 * @param t the AST to decorate 39 * @return the decorated AST 40 */ 41 public AST process(AST t) { 42 // first visit 43 List l = new ArrayList(); 44 traverse((GroovySourceAST)t,l,null); 45 46 //System.out.println("l:" + l); 47 // second visit 48 Iterator itr = l.iterator(); 49 if (itr.hasNext()) { itr.next(); /* discard first */ } 50 traverse((GroovySourceAST)t,null,itr); 51 return t; 52 } 53 54 /** 55 * traverse an AST node 56 * @param t the AST node to traverse 57 * @param l A list to add line/col info to 58 * @param itr An iterator over a list of line/col 59 * @return A decorated AST node 60 */ 61 private void traverse(GroovySourceAST t,List l,Iterator itr) { 62 while (t != null) { 63 // first visit of node 64 if (l != null) { 65 l.add(new LineColumn(t.getLine(),t.getColumn())); 66 } 67 68 // second visit of node 69 if (itr != null && itr.hasNext()) { 70 LineColumn lc = (LineColumn)itr.next(); 71 if (t.getLineLast() == 0) { 72 int nextLine = lc.getLine(); 73 int nextColumn = lc.getColumn(); 74 if (nextLine < t.getLine() || (nextLine == t.getLine() && nextColumn < t.getColumn())) { 75 nextLine = t.getLine(); 76 nextColumn = t.getColumn(); 77 } 78 t.setLineLast(nextLine); 79 t.setColumnLast(nextColumn); 80 // This is a good point to call t.setSnippet(), 81 // but it bulks up the AST too much for production code. 82 } 83 } 84 85 GroovySourceAST child = (GroovySourceAST)t.getFirstChild(); 86 if (child != null) { 87 traverse(child,l,itr); 88 } 89 90 t = (GroovySourceAST)t.getNextSibling(); 91 } 92 } 93 }