Debian Codegraph @

rhino/src/org/mozilla/javascript/RhinoException.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
8 package org.mozilla.javascript;
9
10 import java.io.CharArrayWriter;
11 import java.io.FilenameFilter;
12 import java.io.PrintStream;
13 import java.io.PrintWriter;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.regex.Matcher;
17 import java.util.regex.Pattern;
18
19 /**
20 * The class of exceptions thrown by the JavaScript engine.
21 */
22 public abstract class RhinoException extends RuntimeException
23 {
24 private static final Pattern JAVA_STACK_PATTERN = Pattern.compile("_c_(.*)_\\d+");
25
26 RhinoException()
27 {
28 Evaluator e = Context.createInterpreter();
29 if (e != null)
30 e.captureStackInfo(this);
31 }
32
33 RhinoException(String details)
34 {
35 super(details);
36 Evaluator e = Context.createInterpreter();
37 if (e != null)
38 e.captureStackInfo(this);
39 }
40
41 @Override
42 public final String getMessage()
43 {
44 String details = details();
45 if (sourceName == null || lineNumber <= 0) {
46 return details;
47 }
48 StringBuilder buf = new StringBuilder(details);
49 buf.append(" (");
50 if (sourceName != null) {
51 buf.append(sourceName);
52 }
53 if (lineNumber > 0) {
54 buf.append('#');
55 buf.append(lineNumber);
56 }
57 buf.append(')');
58 return buf.toString();
59 }
60
61 public String details()
62 {
63 return super.getMessage();
64 }
65
66 /**
67 * Get the uri of the script source containing the error, or null
68 * if that information is not available.
69 */
70 public final String sourceName()
71 {
72 return sourceName;
73 }
74
75 /**
76 * Initialize the uri of the script source containing the error.
77 *
78 * @param sourceName the uri of the script source responsible for the error.
79 * It should not be <tt>null</tt>.
80 *
81 * @throws IllegalStateException if the method is called more then once.
82 */
83 public final void initSourceName(String sourceName)
84 {
85 if (sourceName == null) throw new IllegalArgumentException();
86 if (this.sourceName != null) throw new IllegalStateException();
87 this.sourceName = sourceName;
88 }
89
90 /**
91 * Returns the line number of the statement causing the error,
92 * or zero if not available.
93 */
94 public final int lineNumber()
95 {
96 return lineNumber;
97 }
98
99 /**
100 * Initialize the line number of the script statement causing the error.
101 *
102 * @param lineNumber the line number in the script source.
103 * It should be positive number.
104 *
105 * @throws IllegalStateException if the method is called more then once.
106 */
107 public final void initLineNumber(int lineNumber)
108 {
109 if (lineNumber <= 0) throw new IllegalArgumentException(String.valueOf(lineNumber));
110 if (this.lineNumber > 0) throw new IllegalStateException();
111 this.lineNumber = lineNumber;
112 }
113
114 /**
115 * The column number of the location of the error, or zero if unknown.
116 */
117 public final int columnNumber()
118 {
119 return columnNumber;
120 }
121
122 /**
123 * Initialize the column number of the script statement causing the error.
124 *
125 * @param columnNumber the column number in the script source.
126 * It should be positive number.
127 *
128 * @throws IllegalStateException if the method is called more then once.
129 */
130 public final void initColumnNumber(int columnNumber)
131 {
132 if (columnNumber <= 0) throw new IllegalArgumentException(String.valueOf(columnNumber));
133 if (this.columnNumber > 0) throw new IllegalStateException();
134 this.columnNumber = columnNumber;
135 }
136
137 /**
138 * The source text of the line causing the error, or null if unknown.
139 */
140 public final String lineSource()
141 {
142 return lineSource;
143 }
144
145 /**
146 * Initialize the text of the source line containing the error.
147 *
148 * @param lineSource the text of the source line responsible for the error.
149 * It should not be <tt>null</tt>.
150 *
151 * @throws IllegalStateException if the method is called more then once.
152 */
153 public final void initLineSource(String lineSource)
154 {
155 if (lineSource == null) throw new IllegalArgumentException();
156 if (this.lineSource != null) throw new IllegalStateException();
157 this.lineSource = lineSource;
158 }
159
160 final void recordErrorOrigin(String sourceName, int lineNumber,
161 String lineSource, int columnNumber)
162 {
163 // XXX: for compatibility allow for now -1 to mean 0
164 if (lineNumber == -1) {
165 lineNumber = 0;
166 }
167
168 if (sourceName != null) {
169 initSourceName(sourceName);
170 }
171 if (lineNumber != 0) {
172 initLineNumber(lineNumber);
173 }
174 if (lineSource != null) {
175 initLineSource(lineSource);
176 }
177 if (columnNumber != 0) {
178 initColumnNumber(columnNumber);
179 }
180 }
181
182 private String generateStackTrace()
183 {
184 // Get stable reference to work properly with concurrent access
185 CharArrayWriter writer = new CharArrayWriter();
186 super.printStackTrace(new PrintWriter(writer));
187 String origStackTrace = writer.toString();
188 Evaluator e = Context.createInterpreter();
189 if (e != null)
190 return e.getPatchedStack(this, origStackTrace);
191 return null;
192 }
193
194 /**
195 * Get a string representing the script stack of this exception.
196 * If optimization is enabled, this includes java stack elements
197 * whose source and method names suggest they have been generated
198 * by the Rhino script compiler.
199 * @return a script stack dump
200 * @since 1.6R6
201 */
202 public String getScriptStackTrace()
203 {
204 return getScriptStackTrace(NativeError.DEFAULT_STACK_LIMIT, null);
205 }
206
207 /**
208 * Get a string representing the script stack of this exception.
209 * If optimization is enabled, this includes java stack elements
210 * whose source and method names suggest they have been generated
211 * by the Rhino script compiler.
212 * The optional "limit" parameter limits the number of stack frames returned.
213 * The "functionName" parameter will exclude any stack frames "below" the
214 * specified function on the stack.
215 *
216 * @param limit the number of stack frames returned
217 * @param functionName the name of a function on the stack -- frames below it will be ignored
218 * @return a script stack dump
219 * @since 1.8.0
220 */
221 public String getScriptStackTrace(int limit, String functionName)
222 {
223 ScriptStackElement[] stack = getScriptStack(limit, functionName);
224 return formatStackTrace(stack, details());
225 }
226
227 static String formatStackTrace(ScriptStackElement[] stack, String message)
228 {
229 StringBuilder buffer = new StringBuilder();
230 String lineSeparator = SecurityUtilities.getSystemProperty("line.separator");
231
232 if ((stackStyle == StackStyle.V8) && !"null".equals(message)) {
233 // V8 Actually puts the error message at the top of "stack."
234 buffer.append(message);
235 buffer.append(lineSeparator);
236 }
237
238 for (ScriptStackElement elem : stack) {
239 switch (stackStyle) {
240 case MOZILLA:
241 elem.renderMozillaStyle(buffer);
242 break;
243 case V8:
244 elem.renderV8Style(buffer);
245 break;
246 case RHINO:
247 elem.renderJavaStyle(buffer);
248 break;
249 }
250 buffer.append(lineSeparator);
251 }
252 return buffer.toString();
253 }
254
255 /**
256 * Get a string representing the script stack of this exception.
257 * @deprecated the filter argument is ignored as we are able to
258 * recognize script stack elements by our own. Use
259 * #getScriptStackTrace() instead.
260 * @param filter ignored
261 * @return a script stack dump
262 * @since 1.6R6
263 */
264 @Deprecated
265 public String getScriptStackTrace(FilenameFilter filter)
266 {
267 return getScriptStackTrace();
268 }
269
270 /**
271 * Get the script stack of this exception as an array of
272 * {@link ScriptStackElement}s.
273 * If optimization is enabled, this includes java stack elements
274 * whose source and method names suggest they have been generated
275 * by the Rhino script compiler.
276 * @return the script stack for this exception
277 * @since 1.7R3
278 */
279 public ScriptStackElement[] getScriptStack() {
280 return getScriptStack(-1, null);
281 }
282
283 /**
284 * Get the script stack of this exception as an array of
285 * {@link ScriptStackElement}s.
286 * If optimization is enabled, this includes java stack elements
287 * whose source and method names suggest they have been generated
288 * by the Rhino script compiler.
289 *
290 * @param limit the number of stack frames returned, or -1 for unlimited
291 * @param hideFunction the name of a function on the stack -- frames below it will be ignored, or null
292 * @return the script stack for this exception
293 * @since 1.8.0
294 */
295 public ScriptStackElement[] getScriptStack(int limit, String hideFunction) {
296 List<ScriptStackElement> list = new ArrayList<ScriptStackElement>();
297 ScriptStackElement[][] interpreterStack = null;
298 if (interpreterStackInfo != null) {
299 Evaluator interpreter = Context.createInterpreter();
300 if (interpreter instanceof Interpreter)
301 interpreterStack = ((Interpreter) interpreter).getScriptStackElements(this);
302 }
303
304 int interpreterStackIndex = 0;
305 StackTraceElement[] stack = getStackTrace();
306 int count = 0;
307 boolean printStarted = (hideFunction == null);
308
309 // Pattern to recover function name from java method name -
310 // see Codegen.getBodyMethodName()
311 // kudos to Marc Guillemot for coming up with this
312 for (StackTraceElement e : stack) {
313 String fileName = e.getFileName();
314 if (e.getMethodName().startsWith("_c_")
315 && e.getLineNumber() > -1
316 && fileName != null
317 && !fileName.endsWith(".java")) {
318 String methodName = e.getMethodName();
319 Matcher match = JAVA_STACK_PATTERN.matcher(methodName);
320 // the method representing the main script is always "_c_script_0" -
321 // at least we hope so
322 methodName = !"_c_script_0".equals(methodName) && match.find() ?
323 match.group(1) : null;
324
325 if (!printStarted && hideFunction.equals(methodName)) {
326 printStarted = true;
327 } else if (printStarted && ((limit < 0) || (count < limit))) {
328 list.add(new ScriptStackElement(fileName, methodName, e.getLineNumber()));
329 count++;
330 }
331
332 } else if ("org.mozilla.javascript.Interpreter".equals(e.getClassName())
333 && "interpretLoop".equals(e.getMethodName())
334 && interpreterStack != null
335 && interpreterStack.length > interpreterStackIndex) {
336
337 for (ScriptStackElement elem : interpreterStack[interpreterStackIndex++]) {
338 if (!printStarted && hideFunction.equals(elem.functionName)) {
339 printStarted = true;
340 } else if (printStarted && ((limit < 0) || (count < limit))) {
341 list.add(elem);
342 count++;
343 }
344 }
345 }
346 }
347 return list.toArray(new ScriptStackElement[list.size()]);
348 }
349
350
351 @Override
352 public void printStackTrace(PrintWriter s)
353 {
354 if (interpreterStackInfo == null) {
355 super.printStackTrace(s);
356 } else {
357 s.print(generateStackTrace());
358 }
359 }
360
361 @Override
362 public void printStackTrace(PrintStream s)
363 {
364 if (interpreterStackInfo == null) {
365 super.printStackTrace(s);
366 } else {
367 s.print(generateStackTrace());
368 }
369 }
370
371 /**
372 * Returns true if subclasses of <code>RhinoException</code>
373 * use the Mozilla/Firefox style of rendering script stacks
374 * (<code>functionName()@fileName:lineNumber</code>)
375 * instead of Rhino's own Java-inspired format
376 * (<code> at fileName:lineNumber (functionName)</code>).
377 * @return true if stack is rendered in Mozilla/Firefox style
378 * @see ScriptStackElement
379 * @since 1.7R3
380 */
381 public static boolean usesMozillaStackStyle() {
382 return (stackStyle == StackStyle.MOZILLA);
383 }
384
385 /**
386 * Tell subclasses of <code>RhinoException</code> whether to
387 * use the Mozilla/Firefox style of rendering script stacks
388 * (<code>functionName()@fileName:lineNumber</code>)
389 * instead of Rhino's own Java-inspired format
390 * (<code> at fileName:lineNumber (functionName)</code>).
391 * Use "setStackStyle" to select between more than just the "Mozilla" and "Rhino" formats.
392 * @param flag whether to render stacks in Mozilla/Firefox style
393 * @see ScriptStackElement
394 * @since 1.7R3
395 */
396 public static void useMozillaStackStyle(boolean flag) {
397 stackStyle = (flag ? StackStyle.MOZILLA : StackStyle.RHINO);
398 }
399
400 /**
401 * Specify the stack style to use from between three different formats: "Rhino" (the default),
402 * "Mozilla", and "V8." See StackStyle for information about each.
403 * @param style the style to select -- an instance of the StackStyle class
404 * @see StackStyle
405 * @since 1.8.0
406 */
407 public static void setStackStyle(StackStyle style) {
408 stackStyle = style;
409 }
410
411 /**
412 * Return the current stack style in use.
413 * Return the current stack style in use.
414 */
415 public static StackStyle getStackStyle() {
416 return stackStyle;
417 }
418
419 static final long serialVersionUID = 1883500631321581169L;
420
421 // Just for testing!
422 private static StackStyle stackStyle = StackStyle.RHINO;
423
424 private String sourceName;
425 private int lineNumber;
426 private String lineSource;
427 private int columnNumber;
428
429 Object interpreterStackInfo;
430 int[] interpreterLineData;
431
432 // Allow us to override default stack style for debugging.
433 static {
434 String style = System.getProperty("rhino.stack.style");
435 if (style != null) {
436 if ("Rhino".equalsIgnoreCase(style)) {
437 stackStyle = StackStyle.RHINO;
438 } else if ("Mozilla".equalsIgnoreCase(style)) {
439 stackStyle = StackStyle.MOZILLA;
440 } else if ("V8".equalsIgnoreCase(style)) {
441 stackStyle = StackStyle.V8;
442 }
443 }
444 }
445 }