Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.codehaus.groovy.control;
 
 
 import java.io.File;
 import java.io.Reader;
 import java.net.URL;
 
 
 import  antlr.CharScanner;
 import  antlr.MismatchedTokenException;
 import  antlr.MismatchedCharException;
 import  antlr.NoViableAltException;
 import  antlr.NoViableAltForCharException;
 
Provides an anchor for a single source unit (usually a script file) as it passes through the compiler system.

Author(s):
Chris Poirier
Bing Ran
Version:
$Id: SourceUnit.java 15261 2009-02-05 12:18:38Z paulk $
 
 
 public class SourceUnit extends ProcessingUnit {

    
The pluggable parser used to generate the AST - we allow pluggability currently as we need to have Classic and JSR support
 
     private ParserPlugin parserPlugin;

    
Where we can get Readers for our source unit
 
     protected ReaderSource source;

    
A descriptive name of the source unit. This name shouldn't be used for controlling the SourceUnit, it is only for error messages and to determine the name of the class for a script.
 
     protected String name;

    
A Concrete Syntax Tree of the source
 
     protected Reduction cst;

    
The root of the Abstract Syntax Tree for the source
 
     protected ModuleNode ast;


    
Initializes the SourceUnit from existing machinery.
 
     public SourceUnit(String nameReaderSource sourceCompilerConfiguration flags,
                       GroovyClassLoader loaderErrorCollector er) {
         super(flagsloaderer);
 
         this. = name;
         this. = source;
    }


    
Initializes the SourceUnit from the specified file.
    public SourceUnit(File sourceCompilerConfiguration configurationGroovyClassLoader loaderErrorCollector er) {
        this(source.getPath(), new FileReaderSource(sourceconfiguration), configurationloaderer);
    }


    
Initializes the SourceUnit from the specified URL.
    public SourceUnit(URL sourceCompilerConfiguration configurationGroovyClassLoader loaderErrorCollector er) {
        this(source.getPath(), new URLReaderSource(sourceconfiguration), configurationloaderer);
    }


    
Initializes the SourceUnit for a string of source.
    public SourceUnit(String nameString sourceCompilerConfiguration configuration,
                      GroovyClassLoader loaderErrorCollector er) {
        this(namenew StringReaderSource(sourceconfiguration), configurationloaderer);
    }


    
Returns the name for the SourceUnit. This name shouldn't be used for controlling the SourceUnit, it is only for error messages
    public String getName() {
        return ;
    }


    
Returns the Concrete Syntax Tree produced during parse()ing.
    public Reduction getCST() {
        return this.;
    }

    
Returns the Abstract Syntax Tree produced during convert()ing and expanded during later phases.
    public ModuleNode getAST() {
        return this.;
    }


    
Convenience routine, primarily for use by the InteractiveShell, that returns true if parse() failed with an unexpected EOF.
    public boolean failedWithUnexpectedEOF() {
    	// Implementation note - there are several ways for the Groovy compiler
    	// to report an unexpected EOF. Perhaps this implementation misses some.
    	// If you find another way, please add it.
        if (getErrorCollector().hasErrors()) {
            Message last = (MessagegetErrorCollector().getLastError();
            Throwable cause = null;
            if (last instanceof SyntaxErrorMessage) {
                cause = ((SyntaxErrorMessagelast).getCause().getCause();
            }
            if (cause != null) {
            	if (cause instanceof NoViableAltException) {
                    return isEofToken(((NoViableAltException) cause).token);
            	} else if (cause instanceof NoViableAltForCharException) {
            		char badChar = ((NoViableAltForCharException) cause).foundChar;
            		return badChar == CharScanner.EOF_CHAR;
            	} else if (cause instanceof MismatchedCharException) {
            		char badChar = (char) ((MismatchedCharException) cause).foundChar;
            		return badChar == CharScanner.EOF_CHAR;
                } else if (cause instanceof MismatchedTokenException) {
                    return isEofToken(((MismatchedTokenException) cause).token);
                }
            }
        }
        return false;    
    }
    protected boolean isEofToken(antlr.Token token) {
        return token.getType() == antlr.Token.EOF_TYPE;
    }
    //---------------------------------------------------------------------------
    // FACTORIES


    
A convenience routine to create a standalone SourceUnit on a String with defaults for almost everything that is configurable.
    public static SourceUnit create(String nameString source) {
        CompilerConfiguration configuration = new CompilerConfiguration();
        configuration.setTolerance(1);
        return new SourceUnit(namesourceconfigurationnullnew ErrorCollector(configuration));
    }


    
A convenience routine to create a standalone SourceUnit on a String with defaults for almost everything that is configurable.
    public static SourceUnit create(String nameString sourceint tolerance) {
        CompilerConfiguration configuration = new CompilerConfiguration();
        configuration.setTolerance(tolerance);
        return new SourceUnit(namesourceconfigurationnullnew ErrorCollector(configuration));
    }
    //---------------------------------------------------------------------------
    // PROCESSING


    
Parses the source to a CST. You can retrieve it with getCST().
    public void parse() throws CompilationFailedException {
        if (this. > .) {
            throw new GroovyBugError("parsing is already complete");
        }
        if (this. == .) {
            nextPhase();
        }
        //
        // Create a reader on the source and run the parser.
        Reader reader = null;
        try {
            reader = .getReader();
            // let's recreate the parser each time as it tends to keep around state
             = .parseCST(thisreader);
            reader.close();
            
        }
        catch (IOException e) {
            getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(),this));
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException e) {
                    // Ignore
                }
            }
        }
    }


    
