• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  [The "BSD license"]
3  Copyright (c) 2005-2009 Terence Parr
4  All rights reserved.
5 
6  Redistribution and use in source and binary forms, with or without
7  modification, are permitted provided that the following conditions
8  are met:
9  1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11  2. Redistributions in binary form must reproduce the above copyright
12      notice, this list of conditions and the following disclaimer in the
13      documentation and/or other materials provided with the distribution.
14  3. The name of the author may not be used to endorse or promote products
15      derived from this software without specific prior written permission.
16 
17  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 package org.antlr.runtime;
29 
30 import org.antlr.runtime.tree.*;
31 
32 /** The root of the ANTLR exception hierarchy.
33  *
34  *  To avoid English-only error messages and to generally make things
35  *  as flexible as possible, these exceptions are not created with strings,
36  *  but rather the information necessary to generate an error.  Then
37  *  the various reporting methods in Parser and Lexer can be overridden
38  *  to generate a localized error message.  For example, MismatchedToken
39  *  exceptions are built with the expected token type.
40  *  So, don't expect getMessage() to return anything.
41  *
42  *  Note that as of Java 1.4, you can access the stack trace, which means
43  *  that you can compute the complete trace of rules from the start symbol.
44  *  This gives you considerable context information with which to generate
45  *  useful error messages.
46  *
47  *  ANTLR generates code that throws exceptions upon recognition error and
48  *  also generates code to catch these exceptions in each rule.  If you
49  *  want to quit upon first error, you can turn off the automatic error
50  *  handling mechanism using rulecatch action, but you still need to
51  *  override methods mismatch and recoverFromMismatchSet.
52  *
53  *  In general, the recognition exceptions can track where in a grammar a
54  *  problem occurred and/or what was the expected input.  While the parser
55  *  knows its state (such as current input symbol and line info) that
56  *  state can change before the exception is reported so current token index
57  *  is computed and stored at exception time.  From this info, you can
58  *  perhaps print an entire line of input not just a single token, for example.
59  *  Better to just say the recognizer had a problem and then let the parser
60  *  figure out a fancy report.
61  */
62 public class RecognitionException extends Exception {
63 	/** What input stream did the error occur in? */
64 	public transient IntStream input;
65 
66 	/** What is index of token/char were we looking at when the error occurred? */
67 	public int index;
68 
69 	/** The current Token when an error occurred.  Since not all streams
70 	 *  can retrieve the ith Token, we have to track the Token object.
71 	 *  For parsers.  Even when it's a tree parser, token might be set.
72 	 */
73 	public Token token;
74 
75 	/** If this is a tree parser exception, node is set to the node with
76 	 *  the problem.
77 	 */
78 	public Object node;
79 
80 	/** The current char when an error occurred. For lexers. */
81 	public int c;
82 
83 	/** Track the line at which the error occurred in case this is
84 	 *  generated from a lexer.  We need to track this since the
85 	 *  unexpected char doesn't carry the line info.
86 	 */
87 	public int line;
88 
89 	public int charPositionInLine;
90 
91 	/** If you are parsing a tree node stream, you will encounter som
92 	 *  imaginary nodes w/o line/col info.  We now search backwards looking
93 	 *  for most recent token with line/col info, but notify getErrorHeader()
94 	 *  that info is approximate.
95 	 */
96 	public boolean approximateLineInfo;
97 
98 	/** Used for remote debugger deserialization */
RecognitionException()99 	public RecognitionException() {
100 	}
101 
RecognitionException(IntStream input)102 	public RecognitionException(IntStream input) {
103 		this.input = input;
104 		this.index = input.index();
105 		if ( input instanceof TokenStream ) {
106 			this.token = ((TokenStream)input).LT(1);
107 			this.line = token.getLine();
108 			this.charPositionInLine = token.getCharPositionInLine();
109 		}
110 		if ( input instanceof TreeNodeStream ) {
111 			extractInformationFromTreeNodeStream(input);
112 		}
113 		else if ( input instanceof CharStream ) {
114 			this.c = input.LA(1);
115 			this.line = ((CharStream)input).getLine();
116 			this.charPositionInLine = ((CharStream)input).getCharPositionInLine();
117 		}
118 		else {
119 			this.c = input.LA(1);
120 		}
121 	}
122 
extractInformationFromTreeNodeStream(IntStream input)123 	protected void extractInformationFromTreeNodeStream(IntStream input) {
124 		TreeNodeStream nodes = (TreeNodeStream)input;
125 
126 		this.node = nodes.LT(1);
127 
128 		Object positionNode = null;
129 		if (nodes instanceof PositionTrackingStream) {
130 			positionNode = ((PositionTrackingStream<?>)nodes).getKnownPositionElement(false);
131 			if (positionNode == null) {
132 				positionNode = ((PositionTrackingStream<?>)nodes).getKnownPositionElement(true);
133 				this.approximateLineInfo = positionNode != null;
134 			}
135 		}
136 
137 		TreeAdaptor adaptor = nodes.getTreeAdaptor();
138 		Token payload = adaptor.getToken(positionNode != null ? positionNode : this.node);
139 		if ( payload!=null ) {
140 			this.token = payload;
141 			if ( payload.getLine()<= 0 ) {
142 				// imaginary node; no line/pos info; scan backwards
143 				int i = -1;
144 				Object priorNode = nodes.LT(i);
145 				while ( priorNode!=null ) {
146 					Token priorPayload = adaptor.getToken(priorNode);
147 					if ( priorPayload!=null && priorPayload.getLine()>0 ) {
148 						// we found the most recent real line / pos info
149 						this.line = priorPayload.getLine();
150 						this.charPositionInLine = priorPayload.getCharPositionInLine();
151 						this.approximateLineInfo = true;
152 						break;
153 					}
154 
155 					--i;
156 					try {
157 						priorNode = nodes.LT(i);
158 					} catch (UnsupportedOperationException ex) {
159 						priorNode = null;
160 					}
161 				}
162 			}
163 			else { // node created from real token
164 				this.line = payload.getLine();
165 				this.charPositionInLine = payload.getCharPositionInLine();
166 			}
167 		}
168 		else if ( this.node instanceof Tree) {
169 			this.line = ((Tree)this.node).getLine();
170 			this.charPositionInLine = ((Tree)this.node).getCharPositionInLine();
171 			if ( this.node instanceof CommonTree) {
172 				this.token = ((CommonTree)this.node).token;
173 			}
174 		}
175 		else {
176 			int type = adaptor.getType(this.node);
177 			String text = adaptor.getText(this.node);
178 			this.token = new CommonToken(type, text);
179 		}
180 	}
181 
182 	/** Return the token type or char of the unexpected input element */
getUnexpectedType()183 	public int getUnexpectedType() {
184 		if ( input instanceof TokenStream ) {
185 			return token.getType();
186 		}
187 		else if ( input instanceof TreeNodeStream ) {
188 			TreeNodeStream nodes = (TreeNodeStream)input;
189 			TreeAdaptor adaptor = nodes.getTreeAdaptor();
190 			return adaptor.getType(node);
191 		}
192 		else {
193 			return c;
194 		}
195 	}
196 }
197