-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExecutionContext.java
More file actions
669 lines (568 loc) · 21.5 KB
/
Copy pathExecutionContext.java
File metadata and controls
669 lines (568 loc) · 21.5 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
package cod.interpreter.context;
import cod.ast.node.Type;
import cod.debug.DebugSystem;
import cod.error.InternalError;
import cod.interpreter.handler.TypeHandler;
import java.util.*;
public class ExecutionContext {
public ObjectInstance objectInstance;
public Type currentClass;
public String currentMethodName;
public LambdaClosure currentLambdaClosure;
// Locals with scope stacking
private List<Map<String, Object>> localsStack;
private List<Map<String, String>> localTypesStack;
// Slot values (method return slots) - OPTIMIZED
private Map<String, Object> slotValues;
private Map<String, String> slotTypes;
public Set<String> slotsInCurrentPath;
// Slot access caches for O(1) lookups
private Map<String, Integer> slotIndexMap;
private List<String> slotNamesList;
private List<Object> slotValuesList;
private List<String> slotTypesList;
// Fast path flags
private boolean hasSlots = false;
private boolean slotsOptimized = false;
// ========== THREAD LOCAL CONTEXT ==========
private static final ThreadLocal<ExecutionContext> currentContext = new ThreadLocal<ExecutionContext>();
private static final ThreadLocal<Integer> unsafeCommitDepth = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
// ========== OPTIMIZED LOOP CONTEXT ==========
private boolean inOptimizedLoop = false;
private List<Object> pendingOutputs = new ArrayList<Object>();
private boolean unsafeExecutionContext = false;
private IdentityHashMap<Object, Map<Long, Integer>> activeBorrowsByContainer;
// ========== TYPE HANDLER ==========
private final TypeHandler typeHandler;
/**
* Set the current context for this thread
*/
public static void setCurrentContext(ExecutionContext ctx) {
currentContext.set(ctx);
}
/**
* Get the current context for this thread
*/
public static ExecutionContext getCurrentContext() {
return currentContext.get();
}
/**
* Get the base (root) scope map that contains all variables.
* This is the same map that was passed in from REPLRunner.
*/
public Map<String, Object> getLocalsMap() {
if (localsStack == null || localsStack.isEmpty()) {
return new HashMap<String, Object>();
}
// Return the root scope (index 0) which contains all variables
return localsStack.get(0);
}
/**
* Clear the current context for this thread
*/
public static void clearCurrentContext() {
currentContext.remove();
}
public static void enterUnsafeCommitAllowance() {
unsafeCommitDepth.set(unsafeCommitDepth.get() + 1);
}
public static void exitUnsafeCommitAllowance() {
int current = unsafeCommitDepth.get();
unsafeCommitDepth.set(current > 0 ? current - 1 : 0);
}
public static boolean isUnsafeCommitAllowed() {
return unsafeCommitDepth.get() > 0;
}
/**
* Mark that we're entering an optimized loop
*/
public void enterOptimizedLoop() {
this.inOptimizedLoop = true;
this.pendingOutputs.clear();
}
/**
* Mark that we're exiting an optimized loop
*/
public void exitOptimizedLoop() {
this.inOptimizedLoop = false;
this.pendingOutputs.clear();
}
/**
* Check if we're in an optimized loop
*/
public boolean isInOptimizedLoop() {
return inOptimizedLoop;
}
/**
* Record an output for later playback
*/
public void recordOptimizedOutput(Object value) {
if (inOptimizedLoop) {
pendingOutputs.add(value);
}
}
/**
* Get and clear pending outputs
*/
public List<Object> flushPendingOutputs() {
List<Object> outputs = new ArrayList<Object>(pendingOutputs);
pendingOutputs.clear();
return outputs;
}
public boolean isUnsafeExecutionContext() {
return unsafeExecutionContext;
}
public void setUnsafeExecutionContext(boolean unsafeExecutionContext) {
this.unsafeExecutionContext = unsafeExecutionContext;
}
public ExecutionContext(ObjectInstance obj, Map<String, Object> locals,
Map<String, Object> slotValues, Map<String, String> slotTypes,
TypeHandler typeHandler) {
if (typeHandler == null) {
throw new InternalError("ExecutionContext constructed with null typeHandler");
}
this.objectInstance = obj;
this.currentClass = null;
this.currentMethodName = null;
this.currentLambdaClosure = null;
this.typeHandler = typeHandler;
this.activeBorrowsByContainer = new IdentityHashMap<Object, Map<Long, Integer>>();
// Initialize locals
this.localsStack = new ArrayList<Map<String, Object>>();
this.localTypesStack = new ArrayList<Map<String, String>>();
Map<String, Object> initialLocals = new HashMap<String, Object>();
if (locals != null) {
initialLocals.putAll(locals);
}
this.localsStack.add(initialLocals);
Map<String, String> initialTypes = new HashMap<String, String>();
this.localTypesStack.add(initialTypes);
// OPTIMIZED: Initialize slots with parallel arrays for O(1) access
this.slotValues = slotValues != null ? slotValues : new HashMap<String, Object>();
this.slotTypes = slotTypes != null ? slotTypes : new HashMap<String, String>();
this.slotsInCurrentPath = new HashSet<String>();
// Build optimized slot access structures
optimizeSlotAccess();
registerInitialBorrowState(initialLocals);
}
/**
* Get the type handler
*/
public TypeHandler getTypeHandler() {
return typeHandler;
}
// Build parallel arrays for O(1) slot access
private void optimizeSlotAccess() {
if (slotValues == null || slotValues.isEmpty()) {
this.hasSlots = false;
this.slotsOptimized = false;
return;
}
int size = slotValues.size();
this.slotIndexMap = new HashMap<String, Integer>(size);
this.slotNamesList = new ArrayList<String>(size);
this.slotValuesList = new ArrayList<Object>(size);
this.slotTypesList = new ArrayList<String>(size);
int index = 0;
for (Map.Entry<String, Object> entry : slotValues.entrySet()) {
String name = entry.getKey();
slotIndexMap.put(name, index);
slotNamesList.add(name);
slotValuesList.add(entry.getValue());
slotTypesList.add(slotTypes.get(name));
index++;
}
this.hasSlots = true;
this.slotsOptimized = true;
}
// O(1) slot value get by name
public Object getSlotValue(String slotName) {
if (slotName == null) {
throw new InternalError("getSlotValue called with null slotName");
}
// Fast path - use index map
if (slotsOptimized && slotIndexMap.containsKey(slotName)) {
int index = slotIndexMap.get(slotName);
return slotValuesList.get(index);
}
// Fallback to map
return slotValues.get(slotName);
}
// O(1) slot value set by name
public void setSlotValue(String slotName, Object value) {
if (slotName == null) {
throw new InternalError("setSlotValue called with null slotName");
}
// Update both representations
Object previous = slotValues.put(slotName, value);
replaceTrackedValue(previous, value);
if (slotsOptimized && slotIndexMap.containsKey(slotName)) {
int index = slotIndexMap.get(slotName);
slotValuesList.set(index, value);
}
}
// O(1) slot type get by name
public String getSlotType(String slotName) {
if (slotName == null) {
throw new InternalError("getSlotType called with null slotName");
}
// Fast path - use index map
if (slotsOptimized && slotIndexMap.containsKey(slotName)) {
int index = slotIndexMap.get(slotName);
return slotTypesList.get(index);
}
// Fallback to map
return slotTypes.get(slotName);
}
// O(1) slot exists check
public boolean hasSlot(String slotName) {
if (slotName == null) return false;
if (slotsOptimized) {
return slotIndexMap.containsKey(slotName);
}
return slotValues.containsKey(slotName);
}
// Get slot by index (for iteration)
public String getSlotName(int index) {
if (!slotsOptimized || index < 0 || index >= slotNamesList.size()) {
return null;
}
return slotNamesList.get(index);
}
// Get slot count
public int getSlotCount() {
if (slotsOptimized) {
return slotNamesList.size();
}
return slotValues != null ? slotValues.size() : 0;
}
// Mark slot as assigned in current path
public void markSlotAssigned(String slotName) {
if (slotName == null) return;
slotsInCurrentPath.add(slotName);
}
// Check if all slots are assigned
public boolean allSlotsAssigned() {
if (!hasSlots) return false;
if (slotsInCurrentPath.isEmpty()) return false;
// Fast path - use size check
if (slotsOptimized) {
return slotsInCurrentPath.size() >= slotNamesList.size();
}
// Fallback
for (String slotName : slotValues.keySet()) {
if (!slotsInCurrentPath.contains(slotName)) {
return false;
}
}
return true;
}
public Map<String, Object> getSlotValues() {
return slotValues;
}
public Map<String, String> getSlotTypes() {
return slotTypes;
}
public void pushScope() {
localsStack.add(new HashMap<String, Object>());
localTypesStack.add(new HashMap<String, String>());
}
public void popScope() {
if (localsStack.size() > 1) {
Map<String, Object> removedScope = localsStack.remove(localsStack.size() - 1);
for (Object value : removedScope.values()) {
unregisterBorrowsFromValue(value);
}
localTypesStack.remove(localTypesStack.size() - 1);
}
}
public int getScopeDepth() {
return localsStack.size();
}
public Map<String, Object> getScope(int depth) {
if (depth < 0 || depth >= localsStack.size()) {
return null;
}
return localsStack.get(depth);
}
public List<Map<String, Object>> getLocalsStack() {
return localsStack;
}
public List<Map<String, String>> getLocalTypesStack() {
return localTypesStack;
}
public Object getVariable(String name) {
String timer = startPerfTimer(DebugSystem.Level.TRACE, "executionContext.getVariable");
try {
if (name == null) return null;
// Check locals (from innermost to outermost)
for (int i = localsStack.size() - 1; i >= 0; i--) {
Map<String, Object> scope = localsStack.get(i);
Object value = scope.get(name);
if (value != null || scope.containsKey(name)) {
return value;
}
}
return null;
} finally {
stopPerfTimer(timer);
}
}
public void setVariable(String name, Object value) {
String timer = startPerfTimer(DebugSystem.Level.TRACE, "executionContext.setVariable");
try {
if (name == null) {
throw new InternalError("setVariable called with null name");
}
// Check if variable exists in any scope
for (int i = localsStack.size() - 1; i >= 0; i--) {
Map<String, Object> scope = localsStack.get(i);
if (scope.containsKey(name)) {
Object previous = scope.put(name, value);
replaceTrackedValue(previous, value);
return;
}
}
// Create in current scope
Map<String, Object> currentScope = localsStack.get(localsStack.size() - 1);
Object previous = currentScope.put(name, value);
replaceTrackedValue(previous, value);
} finally {
stopPerfTimer(timer);
}
}
public int resolveVariableScopeIndex(String name) {
if (name == null) return -1;
for (int i = localsStack.size() - 1; i >= 0; i--) {
Map<String, Object> scope = localsStack.get(i);
if (scope.containsKey(name)) {
return i;
}
}
return localsStack.size() - 1;
}
public int resolveVariableTypeScopeIndex(String name) {
if (name == null) return -1;
for (int i = localTypesStack.size() - 1; i >= 0; i--) {
Map<String, String> scope = localTypesStack.get(i);
if (scope.containsKey(name)) {
return i;
}
}
return localTypesStack.size() - 1;
}
public String getVariableTypeAtScope(int scopeIndex, String name) {
if (name == null || scopeIndex < 0 || scopeIndex >= localTypesStack.size()) {
return null;
}
return localTypesStack.get(scopeIndex).get(name);
}
public void setVariableAtScope(int scopeIndex, String name, Object value) {
if (name == null) {
throw new InternalError("setVariableAtScope called with null name");
}
if (scopeIndex < 0 || scopeIndex >= localsStack.size()) {
setVariable(name, value);
return;
}
Map<String, Object> scope = localsStack.get(scopeIndex);
Object previous = scope.put(name, value);
replaceTrackedValue(previous, value);
}
public void setVariableTypeAtScope(int scopeIndex, String name, String type) {
if (name == null) {
throw new InternalError("setVariableTypeAtScope called with null name");
}
if (scopeIndex < 0 || scopeIndex >= localTypesStack.size()) {
setVariableType(name, type);
return;
}
localTypesStack.get(scopeIndex).put(name, type);
}
public String getVariableType(String name) {
if (name == null) return null;
for (int i = localTypesStack.size() - 1; i >= 0; i--) {
Map<String, String> scope = localTypesStack.get(i);
if (scope.containsKey(name)) {
return scope.get(name);
}
}
return null;
}
public void setVariableType(String name, String type) {
if (name == null) {
throw new InternalError("setVariableType called with null name");
}
Map<String, String> currentScope = localTypesStack.get(localTypesStack.size() - 1);
currentScope.put(name, type);
}
public Map<String, Object> locals() {
Map<String, Object> all = new HashMap<String, Object>();
for (Map<String, Object> scope : localsStack) {
all.putAll(scope);
}
return all;
}
/**
* Remove a variable from the current scope
* Returns the removed value, or null if not found
*/
public Object removeVariable(String name) {
if (name == null) return null;
// Check from innermost to outermost scope
for (int i = localsStack.size() - 1; i >= 0; i--) {
Map<String, Object> scope = localsStack.get(i);
if (scope.containsKey(name)) {
Object removed = scope.remove(name);
unregisterBorrowsFromValue(removed);
return removed;
}
}
return null;
}
/**
* Remove a variable from all scopes (for cleanup)
* Returns true if found and removed
*/
public boolean removeVariableFromAllScopes(String name) {
if (name == null) return false;
boolean found = false;
for (int i = localsStack.size() - 1; i >= 0; i--) {
Map<String, Object> scope = localsStack.get(i);
if (scope.containsKey(name)) {
Object removed = scope.remove(name);
unregisterBorrowsFromValue(removed);
found = true;
}
}
return found;
}
public ExecutionContext copyWithVariable(String name, Object value, String type) {
Map<String, Object> newLocals = locals();
newLocals.put(name, value);
Map<String, String> newTypes = new HashMap<String, String>();
for (Map<String, String> scope : localTypesStack) {
newTypes.putAll(scope);
}
if (type != null) {
newTypes.put(name, type);
}
return new ExecutionContext(objectInstance, newLocals, slotValues, slotTypes, typeHandler);
}
public void setObjectField(String fieldName, Object value) {
if (fieldName == null) {
throw new InternalError("setObjectField called with null fieldName");
}
if (objectInstance == null || objectInstance.fields == null) {
throw new InternalError("setObjectField called outside object context");
}
Object previous = objectInstance.fields.put(fieldName, value);
replaceTrackedValue(previous, value);
}
public boolean hasActiveBorrow(Object container, long index) {
if (container == null) return false;
Map<Long, Integer> countsByIndex = activeBorrowsByContainer.get(container);
if (countsByIndex == null) return false;
Integer count = countsByIndex.get(index);
return count != null && count > 0;
}
public void trackValueReplacement(Object oldValue, Object newValue) {
replaceTrackedValue(oldValue, newValue);
}
// Clear slot optimization (if slots change)
public void rebuildSlotOptimization() {
this.slotsOptimized = false;
this.slotIndexMap = null;
this.slotNamesList = null;
this.slotValuesList = null;
this.slotTypesList = null;
optimizeSlotAccess();
}
private void registerInitialBorrowState(Map<String, Object> initialLocals) {
if (initialLocals != null) {
for (Object value : initialLocals.values()) {
registerBorrowsFromValue(value);
}
}
if (slotValues != null) {
for (Object value : slotValues.values()) {
registerBorrowsFromValue(value);
}
}
if (objectInstance != null && objectInstance.fields != null) {
for (Object value : objectInstance.fields.values()) {
registerBorrowsFromValue(value);
}
}
}
private void replaceTrackedValue(Object oldValue, Object newValue) {
unregisterBorrowsFromValue(oldValue);
registerBorrowsFromValue(newValue);
}
private void registerBorrowsFromValue(Object value) {
collectBorrowsRecursive(value, 1);
}
private void unregisterBorrowsFromValue(Object value) {
collectBorrowsRecursive(value, -1);
}
@SuppressWarnings("unchecked")
private void collectBorrowsRecursive(Object value, int delta) {
if (value == null) return;
Object unwrapped = typeHandler.unwrap(value);
if (unwrapped == null) return;
if (unwrapped instanceof TypeHandler.PointerValue) {
TypeHandler.PointerValue pointer = (TypeHandler.PointerValue) unwrapped;
updateBorrowCount(pointer.container, pointer.index, delta);
return;
}
if (unwrapped instanceof List) {
String listClassName = unwrapped.getClass().getName();
if (!listClassName.startsWith("java.util.")) {
return;
}
for (Object element : (List<Object>) unwrapped) {
collectBorrowsRecursive(element, delta);
}
}
}
private void updateBorrowCount(Object container, long index, int delta) {
if (container == null || delta == 0) return;
Map<Long, Integer> countsByIndex = activeBorrowsByContainer.get(container);
if (countsByIndex == null) {
if (delta < 0) return;
countsByIndex = new HashMap<Long, Integer>();
activeBorrowsByContainer.put(container, countsByIndex);
}
Integer current = countsByIndex.get(index);
int next = (current != null ? current : 0) + delta;
if (next > 0) {
countsByIndex.put(index, next);
} else {
countsByIndex.remove(index);
if (countsByIndex.isEmpty()) {
activeBorrowsByContainer.remove(container);
}
}
}
private static boolean isTimerEnabled(DebugSystem.Level level) {
DebugSystem.Level current = DebugSystem.getLevel();
return current != DebugSystem.Level.OFF && current.getLevel() >= level.getLevel();
}
private static String startPerfTimer(DebugSystem.Level level, String operation) {
if (!isTimerEnabled(level)) {
return null;
}
DebugSystem.startTimer(level, operation);
return operation;
}
private static void stopPerfTimer(String timerName) {
if (timerName != null) {
DebugSystem.stopTimer(timerName);
}
}
}