Generates an AST from the CST. You can retrieve it with getAST().
    public void convert() throws CompilationFailedException {
        if (this. == . && this.) {
            gotoPhase(.);
        }
        if (this. != .) {
            throw new GroovyBugError("SourceUnit not ready for convert()");
        }
        
        //
        // Build the AST
        
        try {
            this. = .buildAST(thisthis.this.);
            this..setDescription(this.);
        }
        catch (SyntaxException e) {
            getErrorCollector().addError(new SyntaxErrorMessage(e,this));
        }
        String property = (String) AccessController.doPrivileged(new PrivilegedAction() {
        	public Object run() {
        		return System.getProperty("groovy.ast");
        	}
        });
        
        if ("xml".equals(property)) {
            saveAsXML(,);
        }
    }
    private void saveAsXML(String nameModuleNode ast) {
        XStream xstream = new XStream();
        try {
            xstream.toXML(ast,new FileWriter(name + ".xml"));
            ..println("Written AST to " + name + ".xml");
        } catch (Exception e) {
            ..println("Couldn't write to " + name + ".xml");
            e.printStackTrace();
        }
    }
    //---------------------------------------------------------------------------    // SOURCE SAMPLING

    
Returns a sampling of the source at the specified line and column, of null if it is unavailable.
    public String getSample(int lineint columnJanitor janitor) {
        String sample = null;
        String text = .getLine(linejanitor);
        if (text != null) {
            if (column > 0) {
                String marker = Utilities.repeatString(" "column - 1) + "^";
                if (column > 40) {
                    int start = column - 30 - 1;
                    int end = (column + 10 > text.length() ? text.length() : column + 10 - 1);
                    sample = "   " + text.substring(startend) + Utilities.eol() + "   " +
                            marker.substring(startmarker.length());
                }
                else {
                    sample = "   " + text + Utilities.eol() + "   " + marker;
                }
            }
            else {
                sample = text;
            }
        }
        return sample;
    }
    
    public void addException(Exception ethrows CompilationFailedException {
        getErrorCollector().addException(e,this);
    }
    
    public void addError(SyntaxException sethrows CompilationFailedException {
        getErrorCollector().addError(se,this);
    }
New to GrepCode? Check out our FAQ X