forked from mozilla/rhino
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathInterpreter.java
More file actions
5308 lines (4777 loc) · 211 KB
/
Interpreter.java
File metadata and controls
5308 lines (4777 loc) · 211 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 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
import static org.mozilla.javascript.UniqueTag.DOUBLE_MARK;
import java.io.PrintStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.mozilla.javascript.ScriptRuntime.NoSuchMethodShim;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.ast.ScriptNode;
import org.mozilla.javascript.debug.DebugFrame;
import org.mozilla.javascript.debug.DebuggableScript;
public final class Interpreter extends Icode implements Evaluator {
static final int EXCEPTION_TRY_START_SLOT = 0;
static final int EXCEPTION_TRY_END_SLOT = 1;
static final int EXCEPTION_HANDLER_SLOT = 2;
static final int EXCEPTION_TYPE_SLOT = 3;
static final int EXCEPTION_LOCAL_SLOT = 4;
static final int EXCEPTION_SCOPE_SLOT = 5;
// SLOT_SIZE: space for try start/end, handler, start, handler type,
// exception local and scope local
static final int EXCEPTION_SLOT_SIZE = 6;
/** Class to hold data corresponding to one interpreted call stack frame. */
private static class CallFrame implements Cloneable, Serializable {
private static final long serialVersionUID = -2843792508994958978L;
// fields marked "final" in a comment are effectively final except when they're modified
// immediately after cloning.
final CallFrame parentFrame;
// amount of stack frames before this one on the interpretation stack
final short frameIndex;
// The frame that the iterator was executing.
final CallFrame previousInterpreterFrame;
final int parentPC;
// If true indicates read-only frame that is a part of continuation
boolean frozen;
final ScriptOrFn<?> fnOrScript;
final InterpreterData<?> idata;
// Stack structure
// stack[0 <= i < localShift]: arguments and local variables
// stack[localShift <= i <= emptyStackTop]: used for local temporaries
// stack[emptyStackTop < i < stack.length]: stack data
// sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value
final Object[] stack;
final byte[] stackAttributes;
final double[] sDbl;
final CallFrame varSource; // defaults to this unless continuation frame
final short emptyStackTop;
final DebugFrame debuggerFrame;
final boolean useActivation;
boolean isContinuationsTopFrame;
final Scriptable thisObj;
// The values that change during interpretation
Object result;
double resultDbl;
int pc;
int pcPrevBranch;
int pcSourceLineStart;
Scriptable scope;
int savedStackTop;
int savedCallOp;
Object throwable;
boolean parentStrictness;
CallFrame(
Context cx,
Scriptable thisObj,
ScriptOrFn fnOrScript,
InterpreterData code,
CallFrame parentFrame,
CallFrame previousInterpreterFrame) {
idata = code;
debuggerFrame =
cx.debugger != null
? cx.debugger.getFrame(cx, fnOrScript.getDescriptor())
: null;
useActivation = fnOrScript.getDescriptor().requiresActivationFrame();
emptyStackTop = (short) (idata.itsMaxVars + idata.itsMaxLocals - 1);
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1) Kit.codeBug();
stack = new Object[maxFrameArray];
stackAttributes = new byte[maxFrameArray];
sDbl = new double[maxFrameArray];
this.fnOrScript = fnOrScript;
varSource = this;
this.thisObj = thisObj;
this.parentFrame = parentFrame;
if (parentFrame == null) {
this.parentPC =
previousInterpreterFrame == null
? -1
: previousInterpreterFrame.pcSourceLineStart;
} else {
this.parentPC = parentFrame.pcSourceLineStart;
}
this.previousInterpreterFrame = previousInterpreterFrame;
frameIndex = (short) ((parentFrame == null) ? 0 : parentFrame.frameIndex + 1);
if (frameIndex > cx.getMaximumInterpreterStackDepth()) {
throw Context.reportRuntimeError("Exceeded maximum stack depth");
}
// Initialize initial values of variables that change during
// interpretation.
result = Undefined.instance;
pcSourceLineStart = idata.firstLinePC;
savedStackTop = emptyStackTop;
}
private CallFrame(CallFrame original, boolean makeOrphan) {
this(
original,
makeOrphan ? null : original.parentFrame,
makeOrphan ? null : original.previousInterpreterFrame);
}
/* Copy the frame for *continuations*. Here we want to make
fresh copies of the stack and everything related to it. */
private CallFrame(
CallFrame original, CallFrame parentFrame, CallFrame previousInterpreterFrame) {
if (!original.frozen) Kit.codeBug();
stack = Arrays.copyOf(original.stack, original.stack.length);
stackAttributes =
Arrays.copyOf(original.stackAttributes, original.stackAttributes.length);
sDbl = Arrays.copyOf(original.sDbl, original.sDbl.length);
frozen = false;
this.parentFrame = parentFrame;
this.previousInterpreterFrame = previousInterpreterFrame;
if (parentFrame == null) {
frameIndex = 0;
parentPC =
previousInterpreterFrame == null
? -1
: previousInterpreterFrame.pcSourceLineStart;
} else {
frameIndex = original.frameIndex;
parentPC = parentFrame.pcSourceLineStart;
}
fnOrScript = original.fnOrScript;
idata = original.idata;
varSource = original.varSource;
emptyStackTop = original.emptyStackTop;
debuggerFrame = original.debuggerFrame;
useActivation = original.useActivation;
isContinuationsTopFrame = original.isContinuationsTopFrame;
thisObj = original.thisObj;
result = original.result;
resultDbl = original.resultDbl;
pc = original.pc;
pcPrevBranch = original.pcPrevBranch;
pcSourceLineStart = original.pcSourceLineStart;
scope = original.scope;
savedStackTop = original.savedStackTop;
savedCallOp = original.savedCallOp;
throwable = original.throwable;
}
/* Copy the stack for running a generator. We're only doing
this to maintain the correct chain of parents for exception
stacks, so we'll reuse the existing stack arrays. */
private CallFrame(
CallFrame original,
CallFrame parentFrame,
CallFrame previousInterpreterFrame,
boolean keepFrozen) {
if (!original.frozen) Kit.codeBug();
stack = original.stack;
stackAttributes = original.stackAttributes;
sDbl = original.sDbl;
frozen = keepFrozen;
this.parentFrame = parentFrame;
this.previousInterpreterFrame = previousInterpreterFrame;
if (parentFrame == null) {
frameIndex = 0;
parentPC =
previousInterpreterFrame == null
? -1
: previousInterpreterFrame.pcSourceLineStart;
} else {
frameIndex = original.frameIndex;
parentPC = parentFrame.pcSourceLineStart;
}
fnOrScript = original.fnOrScript;
idata = original.idata;
varSource = original.varSource;
emptyStackTop = original.emptyStackTop;
debuggerFrame = original.debuggerFrame;
useActivation = original.useActivation;
isContinuationsTopFrame = original.isContinuationsTopFrame;
thisObj = original.thisObj;
result = original.result;
resultDbl = original.resultDbl;
pc = original.pc;
pcPrevBranch = original.pcPrevBranch;
pcSourceLineStart = original.pcSourceLineStart;
scope = original.scope;
savedStackTop = original.savedStackTop;
savedCallOp = original.savedCallOp;
throwable = original.throwable;
}
void initializeArgs(
Context cx,
Scriptable callerScope,
Object[] args,
double[] argsDbl,
Object[] boundArgs,
int argShift,
int argCount,
Scriptable homeObject) {
var desc = fnOrScript.getDescriptor();
if (useActivation) {
// Copy args to new array to pass to enterActivationFunction
// or debuggerFrame.onEnter
if (argsDbl != null || boundArgs != null) {
int blen = boundArgs == null ? 0 : boundArgs.length;
args = getArgsArray(args, argsDbl, boundArgs, blen, argShift, argCount);
}
argShift = 0;
argsDbl = null;
boundArgs = null;
}
if (desc.getFunctionType() != 0) {
scope = fnOrScript.getDeclarationScope();
this.parentStrictness = ScriptRuntime.enterFunctionStrictness(cx, desc.isStrict());
if (useActivation) {
if (desc.getFunctionType() == FunctionNode.ARROW_FUNCTION) {
scope =
ScriptRuntime.createArrowFunctionActivation(
(JSFunction) fnOrScript,
cx,
scope,
args,
desc.hasRestArg(),
desc.requiresArgumentObject());
} else {
scope =
ScriptRuntime.createFunctionActivation(
(JSFunction) fnOrScript,
cx,
scope,
args,
desc.hasRestArg(),
desc.requiresArgumentObject());
}
}
} else {
scope = callerScope;
ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope, desc.isEvalFunction());
}
// Defer default parameters and nested function declarations until activation scope
// creation
// Ref: Ecma 2026, 10.2.11, FunctionDeclarationInstantiation
if (desc.getFunctionCount() != 0 && !desc.isES6Generator()) {
if (desc.getFunctionType() != 0 && !desc.requiresActivationFrame()) Kit.codeBug();
for (int i = 0; i < desc.getFunctionCount(); i++) {
JSDescriptor fdesc = desc.getFunction(i);
if (fdesc.getFunctionType() == FunctionNode.FUNCTION_STATEMENT) {
initFunction(cx, scope, fnOrScript.getDescriptor(), i);
}
}
}
int varCount = desc.getParamAndVarCount();
for (int i = 0; i < varCount; i++) {
if (desc.getParamOrVarConst(i)) stackAttributes[i] = ScriptableObject.CONST;
}
int definedArgs = desc.getParamCount();
if (definedArgs > argCount) {
definedArgs = argCount;
}
// Fill the frame structure
int blen = 0;
if (boundArgs != null) {
blen = Math.min(definedArgs, boundArgs.length);
System.arraycopy(boundArgs, 0, stack, 0, blen);
}
System.arraycopy(args, argShift, stack, blen, definedArgs - blen);
if (argsDbl != null) {
System.arraycopy(argsDbl, argShift, sDbl, blen, definedArgs - blen);
}
for (int i = definedArgs; i != idata.itsMaxVars; ++i) {
stack[i] = Undefined.instance;
}
if (desc.hasRestArg()) {
Object[] vals;
int offset = desc.getParamCount() - 1;
if (argCount >= desc.getParamCount()) {
vals = new Object[argCount - offset];
argShift = argShift + offset;
for (int valsIdx = 0; valsIdx != vals.length; ++argShift, ++valsIdx) {
Object val = args[argShift];
if (val == UniqueTag.DOUBLE_MARK) {
val = ScriptRuntime.wrapNumber(argsDbl[argShift]);
}
vals[valsIdx] = val;
}
} else {
vals = ScriptRuntime.emptyArgs;
}
stack[offset] = cx.newArray(scope, vals);
}
}
CallFrame cloneFrozen() {
return new CallFrame(this, false);
}
CallFrame shallowCloneFrozen(CallFrame newPreviousInterpreeterFrame) {
return new CallFrame(this, this.parentFrame, newPreviousInterpreeterFrame, true);
}
void syncStateToFrame(CallFrame otherFrame) {
otherFrame.frozen = frozen;
otherFrame.isContinuationsTopFrame = isContinuationsTopFrame;
otherFrame.result = result;
otherFrame.resultDbl = resultDbl;
otherFrame.pc = pc;
otherFrame.pcPrevBranch = pcPrevBranch;
otherFrame.pcSourceLineStart = pcSourceLineStart;
otherFrame.scope = scope;
otherFrame.savedStackTop = savedStackTop;
otherFrame.savedCallOp = savedCallOp;
otherFrame.throwable = throwable;
}
@Override
public boolean equals(Object other) {
// Overridden for semantic equality comparison. These objects
// are typically exposed as NativeContinuation.implementation,
// comparing them allows establishing whether the continuations
// are semantically equal.
if (other instanceof CallFrame) {
// If the call is not within a Context with a top call, we force
// one. It is required as some objects within fully initialized
// global scopes (notably, XMLLibImpl) need to have a top scope
// in order to evaluate their attributes.
try (Context cx = Context.enter()) {
if (ScriptRuntime.hasTopCall(cx)) {
return equalsInTopScope(other).booleanValue();
}
final Scriptable top = ScriptableObject.getTopLevelScope(scope);
return ((Boolean)
ScriptRuntime.doTopCall(
(c, scope, thisObj) -> equalsInTopScope(other),
cx,
top,
top,
isStrictTopFrame()))
.booleanValue();
}
}
return false;
}
@Override
public int hashCode() {
// Overridden for consistency with equals.
// Trying to strike a balance between speed of calculation and
// distribution. Not hashing stack variables as those could have
// unbounded computational cost and limit it to topmost 8 frames.
int depth = 0;
CallFrame f = this;
int h = 0;
do {
h = 31 * (31 * h + f.pc) + f.idata.icodeHashCode();
f = f.parentFrame;
} while (f != null && depth++ < 8);
return h;
}
private Boolean equalsInTopScope(Object other) {
return EqualObjectGraphs.withThreadLocal(eq -> equals(this, (CallFrame) other, eq));
}
private boolean isStrictTopFrame() {
CallFrame f = this;
for (; ; ) {
final CallFrame p = f.parentFrame;
if (p == null) {
return f.fnOrScript.getDescriptor().isStrict();
}
f = p;
}
}
@SuppressWarnings("ReferenceEquality")
private static Boolean equals(CallFrame f1, CallFrame f2, EqualObjectGraphs equal) {
// Iterative instead of recursive, as interpreter stack depth can
// be larger than JVM stack depth.
for (; ; ) {
if (f1 == f2) {
return Boolean.TRUE;
} else if (f1 == null || f2 == null) {
return Boolean.FALSE;
} else if (!f1.fieldsEqual(f2, equal)) {
return Boolean.FALSE;
} else {
f1 = f1.parentFrame;
f2 = f2.parentFrame;
}
}
}
private boolean fieldsEqual(CallFrame other, EqualObjectGraphs equal) {
return frameIndex == other.frameIndex
&& pc == other.pc
&& compareDescs(fnOrScript.getDescriptor(), other.fnOrScript.getDescriptor())
&& equal.equalGraphs(varSource.stack, other.varSource.stack)
&& Arrays.equals(varSource.sDbl, other.varSource.sDbl)
&& equal.equalGraphs(thisObj, other.thisObj)
&& equal.equalGraphs(fnOrScript, other.fnOrScript)
&& equal.equalGraphs(scope, other.scope);
}
CallFrame captureForGenerator() {
return new CallFrame(this, true);
}
Object getFromVars(int offset) {
Object value = stack[offset];
if (value == DOUBLE_MARK) {
return sDbl[offset];
} else {
return value;
}
}
void setInVars(int offset, Object value) {
if (value instanceof Double && Double.isFinite((Double) value)) {
stack[offset] = DOUBLE_MARK;
sDbl[offset] = ((Double) value);
} else {
stack[offset] = value;
}
}
}
/**
* This class is intended as proxy to give {@link DebugFrame} access to the contents of local
* variables. We take this approach rather than forcing the interpreter to introduce activation
* frames because it is faster (assuming local variable manipulation by the interpreter is more
* common than inspection by the debugger) and it reduces the chance that programs might
* evexcute differently in debug mode.
*/
private static class DebugScope implements Scriptable {
private final CallFrame frame;
private volatile Map<String, Integer> offsets;
/** Create a new debug scope associated with a particular call frame. */
private DebugScope(CallFrame frame) {
this.frame = frame;
}
/**
* Populate the map associating names to variable indices. Most names should have been made
* unique as part of the compilation process, but arguments with duplicate names will not
* have been.The map is build so that duplicate argument names resolve to the last index as
* this is also what the compiler does - at least once we are past setting default values.
*/
private Map<String, Integer> getOffsets() {
if (offsets == null) {
offsets = buildOffsets(frame);
}
return offsets;
}
private static Map<String, Integer> buildOffsets(CallFrame frame) {
var desc = frame.fnOrScript.getDescriptor();
int varCount = desc.getParamAndVarCount();
var map = new HashMap<String, Integer>();
for (int i = 0; i < varCount; i++) {
map.put(desc.getParamOrVarName(i), i);
}
return map;
}
@Override
public void delete(String name) {}
@Override
public void delete(int index) {}
@Override
public Object get(String name, Scriptable start) {
int offset = getOffsets().getOrDefault(name, -1);
return offset >= 0 ? frame.getFromVars(offset) : NOT_FOUND;
}
@Override
public Object get(int index, Scriptable start) {
return NOT_FOUND;
}
@Override
public String getClassName() {
return "debugscope";
}
@Override
public Object getDefaultValue(Class<?> hint) {
return null;
}
@Override
public Object[] getIds() {
return getOffsets().keySet().toArray();
}
@Override
public Scriptable getParentScope() {
return frame.scope;
}
@Override
public Scriptable getPrototype() {
return null;
}
@Override
public boolean has(String name, Scriptable start) {
return getOffsets().containsKey(name);
}
@Override
public boolean has(int index, Scriptable start) {
return false;
}
@Override
public boolean hasInstance(Scriptable instance) {
return false;
}
@Override
public void put(String name, Scriptable start, Object value) {
int offset = getOffsets().getOrDefault(name, -1);
if (offset >= 0) {
frame.setInVars(offset, value);
}
}
@Override
public void put(int index, Scriptable start, Object value) {
// Do nothing.
}
@Override
public void setParentScope(Scriptable parent) {
// Do nothing.
}
@Override
public void setPrototype(Scriptable prototype) {
// Do nothing.
}
}
private static boolean compareDescs(JSDescriptor i1, JSDescriptor i2) {
return i1 == i2 || Objects.equals(getRawSource(i1), getRawSource(i2));
}
private static final class ContinuationJump implements Serializable {
private static final long serialVersionUID = 7687739156004308247L;
CallFrame capturedFrame;
CallFrame branchFrame;
Object result;
double resultDbl;
ContinuationJump(NativeContinuation c, CallFrame current) {
this.capturedFrame = (CallFrame) c.getImplementation();
if (this.capturedFrame == null || current == null) {
// Continuation and current execution does not share
// any frames if there is nothing to capture or
// if there is no currently executed frames
this.branchFrame = null;
} else {
// Search for branch frame where parent frame chains starting
// from captured and current meet.
CallFrame chain1 = this.capturedFrame;
CallFrame chain2 = current;
// First work parents of chain1 or chain2 until the same
// frame depth.
int diff = chain1.frameIndex - chain2.frameIndex;
if (diff != 0) {
if (diff < 0) {
// swap to make sure that
// chain1.frameIndex > chain2.frameIndex and diff > 0
chain1 = current;
chain2 = this.capturedFrame;
diff = -diff;
}
do {
chain1 = chain1.parentFrame;
} while (--diff != 0);
if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug();
}
// Now walk parents in parallel until a shared frame is found
// or until the root is reached.
while (!Objects.equals(chain1, chain2) && chain1 != null) {
chain1 = chain1.parentFrame;
chain2 = chain2.parentFrame;
}
this.branchFrame = chain1;
if (this.branchFrame != null && !this.branchFrame.frozen) Kit.codeBug();
}
}
}
private static CallFrame captureFrameForGenerator(CallFrame frame) {
frame.frozen = true;
CallFrame result = frame.captureForGenerator();
frame.frozen = false;
return result;
}
static {
// Checks for byte code consistencies, good compiler can eliminate them
if (Token.LAST_BYTECODE_TOKEN > 127) {
String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127";
System.err.println(str);
throw new IllegalStateException(str);
}
if (MIN_ICODE < -128) {
String str = "Violation of Interpreter.MIN_ICODE >= -128";
System.err.println(str);
throw new IllegalStateException(str);
}
}
private static class CompilationResult<T extends ScriptOrFn<T>> {
private final JSDescriptor<T> descriptor;
private final Scriptable homeObject;
CompilationResult(JSDescriptor<T> descriptor, Scriptable homeObject) {
this.descriptor = descriptor;
this.homeObject = homeObject;
}
}
@Override
@SuppressWarnings("unchecked")
public Object compile(
CompilerEnvirons compilerEnv,
ScriptNode tree,
String rawSource,
boolean returnFunction) {
CodeGenerator<?> cgen = new CodeGenerator<>();
var itsData = cgen.compile(compilerEnv, tree, rawSource, returnFunction);
return new CompilationResult(itsData, compilerEnv.homeObject());
}
@Override
@SuppressWarnings("unchecked")
public DebuggableScript getDebuggableScript(Object bytecode) {
return ((CompilationResult<?>) bytecode).descriptor;
}
@Override
@SuppressWarnings("unchecked")
public Script createScriptObject(Object bytecode, Object staticSecurityDomain) {
var compilerResult = (CompilationResult<JSScript>) bytecode;
return JSFunction.createScript(
compilerResult.descriptor, compilerResult.homeObject, staticSecurityDomain);
}
@Override
public void setEvalScriptFlag(Script script) {
throw new UnsupportedOperationException();
}
@Override
@SuppressWarnings("unchecked")
public Function createFunctionObject(
Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) {
var compilerResult = (CompilationResult<JSFunction>) bytecode;
return JSFunction.createFunction(
cx,
scope,
compilerResult.descriptor,
compilerResult.homeObject,
staticSecurityDomain);
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getIndex(byte[] iCode, int pc) {
return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24)
| ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8)
| (iCode[pc + 3] & 0xFF);
}
private static int getExceptionHandler(CallFrame frame, boolean onlyFinally) {
int[] exceptionTable = frame.idata.itsExceptionTable;
if (exceptionTable == null) {
// No exception handlers
return -1;
}
// Icode switch in the interpreter increments PC immediately
// and it is necessary to subtract 1 from the saved PC
// to point it before the start of the next instruction.
int pc = frame.pc - 1;
// OPT: use binary search
int best = -1, bestStart = 0, bestEnd = 0;
for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
if (!(start <= pc && pc < end)) {
continue;
}
if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) {
continue;
}
if (best >= 0) {
// Since handlers always nest and they never have shared end
// although they can share start it is sufficient to compare
// handlers ends
if (bestEnd < end) {
continue;
}
// Check the above assumption
if (bestStart > start) Kit.codeBug(); // should be nested
if (bestEnd == end) Kit.codeBug(); // no ens sharing
}
best = i;
bestStart = start;
bestEnd = end;
}
return best;
}
static PrintStream interpreterBytecodePrintStream = System.out;
static <T extends ScriptOrFn<T>> void dumpICode(
InterpreterData.Builder<T> idata, JSDescriptor.Builder<T> desc) {
if (!Token.printICode) {
return;
}
byte[] iCode = idata.itsICode;
int iCodeLength = iCode.length;
PrintStream out = interpreterBytecodePrintStream;
out.println("ICode dump, for " + desc.name + ", length = " + iCodeLength);
out.println("MaxStack = " + idata.itsMaxStack);
ICodeDumpContext ctx = new ICodeDumpContext(out, idata);
for (int pc = 0; pc < iCodeLength; ) {
out.flush();
out.print(" [" + pc + "] ");
int token = iCode[pc];
int icodeLength = bytecodeSpan(token);
String tname = Icode.bytecodeName(token);
ctx.pc = pc + 1;
InstructionClass instr = instructionObjs[-MIN_ICODE + token];
instr.dumpICode(token, tname, ctx);
if (pc + icodeLength != ctx.pc) Kit.codeBug();
pc += icodeLength;
}
int[] table = idata.itsExceptionTable;
if (table != null) {
out.println("Exception handlers: " + table.length / EXCEPTION_SLOT_SIZE);
for (int i = 0; i != table.length; i += EXCEPTION_SLOT_SIZE) {
int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
int handlerStart = table[i + EXCEPTION_HANDLER_SLOT];
int type = table[i + EXCEPTION_TYPE_SLOT];
int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT];
out.println(
" tryStart="
+ tryStart
+ " tryEnd="
+ tryEnd
+ " handlerStart="
+ handlerStart
+ " type="
+ (type == 0 ? "catch" : "finally")
+ " exceptionLocal="
+ exceptionLocal);
}
}
out.flush();
}
private static int bytecodeSpan(int bytecode) {
switch (bytecode) {
case Token.THROW:
case Token.YIELD:
case Icode_YIELD_STAR:
case Icode_GENERATOR:
case Icode_GENERATOR_END:
case Icode_GENERATOR_RETURN:
// source line
return 1 + 2;
case Icode_GOSUB:
case Token.GOTO:
case Token.IFEQ:
case Token.IFNE:
case Icode_IFEQ_POP:
case Icode_IF_NULL_UNDEF:
case Icode_IF_NOT_NULL_UNDEF:
case Icode_LEAVEDQ:
// target pc offset
return 1 + 2;
case Icode_CALLSPECIAL:
case Icode_CALLSPECIAL_OPTIONAL:
// call type
// is new
// line number
return 1 + 1 + 1 + 2;
case Token.CATCH_SCOPE:
// scope flag
return 1 + 1;
case Icode_VAR_INC_DEC:
case Icode_NAME_INC_DEC:
case Icode_PROP_INC_DEC:
case Icode_ELEM_INC_DEC:
case Icode_REF_INC_DEC:
// type of ++/--
return 1 + 1;
case Icode_SHORTNUMBER:
// short number
return 1 + 2;
case Icode_INTNUMBER:
// int number
return 1 + 4;
case Icode_REG_IND1:
// ubyte index
return 1 + 1;
case Icode_REG_IND2:
// ushort index
return 1 + 2;
case Icode_REG_IND4:
// int index
return 1 + 4;
case Icode_REG_STR1:
// ubyte string index
return 1 + 1;
case Icode_REG_STR2:
// ushort string index
return 1 + 2;
case Icode_REG_STR4:
// int string index
return 1 + 4;
case Icode_GETVAR1:
case Icode_SETVAR1:
case Icode_SETCONSTVAR1:
// byte var index
return 1 + 1;
case Icode_LINE:
// line number
return 1 + 2;
case Icode_LITERAL_NEW_OBJECT:
// make a copy or not flag
return 1 + 1;
case Icode_LITERAL_NEW_ARRAY:
// skip indexes ID byte
return 1 + 1;
case Icode_REG_BIGINT1:
// ubyte bigint index
return 1 + 1;
case Icode_REG_BIGINT2:
// ushort bigint index
return 1 + 2;
case Icode_REG_BIGINT4:
// uint bigint index
return 1 + 4;
case Icode_OBJECT_REST:
// computedKeyCount byte
return 1 + 1;
}
if (!validBytecode(bytecode)) throw Kit.codeBug();
return 1;
}
static int[] getLineNumbers(JSDescriptor desc) {
JSCode code = desc.getCode();
InterpreterData data;
if (code instanceof InterpreterData) {
data = (InterpreterData) code;
} else {
code = desc.getConstructor();
if (code instanceof InterpreterData) {
data = (InterpreterData) code;
} else {
Kit.codeBug("Attempt to get line number data for non-interpreted code.");
return null;
}
}
HashSet<Integer> presentLines = new HashSet<>();
byte[] iCode = data.itsICode;
int iCodeLength = iCode.length;
for (int pc = 0; pc != iCodeLength; ) {
int bytecode = iCode[pc];
int span = bytecodeSpan(bytecode);
if (bytecode == Icode_LINE) {
if (span != 3) Kit.codeBug();
int line = getIndex(iCode, pc + 1);
presentLines.add(line);
}
pc += span;
}
int[] ret = new int[presentLines.size()];
int i = 0;