-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPerlLanguageProvider.java
More file actions
672 lines (602 loc) · 32.3 KB
/
PerlLanguageProvider.java
File metadata and controls
672 lines (602 loc) · 32.3 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
package org.perlonjava.app.scriptengine;
import org.perlonjava.app.cli.CompilerOptions;
import org.perlonjava.backend.bytecode.BytecodeCompiler;
import org.perlonjava.backend.bytecode.Disassemble;
import org.perlonjava.backend.bytecode.InterpretedCode;
import org.perlonjava.backend.jvm.CompiledCode;
import org.perlonjava.backend.jvm.EmitterContext;
import org.perlonjava.backend.jvm.EmitterMethodCreator;
import org.perlonjava.backend.jvm.InterpreterFallbackException;
import org.perlonjava.backend.jvm.JavaClassInfo;
import org.perlonjava.frontend.analysis.ConstantFoldingVisitor;
import org.perlonjava.frontend.astnode.Node;
import org.perlonjava.frontend.lexer.Lexer;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.parser.DataSection;
import org.perlonjava.frontend.parser.Parser;
import org.perlonjava.frontend.parser.SpecialBlockParser;
import org.perlonjava.frontend.semantic.ScopedSymbolTable;
import org.perlonjava.runtime.perlmodule.BHooksEndOfScope;
import org.perlonjava.runtime.perlmodule.FilterUtilCall;
import org.perlonjava.runtime.perlmodule.Strict;
import org.perlonjava.runtime.runtimetypes.*;
import org.perlonjava.runtime.WarningBitsRegistry;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Constructor;
import java.util.List;
import static org.perlonjava.runtime.runtimetypes.GlobalVariable.resetAllGlobals;
import static org.perlonjava.runtime.runtimetypes.SpecialBlock.*;
/**
* The PerlLanguageProvider class is responsible for executing Perl code within the Java environment.
* It provides methods to execute, tokenize, compile, and parse Perl code.
* <p>
* This class uses Java's MethodHandles and reflection to dynamically invoke methods and constructors.
* It also integrates with the runtime classes such as RuntimeArray, RuntimeContextType, and RuntimeList
* to manage the execution context and results.
* <p>
* Key functionalities include:
* - Executing Perl code and returning the result.
* - Enabling debugging, tokenization, compilation, and parsing modes.
* - Handling errors and providing meaningful error messages.
* <p>
* Why is this class needed?
* <p>
* The PerlLanguageProvider class abstracts the complexity of executing Perl code within a Java environment.
* Directly invoking Perl code execution involves intricate setup and handling of various runtime contexts,
* error management, and integration with Java's MethodHandles and reflection APIs. By encapsulating these
* details within a single class, we provide a simpler and more manageable interface for executing Perl code.
*/
public class PerlLanguageProvider {
// Cache env var at class-init to avoid repeated native System.getenv()
// calls from the compilation fallback hot path.
private static final boolean SHOW_FALLBACK =
System.getenv("JPERL_SHOW_FALLBACK") != null;
private static boolean globalInitialized = false;
public static void resetAll() {
globalInitialized = false;
resetAllGlobals();
DataSection.reset();
}
/**
* Executes the given Perl code and returns the result.
*
* @param compilerOptions Compiler flags, file name and source code
* @param isTopLevelScript Whether this is the top-level script (affects BEGIN/END/etc handling)
* @return The result of the Perl code execution.
*/
public static RuntimeList executePerlCode(CompilerOptions compilerOptions,
boolean isTopLevelScript) throws Exception {
// Default behavior: use SCALAR context for non-top-level scripts
return executePerlCode(compilerOptions, isTopLevelScript, -1);
}
/**
* Executes the given Perl code with specified context and returns the result.
*
* @param compilerOptions Compiler flags, file name and source code
* @param isTopLevelScript Whether this is the top-level script (affects BEGIN/END/etc handling)
* @param callerContext The calling context (VOID, SCALAR, LIST) or -1 for default
* @return The result of the Perl code execution.
*/
public static RuntimeList executePerlCode(CompilerOptions compilerOptions,
boolean isTopLevelScript,
int callerContext) throws Exception {
// Save the current scope so we can restore it after execution.
// This is critical because require/do should not leak their scope to the caller.
ScopedSymbolTable savedCurrentScope = SpecialBlockParser.getCurrentScope();
// Save and clear the eval runtime context so that modules loaded via require/do
// during eval STRING execution don't see the eval's captured variables.
// Without this, SpecialBlockParser.runSpecialBlock would incorrectly alias
// local variables in required modules to the eval's captured variables when
// they share the same name (e.g., $caller in constant.pm vs $caller in eval scope).
RuntimeCode.EvalRuntimeContext savedEvalRuntimeContext =
RuntimeCode.saveAndClearEvalRuntimeContext();
// Store the isMainProgram flag in CompilerOptions for use during code generation
compilerOptions.isMainProgram = isTopLevelScript;
ScopedSymbolTable globalSymbolTable = new ScopedSymbolTable();
// Enter a new scope in the symbol table and add special Perl variables
globalSymbolTable.enterScope();
globalSymbolTable.addVariable("this", "", null); // anon sub instance is local variable 0
globalSymbolTable.addVariable("@_", "our", null); // Argument list is local variable 1
globalSymbolTable.addVariable("wantarray", "", null); // Call context is local variable 2
if (compilerOptions.codeHasEncoding) {
globalSymbolTable.enableStrictOption(Strict.HINT_UTF8);
}
// Use caller's context if specified, otherwise default based on script type
int contextType = callerContext >= 0 ? callerContext :
(isTopLevelScript ? RuntimeContextType.VOID : RuntimeContextType.SCALAR);
// Create the compiler context
EmitterContext ctx = new EmitterContext(
new JavaClassInfo(), // internal java class name
globalSymbolTable.snapShot(), // Top-level symbol table
null, // Method visitor
null, // Class writer
contextType, // Call context - scalar for require/do, void for top-level
true, // Is boxed
null, // errorUtil
compilerOptions,
new RuntimeArray()
);
if (!globalInitialized) {
GlobalContext.initializeGlobals(compilerOptions);
globalInitialized = true;
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("parse code: " + compilerOptions.code);
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug(" call context " + ctx.contextType);
// Apply any BEGIN-block filters before tokenization if requested
// This is a workaround for the limitation that our architecture tokenizes all source upfront
if (compilerOptions.applySourceFilters) {
compilerOptions.code = FilterUtilCall.preprocessWithBeginFilters(compilerOptions.code);
}
// Create the LexerToken list
Lexer lexer = new Lexer(compilerOptions.code);
List<LexerToken> tokens = lexer.tokenize(); // Tokenize the Perl code
if (ctx.compilerOptions.tokenizeOnly) {
// Printing the tokens
for (LexerToken token : tokens) {
System.out.println(token);
}
RuntimeIO.closeAllHandles();
return null; // success
}
compilerOptions.code = null; // Throw away the source code to spare memory
// Create the AST
// Create an instance of ErrorMessageUtil with the file name and token list
ctx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
Parser parser = new Parser(ctx, tokens); // Parse the tokens
parser.isTopLevelScript = isTopLevelScript;
// Create placeholder DATA filehandle early so it's available during BEGIN block execution
// This ensures *ARGV = *DATA aliasing works correctly in BEGIN blocks
DataSection.createPlaceholderDataHandle(parser);
Node ast;
if (isTopLevelScript) {
CallerStack.push(
"main",
ctx.compilerOptions.fileName,
ctx.errorUtil.getLineNumber(parser.tokenIndex));
// Push the main script onto BHooksEndOfScope's loading stack so that
// on_scope_end callbacks (e.g., from namespace::clean) are deferred
// until end of parsing, matching Perl 5 behavior.
BHooksEndOfScope.beginFileLoad(ctx.compilerOptions.fileName);
}
try {
ast = parser.parse(); // Generate the abstract syntax tree (AST)
} finally {
if (isTopLevelScript) {
// Fire on_scope_end callbacks now that parsing is complete.
// This is the "end of compilation scope" equivalent.
BHooksEndOfScope.endFileLoad(ctx.compilerOptions.fileName);
CallerStack.pop();
}
}
// ast = ConstantFoldingVisitor.foldConstants(ast);
// Constant folding: inline user-defined constant subs and fold constant expressions.
// This runs after parsing (so BEGIN blocks have executed and constants are defined)
// and before code emission. The package from the symbol table is used to resolve
// bare constant identifiers (e.g., PI from `use constant PI => 3.14`).
ast = ConstantFoldingVisitor.foldConstants(ast, ctx.symbolTable.getCurrentPackage());
if (ctx.compilerOptions.parseOnly) {
// Printing the ast
System.out.println(ast);
RuntimeIO.closeAllHandles();
return null; // success
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("-- AST:\n" + ast + "--\n");
// Create the Java class from the AST
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("createClassWithMethod");
// Create a new instance of ErrorMessageUtil, resetting the line counter
ctx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
// Snapshot the symbol table after parsing.
// The parser records lexical declarations (e.g., `for my $p (...)`) and pragma state
// (strict/warnings/features) into ctx.symbolTable. Resetting to a fresh global snapshot
// loses those declarations and causes strict-vars failures during codegen.
ctx.symbolTable = ctx.symbolTable.snapShot();
SpecialBlockParser.setCurrentScope(ctx.symbolTable);
try {
// Compile to executable (compiler or interpreter based on flag)
RuntimeCode runtimeCode = compileToExecutable(ast, ctx);
// Execute (unified path for both backends)
return executeCode(runtimeCode, ctx, isTopLevelScript, callerContext);
} finally {
// Restore the caller's scope so require/do doesn't leak its scope to the caller.
// But do NOT restore for top-level scripts - we want the main script's pragmas to persist.
if (savedCurrentScope != null && !isTopLevelScript) {
SpecialBlockParser.setCurrentScope(savedCurrentScope);
}
// Restore the eval runtime context so the caller's eval STRING compilation
// can continue with its captured variables.
RuntimeCode.restoreEvalRuntimeContext(savedEvalRuntimeContext);
}
}
/**
* Executes the given Perl code using a syntax tree and returns the result.
* Uses VOID context by default.
*
* @param ast The abstract syntax tree representing the Perl code.
* @param tokens The list of tokens representing the Perl code.
* @param compilerOptions Compiler flags, file name and source code.
* @return The result of the Perl code execution.
*/
public static RuntimeList executePerlAST(Node ast,
List<LexerToken> tokens,
CompilerOptions compilerOptions) throws Exception {
return executePerlAST(ast, tokens, compilerOptions, RuntimeContextType.VOID);
}
/**
* Executes the given Perl code using a syntax tree with specified context.
*
* @param ast The abstract syntax tree representing the Perl code.
* @param tokens The list of tokens representing the Perl code.
* @param compilerOptions Compiler flags, file name and source code.
* @param contextType The context to use for execution (VOID, SCALAR, LIST).
* @return The result of the Perl code execution.
*/
public static RuntimeList executePerlAST(Node ast,
List<LexerToken> tokens,
CompilerOptions compilerOptions,
int contextType) throws Exception {
// Save the current scope so we can restore it after execution.
ScopedSymbolTable savedCurrentScope = SpecialBlockParser.getCurrentScope();
// Save and clear the eval runtime context (same reason as executePerlCode)
RuntimeCode.EvalRuntimeContext savedEvalRuntimeContext =
RuntimeCode.saveAndClearEvalRuntimeContext();
ScopedSymbolTable globalSymbolTable = new ScopedSymbolTable();
globalSymbolTable.enterScope();
globalSymbolTable.addVariable("this", "", null);
globalSymbolTable.addVariable("@_", "our", null);
globalSymbolTable.addVariable("wantarray", "", null);
// Inherit $^H (strictOptions) from the caller's scope so BEGIN blocks
// can see and modify the enclosing scope's compile-time hints
if (savedCurrentScope != null) {
globalSymbolTable.setStrictOptions(savedCurrentScope.getStrictOptions());
// Inherit warning flags so ${^WARNING_BITS} returns correct values in BEGIN blocks
if (!savedCurrentScope.warningFlagsStack.isEmpty()) {
globalSymbolTable.warningFlagsStack.pop();
globalSymbolTable.warningFlagsStack.push((java.util.BitSet) savedCurrentScope.warningFlagsStack.peek().clone());
}
if (!savedCurrentScope.warningDisabledStack.isEmpty()) {
globalSymbolTable.warningDisabledStack.pop();
globalSymbolTable.warningDisabledStack.push((java.util.BitSet) savedCurrentScope.warningDisabledStack.peek().clone());
}
if (!savedCurrentScope.warningFatalStack.isEmpty()) {
globalSymbolTable.warningFatalStack.pop();
globalSymbolTable.warningFatalStack.push((java.util.BitSet) savedCurrentScope.warningFatalStack.peek().clone());
}
}
EmitterContext ctx = new EmitterContext(
new JavaClassInfo(),
globalSymbolTable.snapShot(),
null,
null,
contextType,
true,
null,
compilerOptions,
new RuntimeArray()
);
if (!globalInitialized) {
GlobalContext.initializeGlobals(compilerOptions);
globalInitialized = true;
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Using provided AST");
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug(" call context " + ctx.contextType);
// Create the Java class from the AST
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("createClassWithMethod");
ctx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
// Snapshot the symbol table as seen by the parser (includes lexical decls + pragma state).
ctx.symbolTable = ctx.symbolTable.snapShot();
SpecialBlockParser.setCurrentScope(ctx.symbolTable);
try {
// Compile to executable (compiler or interpreter based on flag)
RuntimeCode runtimeCode = compileToExecutable(ast, ctx);
return executeCode(runtimeCode, ctx, false, contextType);
} finally {
// Propagate $^H changes back to the caller's scope so subsequent
// code in the same lexical block sees the updated hints
if (savedCurrentScope != null) {
savedCurrentScope.setStrictOptions(ctx.symbolTable.getStrictOptions());
// Also update per-call-site hints so caller()[8] and caller()[10] are correct
WarningBitsRegistry.setCallSiteHints(ctx.symbolTable.getStrictOptions());
WarningBitsRegistry.snapshotCurrentHintHash();
SpecialBlockParser.setCurrentScope(savedCurrentScope);
}
// Restore the eval runtime context
RuntimeCode.restoreEvalRuntimeContext(savedEvalRuntimeContext);
}
}
/**
* Common method to execute compiled code and return the result.
* Works with both interpreter (InterpretedCode) and compiler (CompiledCode).
*
* @param runtimeCode The compiled RuntimeCode instance (InterpretedCode or CompiledCode)
* @param ctx The emitter context.
* @param isMainProgram Indicates if this is the main program.
* @param callerContext The calling context (VOID, SCALAR, LIST) or -1 for default
* @return The result of the Perl code execution.
*/
private static RuntimeList executeCode(RuntimeCode runtimeCode, EmitterContext ctx, boolean isMainProgram, int callerContext) throws Exception {
// Phase B2a (refcount_alignment_52leaks_plan.md): mark this
// body as module-initialization for the sake of the
// reachability-walker auto-sweep, UNLESS it's the main
// program body. DBIC's LeakTracer and similar leak-detection
// code is sensitive to weak refs being cleared mid-initializer
// chain, so auto-sweep inhibits itself while this counter is
// positive.
boolean guardEntered = false;
if (!isMainProgram) {
ModuleInitGuard.enter();
guardEntered = true;
}
try {
return executeCodeImpl(runtimeCode, ctx, isMainProgram, callerContext);
} finally {
if (guardEntered) ModuleInitGuard.exit();
}
}
private static RuntimeList executeCodeImpl(RuntimeCode runtimeCode, EmitterContext ctx, boolean isMainProgram, int callerContext) throws Exception {
runUnitcheckBlocks(ctx.unitcheckBlocks);
if (isMainProgram) {
// Push a CallerStack entry so caller() inside CHECK/INIT/END blocks
// sees the main program as their caller, matching Perl 5 behavior
// where these blocks run from the main program scope.
CallerStack.push("main", ctx.compilerOptions.fileName, 0);
try {
runCheckBlocks();
} finally {
CallerStack.pop();
}
}
if (ctx.compilerOptions.compileOnly) {
RuntimeIO.closeAllHandles();
return null;
}
RuntimeList result;
try {
if (isMainProgram) {
CallerStack.push("main", ctx.compilerOptions.fileName, 0);
try {
runInitBlocks();
} finally {
CallerStack.pop();
}
}
// Use the caller's context if specified, otherwise use default behavior
int executionContext = callerContext >= 0 ? callerContext :
(isMainProgram ? RuntimeContextType.VOID : RuntimeContextType.SCALAR);
// Call apply() directly - works for both InterpretedCode and CompiledCode
result = runtimeCode.apply(new RuntimeArray(), executionContext);
try {
if (isMainProgram) {
// Flush deferred mortal decrements from file-scoped lexical cleanup.
// The main script's apply() runs scopeExitCleanup for all my-variables
// (deferring refCount decrements), but the MortalList is not flushed
// inside the subroutine (flush=false for blockIsSubroutine). Process
// those decrements now so objects reach refCount=0 and DESTROY fires
// BEFORE END blocks run — matching Perl 5's destruct sequence where
// file-scoped lexicals are destroyed before END block dispatch.
MortalList.flush();
// Process captured variables whose scope has exited but whose
// refCount was deferred because captureCount > 0. The interpreter
// captures ALL visible lexicals for eval STRING support, inflating
// captureCount on variables that closures don't actually use.
// Now that all scopes have exited, it's safe to decrement.
// This must happen before END blocks so that DBIC's LeakTracer
// (which runs in an END block) sees objects properly DESTROY'd.
MortalList.flushDeferredCaptures();
CallerStack.push("main", ctx.compilerOptions.fileName, 0);
try {
runEndBlocks();
} finally {
CallerStack.pop();
}
// Global destruction: walk stashes for tracked blessed objects
GlobalDestruction.runGlobalDestruction();
}
} catch (Throwable endException) {
RuntimeIO.closeAllHandles();
String errorMessage = ErrorMessageUtil.stringifyException(endException);
System.out.println(errorMessage);
System.out.println("END failed--call queue aborted.");
}
} catch (PerlExitException e) {
// PerlExitException already ran END blocks and closed handles in WarnDie.exit()
// Just re-throw for the caller to handle
throw e;
} catch (PerlNonLocalReturnException e) {
// A non-local return escaped to the top level (e.g., return inside map/grep
// at the top level). In Perl 5, this produces "Can't return outside a subroutine".
// Consume the exception and treat the return value as the program result.
result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList();
} catch (Throwable t) {
if (isMainProgram) {
MortalList.flush(); // Flush file-scoped lexical cleanup before END
MortalList.flushDeferredCaptures(); // Process captured vars (see above)
CallerStack.push("main", ctx.compilerOptions.fileName, 0);
try {
runEndBlocks(false); // Don't reset $? on exception path
} finally {
CallerStack.pop();
}
RuntimeIO.closeAllHandles();
}
if (t instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new RuntimeException(t);
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Result of generatedMethod: " + result);
RuntimeIO.flushAllHandles();
return result;
}
/**
* Compiles Perl AST to an executable RuntimeCode instance (compiler or interpreter).
* This method provides a unified compilation path that chooses the backend
* based on CompilerOptions.useInterpreter, with automatic fallback to interpreter
* when compilation exceeds JVM method size limits.
*
* @param ast The abstract syntax tree to compile
* @param ctx The emitter context
* @return RuntimeCode instance - either InterpretedCode or CompiledCode
* @throws Exception if compilation fails
*/
private static RuntimeCode compileToExecutable(Node ast, EmitterContext ctx) throws Exception {
if (ctx.compilerOptions.useInterpreter || RuntimeCode.FORCE_INTERPRETER) {
// Interpreter path - returns InterpretedCode (extends RuntimeCode)
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Compiling to bytecode interpreter");
BytecodeCompiler compiler = new BytecodeCompiler(
ctx.compilerOptions.fileName,
1, // sourceLine (legacy parameter)
ctx.errorUtil // Pass errorUtil for proper error formatting with line numbers
);
InterpretedCode interpretedCode = compiler.compile(ast, ctx);
// If --disassemble is enabled, print the bytecode
if (ctx.compilerOptions.disassembleEnabled) {
System.out.println("=== Interpreter Bytecode ===");
System.out.println(Disassemble.disassemble(interpretedCode));
System.out.println("=== End Bytecode ===");
}
return interpretedCode;
} else {
// Compiler path - returns CompiledCode (wrapper around generated class)
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Compiling to JVM bytecode");
try {
Class<?> generatedClass = EmitterMethodCreator.createClassWithMethod(
ctx,
ast,
false // no try-catch
);
Constructor<?> constructor = generatedClass.getConstructor();
Object instance = constructor.newInstance();
// Create MethodHandle for the apply() method
MethodHandle methodHandle = RuntimeCode.lookup.findVirtual(
generatedClass,
"apply",
RuntimeCode.methodType
);
// Wrap in CompiledCode for type safety and consistency
// Main scripts don't have prototypes, so pass null
CompiledCode compiled = new CompiledCode(
methodHandle,
instance,
null, // prototype (main scripts don't have one)
generatedClass,
ctx
);
return compiled;
} catch (InterpreterFallbackException fallback) {
// getBytecode() already compiled interpreter code as fallback
// when ASM frame computation failed (e.g., high fan-in to shared labels).
// Use the pre-compiled interpreter code directly.
boolean showFallback = SHOW_FALLBACK;
if (showFallback) {
System.err.println("Note: Using interpreter fallback (ASM frame compute crash).");
}
return fallback.interpretedCode;
} catch (Throwable e) {
// Check if this is a recoverable compilation error that can use interpreter fallback
// Catch Throwable (not just RuntimeException) because ClassFormatError
// ("Too many arguments in method signature") extends Error, not Exception
if (needsInterpreterFallback(e)) {
boolean showFallback = SHOW_FALLBACK;
if (showFallback) {
System.err.println("Note: Method too large, using interpreter backend.");
}
if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("Falling back to bytecode interpreter due to method size");
// Reset strict/feature/warning flags before fallback compilation.
// The JVM compiler already processed BEGIN blocks (use strict, etc.)
// which set these flags on ctx.symbolTable. But the interpreter will
// re-process those pragmas during execution, so inheriting them causes
// false strict violations (e.g. bareword filehandles rejected).
if (ctx.symbolTable != null) {
ctx.symbolTable.strictOptionsStack.pop();
ctx.symbolTable.strictOptionsStack.push(0);
}
BytecodeCompiler compiler = new BytecodeCompiler(
ctx.compilerOptions.fileName,
1,
ctx.errorUtil
);
InterpretedCode interpretedCode = compiler.compile(ast, ctx);
if (ctx.compilerOptions.disassembleEnabled) {
System.out.println("=== Interpreter Bytecode ===");
System.out.println(Disassemble.disassemble(interpretedCode));
System.out.println("=== End Bytecode ===");
}
return interpretedCode;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
}
}
private static boolean needsInterpreterFallback(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause()) {
// VerifyError means the JVM rejected the generated bytecode
// (e.g., invalid stack map frames from complex control flow).
// Fall back to interpreter instead of crashing.
if (t instanceof VerifyError) {
return true;
}
String msg = t.getMessage();
if (msg != null && (
msg.contains("Method too large") ||
msg.contains("Too many arguments in method signature") ||
msg.contains("ASM frame computation failed") ||
msg.contains("Unexpected runtime error during bytecode generation") ||
msg.contains("dstFrame") ||
msg.contains("requires interpreter fallback"))) {
return true;
}
}
return false;
}
/**
* Compiles Perl code to RuntimeCode without executing it.
* This allows compilation once and execution multiple times for better performance.
*
* @param compilerOptions Compiler flags, file name and source code
* @return The compiled code instance (can be used with RuntimeCode.apply via MethodHandle)
* @throws Exception if compilation fails
*/
public static Object compilePerlCode(CompilerOptions compilerOptions) throws Exception {
ScopedSymbolTable globalSymbolTable = new ScopedSymbolTable();
globalSymbolTable.enterScope();
globalSymbolTable.addVariable("this", "", null); // anon sub instance is local variable 0
globalSymbolTable.addVariable("@_", "our", null); // Argument list is local variable 1
globalSymbolTable.addVariable("wantarray", "", null); // Call context is local variable 2
if (compilerOptions.codeHasEncoding) {
globalSymbolTable.enableStrictOption(Strict.HINT_UTF8);
}
EmitterContext ctx = new EmitterContext(
new JavaClassInfo(),
globalSymbolTable.snapShot(),
null,
null,
RuntimeContextType.SCALAR, // Default to SCALAR context
true,
null,
compilerOptions,
new RuntimeArray()
);
if (!globalInitialized) {
GlobalContext.initializeGlobals(compilerOptions);
globalInitialized = true;
}
// Tokenize
Lexer lexer = new Lexer(compilerOptions.code);
List<LexerToken> tokens = lexer.tokenize();
compilerOptions.code = null; // Free memory
// Parse
ctx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
Parser parser = new Parser(ctx, tokens);
parser.isTopLevelScript = false; // Not top-level for compiled script
Node ast = parser.parse();
// Compile to class or bytecode based on flag
ctx.errorUtil = new ErrorMessageUtil(ctx.compilerOptions.fileName, tokens);
ctx.symbolTable = ctx.symbolTable.snapShot();
SpecialBlockParser.setCurrentScope(ctx.symbolTable);
// Use unified compilation path (works for JSR 223 too!)
return compileToExecutable(ast, ctx);
}
}