forked from mozilla/rhino
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContext.java
More file actions
1819 lines (1680 loc) · 63.8 KB
/
Copy pathContext.java
File metadata and controls
1819 lines (1680 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (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.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Patrick Beard
* Norris Boyd
* Brendan Eich
* Roger Lawrence
* Mike McCabe
* Ian D. Stewart
* Andi Vajda
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
// API class
package org.mozilla.javascript;
import java.beans.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import java.lang.reflect.*;
import org.mozilla.javascript.debug.*;
/**
* This class represents the runtime context of an executing script.
*
* Before executing a script, an instance of Context must be created
* and associated with the thread that will be executing the script.
* The Context will be used to store information about the executing
* of the script such as the call stack. Contexts are associated with
* the current thread using the <a href="#enter()">enter()</a> method.<p>
*
* The behavior of the execution engine may be altered through methods
* such as <a href="#setLanguageVersion>setLanguageVersion</a> and
* <a href="#setErrorReporter>setErrorReporter</a>.<p>
*
* Different forms of script execution are supported. Scripts may be
* evaluated from the source directly, or first compiled and then later
* executed. Interactive execution is also supported.<p>
*
* Some aspects of script execution, such as type conversions and
* object creation, may be accessed directly through methods of
* Context.
*
* @see Scriptable
* @author Norris Boyd
* @author Brendan Eich
*/
public final class Context {
public static String languageVersionProperty = "language version";
public static String errorReporterProperty = "error reporter";
/**
* Create a new Context.
*
* Note that the Context must be associated with a thread before
* it can be used to execute a script.
*
* @see org.mozilla.javascript.Context#enter
*/
public Context() {
setLanguageVersion(VERSION_DEFAULT);
optimizationLevel = codegenClass != null ? 0 : -1;
}
/**
* Create a new context with the associated security support.
*
* @param securitySupport an encapsulation of the functionality
* needed to support security for scripts.
* @see org.mozilla.javascript.SecuritySupport
*/
public Context(SecuritySupport securitySupport) {
this();
this.securitySupport = securitySupport;
}
/**
* Get a context associated with the current thread, creating
* one if need be.
*
* The Context stores the execution state of the JavaScript
* engine, so it is required that the context be entered
* before execution may begin. Once a thread has entered
* a Context, then getCurrentContext() may be called to find
* the context that is associated with the current thread.
* <p>
* Calling <code>enter()</code> will
* return either the Context currently associated with the
* thread, or will create a new context and associate it
* with the current thread. Each call to <code>enter()</code>
* must have a matching call to <code>exit()</code>. For example,
* <pre>
* Context cx = Context.enter();
* ...
* cx.evaluateString(...);
* Context.exit();
* </pre>
* @return a Context associated with the current thread
* @see org.mozilla.javascript.Context#getCurrentContext
* @see org.mozilla.javascript.Context#exit
*/
public static Context enter() {
return enter(null);
}
/**
* Get a Context associated with the current thread, using
* the given Context if need be.
* <p>
* The same as <code>enter()</code> except that <code>cx</code>
* is associated with the current thread and returned if
* the current thread has no associated context and <code>cx</code>
* is not associated with any other thread.
* @param cx a Context to associate with the thread if possible
* @return a Context associated with the current thread
*/
public static Context enter(Context cx) {
// There's some duplication of code in this method to avoid
// unnecessary synchronizations.
Thread t = Thread.currentThread();
Context current = (Context) threadContexts.get(t);
if (current != null) {
synchronized (current) {
current.enterCount++;
}
return current;
}
if (cx != null) {
synchronized (cx) {
if (cx.currentThread == null) {
cx.currentThread = t;
threadContexts.put(t, cx);
cx.enterCount++;
return cx;
}
}
}
current = new Context();
current.currentThread = t;
threadContexts.put(t, current);
current.enterCount = 1;
return current;
}
/**
* Exit a block of code requiring a Context.
*
* Calling <code>exit()</code> will remove the association between
* the current thread and a Context if the prior call to
* <code>enter()</code> on this thread newly associated a Context
* with this thread.
* Once the current thread no longer has an associated Context,
* it cannot be used to execute JavaScript until it is again associated
* with a Context.
*
* @see org.mozilla.javascript.Context#enter
*/
public static void exit() {
Context cx = getCurrentContext();
if (cx != null) {
synchronized (cx) {
if (--cx.enterCount == 0) {
threadContexts.remove(cx.currentThread);
cx.currentThread = null;
}
}
}
}
/**
* Get the current Context.
*
* The current Context is per-thread; this method looks up
* the Context associated with the current thread. <p>
*
* @return the Context associated with the current thread, or
* null if no context is associated with the current
* thread.
* @see org.mozilla.javascript.Context#enter
* @see org.mozilla.javascript.Context#exit
*/
public static Context getCurrentContext() {
Thread t = Thread.currentThread();
return (Context) threadContexts.get(t);
}
/**
* Language versions
*
* All integral values are reserved for future version numbers.
*/
/**
* The unknown version.
*/
public static final int VERSION_UNKNOWN = -1;
/**
* The default version.
*/
public static final int VERSION_DEFAULT = 0;
/**
* JavaScript 1.0
*/
public static final int VERSION_1_0 = 100;
/**
* JavaScript 1.1
*/
public static final int VERSION_1_1 = 110;
/**
* JavaScript 1.2
*/
public static final int VERSION_1_2 = 120;
/**
* JavaScript 1.3
*/
public static final int VERSION_1_3 = 130;
/**
* JavaScript 1.4
*/
public static final int VERSION_1_4 = 140;
/**
* JavaScript 1.5
*/
public static final int VERSION_1_5 = 150;
/**
* Get the current language version.
* <p>
* The language version number affects JavaScript semantics as detailed
* in the overview documentation.
*
* @return an integer that is one of VERSION_1_0, VERSION_1_1, etc.
*/
public int getLanguageVersion() {
return version;
}
/**
* Set the language version.
*
* <p>
* Setting the language version will affect functions and scripts compiled
* subsequently. See the overview documentation for version-specific
* behavior.
*
* @param version the version as specified by VERSION_1_0, VERSION_1_1, etc.
*/
public void setLanguageVersion(int version) {
if (listeners != null && version != this.version) {
firePropertyChange(languageVersionProperty,
new Integer(this.version),
new Integer(version));
}
this.version = version;
}
/**
* Get the implementation version.
*
* <p>
* The implementation version is of the form
* <pre>
* "<i>name langVer</i> <code>release</code> <i>relNum date</i>"
* </pre>
* where <i>name</i> is the name of the product, <i>langVer</i> is
* the language version, <i>relNum</i> is the release number, and
* <i>date</i> is the release date for that specific
* release in the form "yyyy mm dd".
*
* @return a string that encodes the product, language version, release
* number, and date.
*/
public String getImplementationVersion() {
return "JavaScript-Java 1.5 release 1 2000 03 15";
}
/**
* Get the current error reporter.
*
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter getErrorReporter() {
if (errorReporter == null) {
errorReporter = new DefaultErrorReporter();
}
return errorReporter;
}
/**
* Change the current error reporter.
*
* @return the previous error reporter
* @see org.mozilla.javascript.ErrorReporter
*/
public ErrorReporter setErrorReporter(ErrorReporter reporter) {
ErrorReporter result = errorReporter;
if (listeners != null && errorReporter != reporter) {
firePropertyChange(errorReporterProperty, errorReporter,
reporter);
}
errorReporter = reporter;
return result;
}
/**
* Get the current locale. Returns the default locale if none has
* been set.
*
* @see java.util.Locale
*/
public Locale getLocale() {
if (locale == null)
locale = Locale.getDefault();
return locale;
}
/**
* Set the current locale.
*
* @see java.util.Locale
*/
public Locale setLocale(Locale loc) {
Locale result = locale;
locale = loc;
return result;
}
/**
* Register an object to receive notifications when a bound property
* has changed
* @see java.beans.PropertyChangeEvent
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (listeners == null) {
listeners = new ListenerCollection();
}
listeners.addListener(listener);
}
/**
* Remove an object from the list of objects registered to receive
* notification of changes to a bounded property
* @see java.beans.PropertyChangeEvent
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @param listener the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.removeListener(listener);
}
/**
* Notify any registered listeners that a bounded property has changed
* @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
* @see java.beans.PropertyChangeListener
* @see java.beans.PropertyChangeEvent
* @param property the bound property
* @param oldValue the old value
* @param newVale the new value
*/
protected void firePropertyChange(String property, Object oldValue,
Object newValue) {
Class listenerClass = java.beans.PropertyChangeListener.class;
Object[] listenerList = listeners.getListeners(listenerClass);
for(int i = 0; i < listenerList.length; i++) {
PropertyChangeListener l =
(PropertyChangeListener)listenerList[i];
l.propertyChange(new PropertyChangeEvent(
this, property, oldValue, newValue));
}
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = Context.getContext();
cx.getErrorReporter().warning(message, sourceName, lineno,
lineSource, lineOffset);
}
/**
* Report a warning using the error reporter for the current thread.
*
* @param message the warning message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportWarning(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportWarning(message, filename, linep[0], null, 0);
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message, String sourceName,
int lineno, String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.errorCount++;
cx.getErrorReporter().error(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message);
}
}
/**
* Report an error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static void reportError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
Context.reportError(message, filename, linep[0], null, 0);
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param lineSource the text of the line (may be null)
* @param lineOffset the offset into lineSource where problem was detected
* @return a runtime exception that will be thrown to terminate the
* execution of the script
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message,
String sourceName,
int lineno,
String lineSource,
int lineOffset)
{
Context cx = getCurrentContext();
if (cx != null) {
cx.errorCount++;
return cx.getErrorReporter().
runtimeError(message, sourceName, lineno,
lineSource, lineOffset);
} else {
throw new EvaluatorException(message);
}
}
/**
* Report a runtime error using the error reporter for the current thread.
*
* @param message the error message to report
* @see org.mozilla.javascript.ErrorReporter
*/
public static EvaluatorException reportRuntimeError(String message) {
int[] linep = { 0 };
String filename = getSourcePositionFromStack(linep);
return Context.reportRuntimeError(message, filename, linep[0], null, 0);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @return the initialized scope
*/
public Scriptable initStandardObjects(ScriptableObject scope) {
return initStandardObjects(scope, false);
}
/**
* Initialize the standard objects.
*
* Creates instances of the standard objects and their constructors
* (Object, String, Number, Date, etc.), setting up 'scope' to act
* as a global object as in ECMA 15.1.<p>
*
* This method must be called to initialize a scope before scripts
* can be evaluated in that scope.<p>
*
* This form of the method also allows for creating "sealed" standard
* objects. An object that is sealed cannot have properties added or
* removed. This is useful to create a "superglobal" that can be shared
* among several top-level objects. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* @param scope the scope to initialize, or null, in which case a new
* object will be created to serve as the scope
* @param sealed whether or not to create sealed standard objects that
* cannot be modified.
* @return the initialized scope
* @since 1.4R3
*/
public ScriptableObject initStandardObjects(ScriptableObject scope,
boolean sealed)
{
final String omj = "org.mozilla.javascript.";
try {
if (scope == null)
scope = new NativeObject();
ScriptableObject.defineClass(scope, NativeFunction.class, sealed);
ScriptableObject.defineClass(scope, NativeObject.class, sealed);
Scriptable objectProto = ScriptableObject.
getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.
getFunctionPrototype(scope);
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
ScriptableObject.defineClass(scope, NativeError.class, sealed);
ScriptableObject.defineClass(scope, NativeGlobal.class, sealed);
String[] classes = { "NativeArray", "Array",
"NativeString", "String",
"NativeBoolean", "Boolean",
"NativeNumber", "Number",
"NativeDate", "Date",
"NativeMath", "Math",
"NativeCall", "Call",
"NativeWith", "With",
"regexp.NativeRegExp", "RegExp",
"NativeScript", "Script",
};
for (int i=0; i < classes.length; i+=2) {
try {
if (sealed) {
Class c = Class.forName(omj + classes[i]);
ScriptableObject.defineClass(scope, c, sealed);
} else {
String s = omj + classes[i];
new LazilyLoadedCtor(scope, classes[i+1], s,
ScriptableObject.DONTENUM);
}
} catch (ClassNotFoundException e) {
continue;
}
}
// Define the JavaAdapter class, allowing it to be overridden.
String adapterName = "org.mozilla.javascript.JavaAdapter";
try {
adapterName = System.getProperty(adapterName, adapterName);
} catch (SecurityException e) {
// We may not be allowed to get system properties. Just
// use the default adapter in that case.
}
try {
Class adapterClass = Class.forName(adapterName);
ScriptableObject.defineClass(scope, adapterClass, sealed);
// This creates the Packages and java package roots.
Class c = Class.forName(omj + "NativeJavaPackage");
ScriptableObject.defineClass(scope, c, sealed);
} catch (ClassNotFoundException e) {
// If the class is not found, proceed without it.
} catch (SecurityException e) {
// Ignore AccessControlExceptions that may occur if a
// SecurityManager is installed:
// java.lang.RuntimePermission createClassLoader
// java.util.PropertyPermission
// org.mozilla.javascript.JavaAdapter read
}
}
// All of these exceptions should not occur since we are initializing
// from known classes
catch (IllegalAccessException e) {
throw WrappedException.wrapException(e);
}
catch (InstantiationException e) {
throw WrappedException.wrapException(e);
}
catch (InvocationTargetException e) {
throw WrappedException.wrapException(e);
}
catch (ClassDefinitionException e) {
throw WrappedException.wrapException(e);
}
catch (PropertyException e) {
throw WrappedException.wrapException(e);
}
return scope;
}
/**
* Get the singleton object that represents the JavaScript Undefined value.
*/
public static Object getUndefinedValue() {
return Undefined.instance;
}
/**
* Evaluate a JavaScript source string.
*
* The provided source name and line number are used for error messages
* and for producing debug information.
*
* @param scope the scope to execute in
* @param source the JavaScript source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the string
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the source string
* @see org.mozilla.javascript.SecuritySupport
*/
public Object evaluateString(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
throws JavaScriptException
{
try {
Reader in = new StringReader(source);
return evaluateReader(scope, in, sourceName, lineno,
securityDomain);
}
catch (IOException ioe) {
// Should never occur because we just made the reader from a String
throw new RuntimeException();
}
}
/**
* Evaluate a reader as JavaScript source.
*
* All characters of the reader are consumed.
*
* @param scope the scope to execute in
* @param in the Reader to get JavaScript source from
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return the result of evaluating the source
*
* @exception IOException if an IOException was generated by the Reader
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while evaluating the Reader
*/
public Object evaluateReader(Scriptable scope, Reader in,
String sourceName, int lineno,
Object securityDomain)
throws IOException, JavaScriptException
{
Script script = compileReader(scope, in, sourceName, lineno,
securityDomain);
if (script != null)
return script.exec(this, scope);
else
return null;
}
/**
* Check whether a string is ready to be compiled.
* <p>
* stringIsCompilableUnit is intended to support interactive compilation of
* javascript. If compiling the string would result in an error
* that might be fixed by appending more source, this method
* returns false. In every other case, it returns true.
* <p>
* Interactive shells may accumulate source lines, using this
* method after each new line is appended to check whether the
* statement being entered is complete.
*
* @param source the source buffer to check
* @return whether the source is ready for compilation
* @since 1.4 Release 2
*/
synchronized public boolean stringIsCompilableUnit(String source)
{
Reader in = new StringReader(source);
// no source name or source text manager, because we're just
// going to throw away the result.
TokenStream ts = new TokenStream(in, null, null, 1);
// Temporarily set error reporter to always be the exception-throwing
// DefaultErrorReporter. (This is why the method is synchronized...)
ErrorReporter currentReporter =
setErrorReporter(new DefaultErrorReporter());
boolean errorseen = false;
try {
IRFactory irf = new IRFactory(ts, null);
Parser p = new Parser(irf);
p.parse(ts);
} catch (IOException ioe) {
errorseen = true;
} catch (EvaluatorException ee) {
errorseen = true;
} finally {
// Restore the old error reporter.
setErrorReporter(currentReporter);
}
// Return false only if an error occurred as a result of reading past
// the end of the file, i.e. if the source could be fixed by
// appending more source.
if (errorseen && ts.eof())
return false;
else
return true;
}
/**
* Compiles the source in the given reader.
* <p>
* Returns a script that may later be executed.
* Will consume all the source in the reader.
*
* @param scope if nonnull, will be the scope in which the script object
* is created. The script object will be a valid JavaScript object
* as if it were created using the JavaScript1.3 Script constructor
* @param in the input reader
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number for reporting errors
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a script that may later be executed
* @see org.mozilla.javascript.Script#exec
* @exception IOException if an IOException was generated by the Reader
*/
public Script compileReader(Scriptable scope, Reader in, String sourceName,
int lineno, Object securityDomain)
throws IOException
{
return (Script) compile(scope, in, sourceName, lineno, securityDomain,
false);
}
/**
* Compile a JavaScript function.
* <p>
* The function source must be a function definition as defined by
* ECMA (e.g., "function f(a) { return a; }").
*
* @param scope the scope to compile relative to
* @param source the function definition source
* @param sourceName a string describing the source, such as a filename
* @param lineno the starting line number
* @param securityDomain an arbitrary object that specifies security
* information about the origin or owner of the script. For
* implementations that don't care about security, this value
* may be null.
* @return a Function that may later be called
* @see org.mozilla.javascript.Function
*/
public Function compileFunction(Scriptable scope, String source,
String sourceName, int lineno,
Object securityDomain)
{
Reader in = new StringReader(source);
try {
return (Function) compile(scope, in, sourceName, lineno,
securityDomain, true);
}
catch (IOException ioe) {
// Should never happen because we just made the reader
// from a String
throw new RuntimeException();
}
}
/**
* Decompile the script.
* <p>
* The canonical source of the script is returned.
*
* @param script the script to decompile
* @param scope the scope under which to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the script source
*/
public String decompileScript(Script script, Scriptable scope,
int indent)
{
NativeScript ns = (NativeScript) script;
ns.initScript(scope);
return ns.decompile(indent, true, false);
}
/**
* Decompile a JavaScript Function.
* <p>
* Decompiles a previously compiled JavaScript function object to
* canonical source.
* <p>
* Returns function body of '[native code]' if no decompilation
* information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function source
*/
public String decompileFunction(Function fun, int indent) {
if (fun instanceof NativeFunction)
return ((NativeFunction)fun).decompile(indent, true, false);
else
return "function " + fun.getClassName() +
"() {\n\t[native code]\n}\n";
}
/**
* Decompile the body of a JavaScript Function.
* <p>
* Decompiles the body a previously compiled JavaScript Function
* object to canonical source, omitting the function header and
* trailing brace.
*
* Returns '[native code]' if no decompilation information is available.
*
* @param fun the JavaScript function to decompile
* @param indent the number of spaces to indent the result
* @return a string representing the function body source.
*/
public String decompileFunctionBody(Function fun, int indent) {
if (fun instanceof NativeFunction)
return ((NativeFunction)fun).decompile(indent, true, true);
else
// not sure what the right response here is. JSRef currently
// dumps core.
return "[native code]\n";
}
/**
* Create a new JavaScript object.
*
* Equivalent to evaluating "new Object()".
* @param scope the scope to search for the constructor and to evaluate
* against
* @return the new object
* @exception PropertyException if "Object" cannot be found in
* the scope
* @exception NotAFunctionException if the "Object" found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
return newObject(scope, "Object", null);
}
/**
* Create a new JavaScript object by executing the named constructor.
*
* The call <code>newObject("Foo")</code> is equivalent to
* evaluating "new Foo()".
*
* @param scope the scope to search for the constructor and to evaluate against
* @param constructorName the name of the constructor to call
* @return the new object
* @exception PropertyException if a property with the constructor
* name cannot be found in the scope
* @exception NotAFunctionException if the property found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurred while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
return newObject(scope, constructorName, null);
}
/**
* Creates a new JavaScript object by executing the named constructor.
*
* Searches <code>scope</code> for the named constructor, calls it with
* the given arguments, and returns the result.<p>
*
* The code
* <pre>
* Object[] args = { "a", "b" };
* newObject(scope, "Foo", args)</pre>
* is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo
* constructor has been defined in <code>scope</code>.
*
* @param scope The scope to search for the constructor and to evaluate
* against
* @param constructorName the name of the constructor to call
* @param args the array of arguments for the constructor
* @return the new object
* @exception PropertyException if a property with the constructor
* name cannot be found in the scope
* @exception NotAFunctionException if the property found in the scope
* is not a function
* @exception JavaScriptException if an uncaught JavaScript exception
* occurs while creating the object
*/
public Scriptable newObject(Scriptable scope, String constructorName,
Object[] args)
throws PropertyException,
NotAFunctionException,
JavaScriptException
{
Object ctorVal = ScriptRuntime.getTopLevelProp(scope, constructorName);
if (ctorVal == Scriptable.NOT_FOUND) {
Object[] errArgs = { constructorName };
String message = getMessage("msg.ctor.not.found", errArgs);
throw new PropertyException(message);
}
if (!(ctorVal instanceof Function)) {
Object[] errArgs = { constructorName };
String message = getMessage("msg.not.ctor", errArgs);