-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRuntimeCode.java
More file actions
1772 lines (1569 loc) · 82 KB
/
RuntimeCode.java
File metadata and controls
1772 lines (1569 loc) · 82 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
package org.perlonjava.runtime;
import org.perlonjava.CompilerOptions;
import org.perlonjava.astnode.Node;
import org.perlonjava.astnode.OperatorNode;
import org.perlonjava.codegen.EmitterContext;
import org.perlonjava.codegen.EmitterMethodCreator;
import org.perlonjava.codegen.JavaClassInfo;
import org.perlonjava.lexer.Lexer;
import org.perlonjava.lexer.LexerToken;
import org.perlonjava.operators.WarnDie;
import org.perlonjava.parser.Parser;
import org.perlonjava.mro.InheritanceResolver;
import org.perlonjava.operators.ModuleOperators;
import org.perlonjava.scriptengine.PerlLanguageProvider;
import org.perlonjava.symbols.ScopedSymbolTable;
import org.perlonjava.symbols.SymbolTable;
import org.perlonjava.interpreter.BytecodeCompiler;
import org.perlonjava.interpreter.InterpretedCode;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Supplier;
import static org.perlonjava.Configuration.getPerlVersionNoV;
import static org.perlonjava.parser.ParserTables.CORE_PROTOTYPES;
import static org.perlonjava.runtime.GlobalVariable.*;
import static org.perlonjava.runtime.RuntimeScalarCache.scalarUndef;
import static org.perlonjava.runtime.RuntimeScalarType.*;
import static org.perlonjava.runtime.SpecialBlock.runEndBlocks;
import static org.perlonjava.parser.SpecialBlockParser.setCurrentScope;
import static org.perlonjava.runtime.SpecialBlock.runUnitcheckBlocks;
/**
* The RuntimeCode class represents a compiled code object in the runtime environment.
* It provides functionality to compile, store, and execute Perl subroutines and eval strings.
*/
public class RuntimeCode extends RuntimeBase implements RuntimeScalarReference {
// Lookup object for performing method handle operations
public static final MethodHandles.Lookup lookup = MethodHandles.lookup();
/**
* Flag to control whether eval STRING should use the interpreter backend.
* When set, eval STRING compiles to InterpretedCode instead of generating JVM bytecode.
* This provides 46x faster compilation for workloads with many unique eval strings.
*
* Set environment variable JPERL_EVAL_USE_INTERPRETER=1 to enable.
*/
public static final boolean EVAL_USE_INTERPRETER =
System.getenv("JPERL_EVAL_USE_INTERPRETER") != null;
/**
* Flag to control whether eval compilation errors should be printed to stderr.
* By default, eval failures are silent (errors only stored in $@).
*
* Set environment variable JPERL_EVAL_VERBOSE=1 to enable verbose error reporting.
* This is useful for debugging eval compilation issues, especially when testing
* the interpreter path.
*/
public static final boolean EVAL_VERBOSE =
System.getenv("JPERL_EVAL_VERBOSE") != null;
/**
* ThreadLocal storage for runtime values of captured variables during eval STRING compilation.
*
* PROBLEM: In perl5, BEGIN blocks inside eval STRING can access outer lexical variables' runtime values:
* my @imports = qw(a b);
* eval q{ BEGIN { say @imports } }; # perl5 prints: a b
*
* In PerlOnJava, BEGIN blocks execute during parsing (before the eval class is instantiated),
* so they couldn't access runtime values - they would see empty variables.
*
* SOLUTION: When evalStringHelper() is called, the runtime values are stored in this ThreadLocal.
* During parsing, when SpecialBlockParser sets up BEGIN blocks, it can access these runtime values
* and use them to initialize the special globals that lexical variables become in BEGIN blocks.
*
* This ThreadLocal stores:
* - Key: The evalTag identifying this eval compilation
* - Value: EvalRuntimeContext containing:
* - runtimeValues: Object[] of captured variable values
* - capturedEnv: String[] of captured variable names (matching array indices)
*
* Thread-safety: Each thread's eval compilation uses its own ThreadLocal storage, so parallel
* eval compilations don't interfere with each other.
*/
private static final ThreadLocal<EvalRuntimeContext> evalRuntimeContext = new ThreadLocal<>();
/**
* Container for runtime context during eval STRING compilation.
* Holds both the runtime values and variable names so SpecialBlockParser can
* match variables to their values.
*/
public static class EvalRuntimeContext {
public final Object[] runtimeValues;
public final String[] capturedEnv;
public final String evalTag;
public EvalRuntimeContext(Object[] runtimeValues, String[] capturedEnv, String evalTag) {
this.runtimeValues = runtimeValues;
this.capturedEnv = capturedEnv;
this.evalTag = evalTag;
}
/**
* Get the runtime value for a variable by name.
*
* IMPORTANT: The capturedEnv array includes all variables (including 'this', '@_', 'wantarray'),
* but runtimeValues array skips the first skipVariables (currently 3).
* So if @imports is at capturedEnv[5], its value is at runtimeValues[5-3=2].
*
* @param varName The variable name (e.g., "@imports", "$scalar")
* @return The runtime value, or null if not found
*/
public Object getRuntimeValue(String varName) {
int skipVariables = 3; // 'this', '@_', 'wantarray'
for (int i = skipVariables; i < capturedEnv.length; i++) {
if (varName.equals(capturedEnv[i])) {
int runtimeIndex = i - skipVariables;
if (runtimeIndex >= 0 && runtimeIndex < runtimeValues.length) {
return runtimeValues[runtimeIndex];
}
}
}
return null;
}
}
/**
* Get the current eval runtime context for accessing variable runtime values during parsing.
* This is called by SpecialBlockParser when setting up BEGIN blocks.
*
* @return The current eval runtime context, or null if not in eval STRING compilation
*/
public static EvalRuntimeContext getEvalRuntimeContext() {
return evalRuntimeContext.get();
}
// Cache for memoization of evalStringHelper results
private static final int CLASS_CACHE_SIZE = 100;
private static final Map<String, Class<?>> evalCache = new LinkedHashMap<String, Class<?>>(CLASS_CACHE_SIZE, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Class<?>> eldest) {
return size() > CLASS_CACHE_SIZE;
}
};
// Cache for method handles with eviction policy
private static final int METHOD_HANDLE_CACHE_SIZE = 100;
private static final Map<Class<?>, MethodHandle> methodHandleCache = new LinkedHashMap<Class<?>, MethodHandle>(METHOD_HANDLE_CACHE_SIZE, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Class<?>, MethodHandle> eldest) {
return size() > METHOD_HANDLE_CACHE_SIZE;
}
};
public static MethodType methodType = MethodType.methodType(RuntimeList.class, RuntimeArray.class, int.class);
// Temporary storage for anonymous subroutines and eval string compiler context
public static HashMap<String, Class<?>> anonSubs = new HashMap<>(); // temp storage for makeCodeObject()
public static HashMap<String, EmitterContext> evalContext = new HashMap<>(); // storage for eval string compiler context
// Runtime eval counter for generating unique filenames when $^P is set
private static int runtimeEvalCounter = 1;
// Method object representing the compiled subroutine
public MethodHandle methodHandle;
public boolean isStatic;
public String autoloadVariableName = null;
// Code object instance used during execution
public Object codeObject;
// Prototype of the subroutine
public String prototype;
// Attributes associated with the subroutine
public List<String> attributes = new ArrayList<>();
// Method context information for next::method support
public String packageName;
public String subName;
// Source package for imported forward declarations (used for AUTOLOAD resolution)
public String sourcePackage = null;
// Flag to indicate this is a symbolic reference created by \&{string} that should always be "defined"
public boolean isSymbolicReference = false;
// Flag to indicate this is a built-in operator
public boolean isBuiltin = false;
// State variables
public Map<String, Boolean> stateVariableInitialized = new HashMap<>();
public Map<String, RuntimeScalar> stateVariable = new HashMap<>();
public Map<String, RuntimeArray> stateArray = new HashMap<>();
public Map<String, RuntimeHash> stateHash = new HashMap<>();
public RuntimeList constantValue;
// Field to hold the thread compiling this code
public Supplier<Void> compilerSupplier;
/**
* Constructs a RuntimeCode instance with the specified prototype and attributes.
*
* @param prototype the prototype of the subroutine
* @param attributes the attributes associated with the subroutine
*/
public RuntimeCode(String prototype, List<String> attributes) {
this.prototype = prototype;
this.attributes = attributes;
}
public RuntimeCode(MethodHandle methodObject, Object codeObject, String prototype) {
this.methodHandle = methodObject;
this.codeObject = codeObject;
this.prototype = prototype;
}
// Add a method to clear caches when globals are reset
public static void clearCaches() {
evalCache.clear();
methodHandleCache.clear();
anonSubs.clear();
evalContext.clear();
evalRuntimeContext.remove();
}
public static void copy(RuntimeCode code, RuntimeCode codeFrom) {
code.prototype = codeFrom.prototype;
code.attributes = codeFrom.attributes;
code.methodHandle = codeFrom.methodHandle;
code.isStatic = codeFrom.isStatic;
code.codeObject = codeFrom.codeObject;
}
/**
* Backwards-compatible overload for code compiled before runtimeValues parameter was added.
* This allows pre-compiled Perl modules to continue working with the new signature.
*
* @param code the RuntimeScalar containing the eval string
* @param evalTag the tag used to retrieve the eval context
* @return the compiled Class representing the anonymous subroutine
* @throws Exception if an error occurs during compilation
*/
public static Class<?> evalStringHelper(RuntimeScalar code, String evalTag) throws Exception {
return evalStringHelper(code, evalTag, new Object[0]);
}
/**
* Compiles the text of an eval string into a Class that represents an anonymous subroutine.
* After the Class is returned to the caller, an instance of the Class will be populated
* with closure variables, and then makeCodeObject() will be called to transform the Class
* instance into a Perl CODE object.
*
* IMPORTANT CHANGE: This method now accepts runtime values of captured variables.
*
* WHY THIS IS NEEDED:
* In perl5, BEGIN blocks inside eval STRING can access outer lexical variables' runtime values.
* For example:
* my @imports = qw(md5 md5_hex);
* eval q{ use Digest::MD5 @imports }; # BEGIN block sees @imports = (md5 md5_hex)
*
* Previously in PerlOnJava, BEGIN blocks would see empty variables because they execute
* during parsing, before the eval class is instantiated with runtime values.
*
* NOW: We pass runtime values to this method and store them in ThreadLocal storage.
* SpecialBlockParser can then access these values when setting up BEGIN blocks,
* allowing lexical variables to be initialized with their runtime values.
*
* @param code the RuntimeScalar containing the eval string
* @param evalTag the tag used to retrieve the eval context
* @param runtimeValues the runtime values of captured variables (Object[] matching capturedEnv order)
* @return the compiled Class representing the anonymous subroutine
* @throws Exception if an error occurs during compilation
*/
public static Class<?> evalStringHelper(RuntimeScalar code, String evalTag, Object[] runtimeValues) throws Exception {
// Retrieve the eval context that was saved at program compile-time
EmitterContext ctx = RuntimeCode.evalContext.get(evalTag);
// Store runtime values in ThreadLocal so SpecialBlockParser can access them during parsing.
// This enables BEGIN blocks to see outer lexical variables' runtime values.
//
// CRITICAL: The runtimeValues array matches capturedEnv order (both skip first 3 variables).
// SpecialBlockParser will use getRuntimeValue() to look up values by variable name.
//
// Example: If @imports is at capturedEnv[5], its runtime value is at runtimeValues[5-3=2]
// (because both arrays skip 'this', '@_', and 'wantarray')
EvalRuntimeContext runtimeCtx = new EvalRuntimeContext(
runtimeValues,
ctx.capturedEnv, // Variable names in same order as runtimeValues
evalTag
);
evalRuntimeContext.set(runtimeCtx);
try {
// Check if the eval string contains non-ASCII characters
// If so, treat it as Unicode source to preserve Unicode characters during parsing
// EXCEPT for evalbytes, which must treat everything as bytes
String evalString = code.toString();
boolean hasUnicode = false;
if (!ctx.isEvalbytes && code.type != RuntimeScalarType.BYTE_STRING) {
for (int i = 0; i < evalString.length(); i++) {
if (evalString.charAt(i) > 127) {
hasUnicode = true;
break;
}
}
}
// Clone compiler options and set isUnicodeSource if needed
// This only affects string parsing, not symbol table or method resolution
CompilerOptions evalCompilerOptions = ctx.compilerOptions;
// The eval string can originate from either a Perl STRING or BYTE_STRING scalar.
// For BYTE_STRING source we must treat the source as raw bytes (latin-1-ish) and
// NOT re-encode characters to UTF-8 when simulating 'non-unicode source'.
boolean isByteStringSource = !ctx.isEvalbytes && code.type == RuntimeScalarType.BYTE_STRING;
if (hasUnicode || ctx.isEvalbytes || isByteStringSource) {
evalCompilerOptions = (CompilerOptions) ctx.compilerOptions.clone();
if (hasUnicode) {
evalCompilerOptions.isUnicodeSource = true;
}
if (ctx.isEvalbytes) {
evalCompilerOptions.isEvalbytes = true;
}
if (isByteStringSource) {
evalCompilerOptions.isByteStringSource = true;
}
}
// Check $^P to determine if we should use caching
// When debugging is enabled, we want each eval to get a unique filename
int debugFlags = GlobalVariable.getGlobalVariable(GlobalContext.encodeSpecialVar("P")).getInt();
boolean isDebugging = debugFlags != 0;
// Override the filename with a runtime-generated eval number when debugging
String actualFileName = evalCompilerOptions.fileName;
if (isDebugging) {
synchronized (RuntimeCode.class) {
actualFileName = "(eval " + runtimeEvalCounter++ + ")";
}
}
// Check if the result is already cached (include hasUnicode, isEvalbytes, byte-string-source, and feature flags in cache key)
// Skip caching when $^P is set, so each eval gets a unique filename
int featureFlags = ctx.symbolTable.featureFlagsStack.peek();
String cacheKey = code.toString() + '\0' + evalTag + '\0' + hasUnicode + '\0' + ctx.isEvalbytes + '\0' + isByteStringSource + '\0' + featureFlags;
Class<?> cachedClass = null;
if (!isDebugging) {
synchronized (evalCache) {
if (evalCache.containsKey(cacheKey)) {
cachedClass = evalCache.get(cacheKey);
}
}
if (cachedClass != null) {
return cachedClass;
}
}
// IMPORTANT: The eval call site (EmitEval) computes the constructor signature from
// ctx.symbolTable (captured at compile-time). We must use that exact symbol table for
// codegen, otherwise the generated <init>(...) descriptor may not match what the
// call site is looking up via reflection.
ScopedSymbolTable capturedSymbolTable = ctx.symbolTable;
// eval may include lexical pragmas (use strict/warnings/features). We need those flags
// during codegen of the eval body, but they must NOT leak back into the caller scope.
BitSet savedWarningFlags = (BitSet) capturedSymbolTable.warningFlagsStack.peek().clone();
int savedFeatureFlags = capturedSymbolTable.featureFlagsStack.peek();
int savedStrictOptions = capturedSymbolTable.strictOptionsStack.peek();
// Parse using a mutable clone so lexical declarations inside the eval do not
// change the captured environment / constructor signature.
// IMPORTANT: The parseSymbolTable starts with the captured flags so that
// the eval code is parsed with the correct feature/strict/warning context
ScopedSymbolTable parseSymbolTable = capturedSymbolTable.snapShot();
// CRITICAL: Pre-create aliases for captured variables BEFORE parsing
// This allows BEGIN blocks in the eval string to access outer lexical variables.
//
// When the eval string is parsed, variable references in BEGIN blocks will be
// resolved to these special package globals that we're aliasing now.
//
// Example: my @arr = qw(a b); eval q{ BEGIN { say @arr } };
// We create: globalArrays["BEGIN_PKG_x::@arr"] = (the runtime @arr object)
// Then when "say @arr" is parsed in the BEGIN, it resolves to BEGIN_PKG_x::@arr
// which is aliased to the runtime array with values (a, b).
Map<Integer, SymbolTable.SymbolEntry> capturedVars = capturedSymbolTable.getAllVisibleVariables();
for (SymbolTable.SymbolEntry entry : capturedVars.values()) {
if (!entry.name().equals("@_") && !entry.decl().isEmpty() && !entry.name().startsWith("&")) {
if (!entry.decl().equals("our")) {
// "my" or "state" variables get special BEGIN package globals
Object runtimeValue = runtimeCtx.getRuntimeValue(entry.name());
if (runtimeValue != null) {
// Get or create the special package ID
// IMPORTANT: We need to set the ID NOW (before parsing) so that when
// runSpecialBlock is called during parsing, it uses the SAME ID
OperatorNode ast = entry.ast();
if (ast != null) {
if (ast.id == 0) {
ast.id = EmitterMethodCreator.classCounter++;
}
String packageName = PersistentVariable.beginPackage(ast.id);
// IMPORTANT: Global variable keys do NOT include the sigil
// entry.name() is "@arr" but the key should be "packageName::arr"
String varNameWithoutSigil = entry.name().substring(1); // Remove the sigil
String fullName = packageName + "::" + varNameWithoutSigil;
// Alias the global to the runtime value
if (runtimeValue instanceof RuntimeArray) {
GlobalVariable.globalArrays.put(fullName, (RuntimeArray) runtimeValue);
} else if (runtimeValue instanceof RuntimeHash) {
GlobalVariable.globalHashes.put(fullName, (RuntimeHash) runtimeValue);
} else if (runtimeValue instanceof RuntimeScalar) {
GlobalVariable.globalVariables.put(fullName, (RuntimeScalar) runtimeValue);
}
}
}
}
}
}
EmitterContext evalCtx = new EmitterContext(
new JavaClassInfo(), // internal java class name
parseSymbolTable, // symbolTable
null, // method visitor
null, // class writer
ctx.contextType, // call context
true, // is boxed
ctx.errorUtil, // error message utility
evalCompilerOptions, // possibly modified for Unicode source
ctx.unitcheckBlocks);
// evalCtx.logDebug("evalStringHelper EmitterContext: " + evalCtx);
// evalCtx.logDebug("evalStringHelper Code: " + code);
// Process the string source code to create the LexerToken list
Lexer lexer = new Lexer(evalString);
List<LexerToken> tokens = lexer.tokenize(); // Tokenize the Perl code
Node ast = null;
Class<?> generatedClass;
try {
// Create the AST
// Create an instance of ErrorMessageUtil with the file name and token list
evalCtx.errorUtil = new ErrorMessageUtil(evalCtx.compilerOptions.fileName, tokens);
Parser parser = new Parser(evalCtx, tokens); // Parse the tokens
ast = parser.parse(); // Generate the abstract syntax tree (AST)
// ast = ConstantFoldingVisitor.foldConstants(ast);
// Create a new instance of ErrorMessageUtil, resetting the line counter
evalCtx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
ScopedSymbolTable postParseSymbolTable = evalCtx.symbolTable;
evalCtx.symbolTable = capturedSymbolTable;
evalCtx.symbolTable.copyFlagsFrom(postParseSymbolTable);
setCurrentScope(evalCtx.symbolTable);
// Use the captured environment array from compile-time to ensure
// constructor signature matches what EmitEval generated bytecode for
if (ctx.capturedEnv != null) {
evalCtx.capturedEnv = ctx.capturedEnv;
}
generatedClass = EmitterMethodCreator.createClassWithMethod(
evalCtx,
ast,
false // use try-catch
);
runUnitcheckBlocks(ctx.unitcheckBlocks);
} catch (Throwable e) {
// Compilation error in eval-string
// Set the global error variable "$@"
RuntimeScalar err = GlobalVariable.getGlobalVariable("main::@");
err.set(e.getMessage());
// If EVAL_VERBOSE is set, print the error to stderr for debugging
if (EVAL_VERBOSE) {
System.err.println("eval compilation error: " + e.getMessage());
if (e.getCause() != null) {
System.err.println("Caused by: " + e.getCause().getMessage());
}
}
// Check if $SIG{__DIE__} handler is defined
RuntimeScalar sig = GlobalVariable.getGlobalHash("main::SIG").get("__DIE__");
if (sig.getDefinedBoolean()) {
// Call the $SIG{__DIE__} handler (similar to what die() does)
RuntimeScalar sigHandler = new RuntimeScalar(sig);
// Undefine $SIG{__DIE__} before calling to avoid infinite recursion
int level = DynamicVariableManager.getLocalLevel();
DynamicVariableManager.pushLocalVariable(sig);
try {
RuntimeArray args = new RuntimeArray();
RuntimeArray.push(args, new RuntimeScalar(err));
apply(sigHandler, args, RuntimeContextType.SCALAR);
} catch (Throwable handlerException) {
// If the handler dies, use its payload as the new error
if (handlerException instanceof RuntimeException && handlerException.getCause() instanceof PerlDieException) {
PerlDieException pde = (PerlDieException) handlerException.getCause();
RuntimeBase handlerPayload = pde.getPayload();
if (handlerPayload != null) {
err.set(handlerPayload.getFirst());
}
} else if (handlerException instanceof PerlDieException) {
PerlDieException pde = (PerlDieException) handlerException;
RuntimeBase handlerPayload = pde.getPayload();
if (handlerPayload != null) {
err.set(handlerPayload.getFirst());
}
}
// If handler throws other exceptions, ignore them (keep original error in $@)
} finally {
// Restore $SIG{__DIE__}
DynamicVariableManager.popToLocalLevel(level);
}
}
// Return null to signal compilation failure (don't throw exception)
// This prevents the exception from escaping to outer eval blocks
return null;
} finally {
// Restore caller lexical flags (do not leak eval pragmas).
capturedSymbolTable.warningFlagsStack.pop();
capturedSymbolTable.warningFlagsStack.push((BitSet) savedWarningFlags.clone());
capturedSymbolTable.featureFlagsStack.pop();
capturedSymbolTable.featureFlagsStack.push(savedFeatureFlags);
capturedSymbolTable.strictOptionsStack.pop();
capturedSymbolTable.strictOptionsStack.push(savedStrictOptions);
setCurrentScope(capturedSymbolTable);
// Store source lines in symbol table if $^P flags are set
// Do this on both success and failure paths when flags require retention
// Use the original evalString and actualFileName; AST may be null on failure
storeSourceLines(evalString, actualFileName, ast, tokens);
}
// Cache the result (unless debugging is enabled)
if (!isDebugging) {
synchronized (evalCache) {
evalCache.put(cacheKey, generatedClass);
}
}
return generatedClass;
} finally {
// Clean up ThreadLocal to prevent memory leaks
// IMPORTANT: Always clean up ThreadLocal in finally block to ensure it's removed
// even if compilation fails. Failure to do so could cause memory leaks in
// long-running applications with thread pools.
evalRuntimeContext.remove();
}
}
/**
* Stores source lines in the symbol table for debugger support when $^P flags are set.
*
* @param evalString The source code string to store
* @param filename The filename (e.g., "(eval 1)")
* @param ast The AST to check for subroutine definitions (may be null on compilation failure)
* @param tokens Lexer tokens for #line directive processing
*/
private static void storeSourceLines(String evalString, String filename, Node ast, List<LexerToken> tokens) {
// Check $^P for debugger flags
int debugFlags = GlobalVariable.getGlobalVariable(GlobalContext.encodeSpecialVar("P")).getInt();
// 0x02 (2): Line-by-line debugging (also saves source like 0x400)
// 0x400 (1024): Save source code lines
// 0x800 (2048): Include evals that generate no subroutines
// 0x1000 (4096): Include source that did not compile
boolean shouldSaveSource = (debugFlags & 0x02) != 0 || (debugFlags & 0x400) != 0;
boolean saveWithoutSubs = (debugFlags & 0x800) != 0;
if (shouldSaveSource) {
// Note: We can't reliably detect subroutine definitions from the AST because
// subroutines are processed at parse-time and removed from the AST.
// Use a simple heuristic: check if the eval string contains "sub " followed by
// an identifier or block.
boolean definesSubs = evalString.matches("(?s).*\\bsub\\s+(?:\\w+|\\{).*");
// Only save if either:
// - The eval defines subroutines, OR
// - The 0x800 flag is set (save evals without subs)
if (!definesSubs && !saveWithoutSubs) {
return; // Skip this eval
}
// Store in the symbol table as @{"_<(eval N)"}
String symbolKey = "_<" + filename;
// Split the eval string into lines (without including trailing empty strings)
String[] lines = evalString.split("\n");
// Create the array with the format expected by the debugger:
// [0] = undef, [1..n] = lines with \n, [n+1] = \n, [n+2] = ;
String arrayKey = "main::" + symbolKey;
RuntimeArray sourceArray = GlobalVariable.getGlobalArray(arrayKey);
sourceArray.elements.clear();
// Index 0: undef
sourceArray.elements.add(RuntimeScalarCache.scalarUndef);
// Indexes 1..n: each line with "\n" appended
for (String line : lines) {
sourceArray.elements.add(new RuntimeScalar(line + "\n"));
}
// Index n+1: "\n"
sourceArray.elements.add(new RuntimeScalar("\n"));
// Index n+2: ";"
sourceArray.elements.add(new RuntimeScalar(";"));
// Process #line directives to populate @{"_<filename"} arrays
processLineDirectives(evalString, lines, tokens);
}
}
/**
* Process #line directives in the eval string to populate @{"_<filename"} arrays.
* This implements the debugger behavior where #line N "file" causes subsequent
* source lines to be stored in @{"_<file"} at index N.
*
* @param evalString The full eval source string
* @param lines The split lines of the eval string
* @param tokens Lexer tokens (may be null on compilation failure)
*/
private static void processLineDirectives(String evalString, String[] lines, List<LexerToken> tokens) {
String currentFilename = null;
int currentLineOffset = 0; // 0-based index into lines array
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// Simple #line directive parsing: #line N "filename"
// Allow optional leading whitespace
java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\s*#line\\s+(\\d+)\\s+\"([^\"]+)\"").matcher(line);
if (m.find()) {
int targetLine = Integer.parseInt(m.group(1)); // 1-based line number in target file
currentFilename = m.group(2);
currentLineOffset = i + 1; // Next line in eval corresponds to targetLine
// Ensure the target array exists and is properly sized
String targetKey = "main::_<" + currentFilename;
RuntimeArray targetArray = GlobalVariable.getGlobalArray(targetKey);
// Ensure array is large enough (sparse behavior)
while (targetArray.elements.size() <= targetLine) {
targetArray.elements.add(RuntimeScalarCache.scalarUndef);
}
// Place the next line at the correct index
if (i + 1 < lines.length) {
targetArray.elements.set(targetLine, new RuntimeScalar(lines[i + 1] + "\n"));
}
} else if (currentFilename != null && i >= currentLineOffset) {
// Continue populating the current filename array
int targetLine = (i - currentLineOffset) + 1; // Convert to 1-based
String targetKey = "main::_<" + currentFilename;
RuntimeArray targetArray = GlobalVariable.getGlobalArray(targetKey);
// Ensure array is large enough (sparse behavior)
while (targetArray.elements.size() <= targetLine) {
targetArray.elements.add(RuntimeScalarCache.scalarUndef);
}
targetArray.elements.set(targetLine, new RuntimeScalar(line + "\n"));
}
}
}
/**
* Execute eval STRING using the interpreter backend for faster compilation.
* This method parses the eval string and compiles it to InterpretedCode instead
* of generating JVM bytecode, which is 46x faster for workloads with many unique eval strings.
*
* @param code The RuntimeScalar containing the eval string
* @param evalTag The unique identifier for this eval site
* @param runtimeValues The captured variable values from the outer scope
* @param args The @_ arguments to pass to the eval
* @param callContext The calling context (SCALAR/LIST/VOID)
* @return The result of executing the eval as a RuntimeList
* @throws Throwable if compilation or execution fails
*/
public static RuntimeList evalStringWithInterpreter(
RuntimeScalar code,
String evalTag,
Object[] runtimeValues,
RuntimeArray args,
int callContext) throws Throwable {
// Retrieve the eval context that was saved at program compile-time
EmitterContext ctx = RuntimeCode.evalContext.get(evalTag);
// Store runtime values in ThreadLocal for BEGIN block support
EvalRuntimeContext runtimeCtx = new EvalRuntimeContext(
runtimeValues,
ctx.capturedEnv,
evalTag
);
evalRuntimeContext.set(runtimeCtx);
InterpretedCode interpretedCode = null;
RuntimeList result;
// Save dynamic variable level to restore after eval
int dynamicVarLevel = DynamicVariableManager.getLocalLevel();
try {
String evalString = code.toString();
// Handle Unicode source detection (same logic as evalStringHelper)
boolean hasUnicode = false;
if (!ctx.isEvalbytes && code.type != RuntimeScalarType.BYTE_STRING) {
for (int i = 0; i < evalString.length(); i++) {
if (evalString.charAt(i) > 127) {
hasUnicode = true;
break;
}
}
}
// Clone compiler options if needed
CompilerOptions evalCompilerOptions = ctx.compilerOptions;
boolean isByteStringSource = !ctx.isEvalbytes && code.type == RuntimeScalarType.BYTE_STRING;
if (hasUnicode || ctx.isEvalbytes || isByteStringSource) {
evalCompilerOptions = (CompilerOptions) ctx.compilerOptions.clone();
if (hasUnicode) {
evalCompilerOptions.isUnicodeSource = true;
}
if (ctx.isEvalbytes) {
evalCompilerOptions.isEvalbytes = true;
}
if (isByteStringSource) {
evalCompilerOptions.isByteStringSource = true;
}
}
// Setup for BEGIN block support - create aliases for captured variables
ScopedSymbolTable capturedSymbolTable = ctx.symbolTable;
Map<Integer, SymbolTable.SymbolEntry> capturedVars = capturedSymbolTable.getAllVisibleVariables();
for (SymbolTable.SymbolEntry entry : capturedVars.values()) {
if (!entry.name().equals("@_") && !entry.decl().isEmpty() && !entry.name().startsWith("&")) {
if (!entry.decl().equals("our")) {
Object runtimeValue = runtimeCtx.getRuntimeValue(entry.name());
if (runtimeValue != null) {
OperatorNode ast = entry.ast();
if (ast != null) {
if (ast.id == 0) {
ast.id = EmitterMethodCreator.classCounter++;
}
String packageName = PersistentVariable.beginPackage(ast.id);
String varNameWithoutSigil = entry.name().substring(1);
String fullName = packageName + "::" + varNameWithoutSigil;
if (runtimeValue instanceof RuntimeArray) {
GlobalVariable.globalArrays.put(fullName, (RuntimeArray) runtimeValue);
} else if (runtimeValue instanceof RuntimeHash) {
GlobalVariable.globalHashes.put(fullName, (RuntimeHash) runtimeValue);
} else if (runtimeValue instanceof RuntimeScalar) {
GlobalVariable.globalVariables.put(fullName, (RuntimeScalar) runtimeValue);
}
}
}
}
}
}
try {
// Parse the eval string
Lexer lexer = new Lexer(evalString);
List<LexerToken> tokens = lexer.tokenize();
// Create parser context
ScopedSymbolTable parseSymbolTable = capturedSymbolTable.snapShot();
EmitterContext evalCtx = new EmitterContext(
new JavaClassInfo(),
parseSymbolTable,
null,
null,
callContext, // Use the runtime calling context, not the saved one!
true,
new ErrorMessageUtil(evalCompilerOptions.fileName, tokens),
evalCompilerOptions,
ctx.unitcheckBlocks);
Parser parser = new Parser(evalCtx, tokens);
Node ast = parser.parse();
// Run UNITCHECK blocks
runUnitcheckBlocks(evalCtx.unitcheckBlocks);
// Build adjusted registry for captured variables
// Map variable names to register indices (3+ for captured variables)
Map<String, Integer> adjustedRegistry = new HashMap<>();
adjustedRegistry.put("this", 0);
adjustedRegistry.put("@_", 1);
adjustedRegistry.put("wantarray", 2);
// Add captured variables starting at register 3
int captureIndex = 3;
Map<Integer, SymbolTable.SymbolEntry> capturedVariables = capturedSymbolTable.getAllVisibleVariables();
for (Map.Entry<Integer, SymbolTable.SymbolEntry> entry : capturedVariables.entrySet()) {
int index = entry.getKey();
if (index >= 3) { // Skip reserved registers
String varName = entry.getValue().name();
adjustedRegistry.put(varName, captureIndex);
captureIndex++;
}
}
// Compile to InterpretedCode with variable registry
BytecodeCompiler compiler = new BytecodeCompiler(
evalCompilerOptions.fileName,
1,
evalCtx.errorUtil,
adjustedRegistry);
interpretedCode = compiler.compile(ast, evalCtx);
// Set captured variables
if (runtimeValues.length > 0) {
RuntimeBase[] capturedVars2 = new RuntimeBase[runtimeValues.length];
for (int i = 0; i < runtimeValues.length; i++) {
capturedVars2[i] = (RuntimeBase) runtimeValues[i];
}
interpretedCode = interpretedCode.withCapturedVars(capturedVars2);
}
} catch (Throwable e) {
// Compilation error in eval-string
// Set the global error variable "$@"
RuntimeScalar err = GlobalVariable.getGlobalVariable("main::@");
err.set(e.getMessage());
// If EVAL_VERBOSE is set, print the error to stderr for debugging
if (EVAL_VERBOSE) {
System.err.println("eval compilation error: " + e.getMessage());
if (e.getCause() != null) {
System.err.println("Caused by: " + e.getCause().getMessage());
}
}
// Check if $SIG{__DIE__} handler is defined
RuntimeScalar sig = GlobalVariable.getGlobalHash("main::SIG").get("__DIE__");
if (sig.getDefinedBoolean()) {
// Call the $SIG{__DIE__} handler (similar to what die() does)
RuntimeScalar sigHandler = new RuntimeScalar(sig);
// Undefine $SIG{__DIE__} before calling to avoid infinite recursion
int level = DynamicVariableManager.getLocalLevel();
DynamicVariableManager.pushLocalVariable(sig);
try {
RuntimeArray handlerArgs = new RuntimeArray();
RuntimeArray.push(handlerArgs, new RuntimeScalar(err));
apply(sigHandler, handlerArgs, RuntimeContextType.SCALAR);
} catch (Throwable handlerException) {
// If the handler dies, use its payload as the new error
if (handlerException instanceof RuntimeException && handlerException.getCause() instanceof PerlDieException) {
PerlDieException pde = (PerlDieException) handlerException.getCause();
RuntimeBase handlerPayload = pde.getPayload();
if (handlerPayload != null) {
err.set(handlerPayload.getFirst());
}
} else if (handlerException instanceof PerlDieException) {
PerlDieException pde = (PerlDieException) handlerException;
RuntimeBase handlerPayload = pde.getPayload();
if (handlerPayload != null) {
err.set(handlerPayload.getFirst());
}
}
// If handler throws other exceptions, ignore them (keep original error in $@)
} finally {
// Restore $SIG{__DIE__}
DynamicVariableManager.popToLocalLevel(level);
}
}
// Return undef/empty list to signal compilation failure
if (callContext == RuntimeContextType.LIST) {
return new RuntimeList();
} else {
return new RuntimeList(new RuntimeScalar());
}
}
// Execute the interpreted code
try {
result = interpretedCode.apply(args, callContext);
// Clear $@ on successful execution
RuntimeScalar err = GlobalVariable.getGlobalVariable("main::@");
err.set("");
return result;
} catch (PerlDieException e) {
// Runtime error - set $@ and return undef/empty list
RuntimeScalar err = GlobalVariable.getGlobalVariable("main::@");
RuntimeBase payload = e.getPayload();
if (payload != null) {
err.set(payload.getFirst());
} else {
err.set("Died");
}
// Return undef/empty list
if (callContext == RuntimeContextType.LIST) {
return new RuntimeList();
} else {
return new RuntimeList(new RuntimeScalar());
}
} catch (Throwable e) {
// Other runtime errors - set $@ and return undef/empty list
RuntimeScalar err = GlobalVariable.getGlobalVariable("main::@");
String message = e.getMessage();
if (message == null || message.isEmpty()) {
message = e.getClass().getSimpleName();
}
err.set(message);
// Return undef/empty list
if (callContext == RuntimeContextType.LIST) {
return new RuntimeList();
} else {
return new RuntimeList(new RuntimeScalar());
}
}
} finally {
// Restore dynamic variables (local) to their state before eval
DynamicVariableManager.popToLocalLevel(dynamicVarLevel);
// Clean up ThreadLocal
evalRuntimeContext.remove();
}
}
// make sure we return a RuntimeScalar from __SUB__
public static RuntimeScalar selfReferenceMaybeNull(RuntimeScalar codeRef) {
return codeRef == null
? scalarUndef
: codeRef;
}
/**
* Factory method to create a CODE object (anonymous subroutine).
* This is called right after a new Class is compiled.
* The codeObject is an instance of the new Class, with the closure variables in place.
*
* @param codeObject the instance of the compiled Class
* @return a RuntimeScalar representing the CODE object
* @throws Exception if an error occurs during method retrieval
*/
public static RuntimeScalar makeCodeObject(Object codeObject) throws Exception {
return makeCodeObject(codeObject, null);
}
public static RuntimeScalar makeCodeObject(Object codeObject, String prototype) throws Exception {
// Retrieve the class of the provided code object
Class<?> clazz = codeObject.getClass();
// Check if the method handle is already cached
MethodHandle methodHandle;
synchronized (methodHandleCache) {
if (methodHandleCache.containsKey(clazz)) {
methodHandle = methodHandleCache.get(clazz);
} else {
// Get the 'apply' method from the class.
methodHandle = RuntimeCode.lookup.findVirtual(clazz, "apply", RuntimeCode.methodType);
// Cache the method handle
methodHandleCache.put(clazz, methodHandle);
}
}
// Wrap the method and the code object in a RuntimeCode instance
// This allows us to store both the method and the object it belongs to
// Create a new RuntimeScalar instance to hold the CODE object
RuntimeScalar codeRef = new RuntimeScalar(new RuntimeCode(methodHandle, codeObject, prototype));
// Set the __SUB__ instance field
Field field = clazz.getDeclaredField("__SUB__");
field.set(codeObject, codeRef);
return codeRef;
}
/**
* Call a method in a Perl-like class hierarchy using the C3 linearization algorithm.
* This version accepts a native RuntimeBase[] array for parameters.
*
* @param runtimeScalar The object to call the method on.
* @param method The method to resolve.
* @param currentSub The subroutine to resolve SUPER::method in.
* @param args The arguments to pass to the method as native array.
* @param callContext The call context.
* @return The result of the method call.
*/
public static RuntimeList call(RuntimeScalar runtimeScalar,
RuntimeScalar method,
RuntimeScalar currentSub,
RuntimeBase[] args,
int callContext) {
// Transform the native array to RuntimeArray of aliases (Perl variable `@_`)
// Note: `this` (runtimeScalar) will be inserted by the RuntimeArray version
RuntimeArray a = new RuntimeArray();
for (RuntimeBase arg : args) {
arg.setArrayOfAlias(a);
}
return call(runtimeScalar, method, currentSub, a, callContext);
}