001 package org.codehaus.groovy.syntax;
002
003 import org.codehaus.groovy.syntax.Types;
004 import org.codehaus.groovy.syntax.Token;
005 import org.codehaus.groovy.syntax.ParserException;
006
007 public class UnexpectedTokenException extends ParserException {
008 private Token unexpectedToken;
009 private int[] expectedTypes;
010 private String comment;
011
012 public UnexpectedTokenException(Token token) {
013 this(token, null, null );
014 }
015
016 public UnexpectedTokenException(Token token, int expectedType) {
017 this(token, new int[] { expectedType });
018 }
019
020 public UnexpectedTokenException(Token token, int[] expectedTypes) {
021 this(token, expectedTypes, null );
022 }
023
024 public UnexpectedTokenException(Token token, int[] expectedTypes, String comment) {
025 super("Unexpected token", token);
026 this.unexpectedToken = token;
027 this.expectedTypes = expectedTypes;
028 this.comment = comment;
029 }
030
031 public Token getUnexpectedToken() {
032 return this.unexpectedToken;
033 }
034
035 public int[] getExpectedTypes() {
036 return this.expectedTypes;
037 }
038
039 public String getUnexpectedTokenText( ) {
040 String text = null;
041 if( this.unexpectedToken != null )
042 {
043 text = this.unexpectedToken.getText();
044 }
045
046 if( text == null )
047 {
048 text = "";
049 }
050
051 return text;
052 }
053
054 public String getMessage() {
055 StringBuffer message = new StringBuffer();
056
057 if( expectedTypes != null ) {
058 message.append( "expected " );
059
060 if (this.expectedTypes.length == 1) {
061 message.append( Types.getDescription(this.expectedTypes[0]) );
062 }
063 else {
064 message.append("one of { ");
065
066 for (int i = 0; i < expectedTypes.length; ++i) {
067 message.append( Types.getDescription(this.expectedTypes[i]) );
068
069 if ((i + 1) < expectedTypes.length) {
070 if( expectedTypes.length > 2 ) {
071 message.append(", ");
072 }
073 else {
074 message.append(" ");
075 }
076 }
077
078 if ((i + 2) == expectedTypes.length) {
079 message.append("or ");
080 }
081 }
082
083 message.append(" }");
084 }
085
086 message.append( "; found '" );
087 }
088 else {
089 message.append( "could not use '" );
090 }
091
092 message.append( getUnexpectedTokenText() ).append( "'" );
093 if( unexpectedToken != null ) {
094 message.append(" at " + unexpectedToken.getStartLine() + ":" + unexpectedToken.getStartColumn());
095 }
096 else {
097 message.append(" at unknown location (probably end of file)");
098 }
099
100 if( comment != null ) {
101 message.append( "; " );
102 message.append( comment );
103 }
104
105 return message.toString();
106 }
107 }