-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSubroutineParser.java
More file actions
882 lines (761 loc) · 46.4 KB
/
SubroutineParser.java
File metadata and controls
882 lines (761 loc) · 46.4 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
package org.perlonjava.frontend.parser;
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.JavaClassInfo;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.lexer.LexerTokenType;
import org.perlonjava.frontend.semantic.ScopedSymbolTable;
import org.perlonjava.frontend.semantic.SymbolTable;
import org.perlonjava.runtime.mro.InheritanceResolver;
import org.perlonjava.runtime.runtimetypes.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.function.Supplier;
import static org.perlonjava.frontend.parser.ParserTables.CORE_PROTOTYPES;
import static org.perlonjava.frontend.parser.ParserTables.INFIX_OP;
import static org.perlonjava.frontend.parser.PrototypeArgs.consumeArgsWithPrototype;
import static org.perlonjava.frontend.parser.SignatureParser.parseSignature;
import static org.perlonjava.frontend.parser.TokenUtils.peek;
public class SubroutineParser {
// Create a static semaphore with 1 permit
private static final Semaphore semaphore = new Semaphore(1);
/**
* Parses a subroutine call.
*
* @param parser The parser object
* @return A Node representing the parsed subroutine call.
*/
static Node parseSubroutineCall(Parser parser, boolean isMethod) {
// Parse the subroutine name as a complex identifier
// Alternately, this could be the start of a v-string like v10.20.30
int currentIndex = parser.tokenIndex;
String subName = IdentifierParser.parseSubroutineIdentifier(parser);
parser.ctx.logDebug("SubroutineCall subName `" + subName + "` package " + parser.ctx.symbolTable.getCurrentPackage());
if (subName == null) {
throw new PerlCompilerException(parser.tokenIndex, "Syntax error", parser.ctx.errorUtil);
}
// Check if this is a standard filehandle that should be treated as a bareword, not a subroutine call
if (!isMethod && (subName.equals("STDIN") || subName.equals("STDOUT") || subName.equals("STDERR"))) {
// Return as a simple identifier node, not a subroutine call
return new IdentifierNode(subName, currentIndex);
}
// Check if this is a lexical sub/method (my sub name / my method name)
// Lexical subs are stored in the symbol table with "&" prefix
// IMPORTANT: Check lexical sub FIRST, even if the name is a quote-like operator!
// This allows "my sub y" to shadow the "y///" transliteration operator
String lexicalKey = "&" + subName;
SymbolTable.SymbolEntry lexicalEntry = parser.ctx.symbolTable.getSymbolEntry(lexicalKey);
if (lexicalEntry != null && lexicalEntry.ast() instanceof OperatorNode varNode) {
// Check if this is an "our sub" - if so, use the stored fully qualified name
Boolean isOurSub = (Boolean) varNode.getAnnotation("isOurSub");
if (isOurSub != null && isOurSub) {
// Use the stored fully qualified name instead of the current package
String storedFullName = (String) varNode.getAnnotation("fullSubName");
if (storedFullName != null) {
// Replace subName with the fully qualified name and continue with normal package sub lookup
subName = storedFullName;
}
// Fall through to normal package sub handling below
} else {
// This is a lexical sub (my/state) - handle it specially
LexerToken nextToken = peek(parser);
// Check if there's a prototype stored for this lexical sub
String lexicalPrototype = varNode.getAnnotation("prototype") != null ?
(String) varNode.getAnnotation("prototype") : null;
// Use lexical sub when:
// 1. There are explicit parentheses, OR
// 2. There's a prototype, OR
// 3. The next token isn't a bareword identifier (to avoid indirect method call confusion), OR
// 4. We're parsing a code reference for sort/map/grep (parsingForLoopVariable is true)
boolean useExplicitParen = nextToken.text.equals("(");
boolean hasPrototype = lexicalPrototype != null;
boolean nextIsIdentifier = nextToken.type == LexerTokenType.IDENTIFIER;
if (useExplicitParen || hasPrototype || !nextIsIdentifier || parser.parsingForLoopVariable) {
// This is a lexical sub/method - use the hidden variable instead of package lookup
// The varNode is the "my $name__lexsub_123" or "my $name__lexmethod_123" variable
// Get the hidden variable name for the lexical sub
String hiddenVarName = (String) varNode.getAnnotation("hiddenVarName");
if (hiddenVarName != null) {
// Get the package where this lexical sub was declared
String declaringPackage = (String) varNode.getAnnotation("declaringPackage");
// Make the hidden variable name fully qualified with the declaring package
String qualifiedHiddenVarName = hiddenVarName;
if (declaringPackage != null && !hiddenVarName.contains("::")) {
qualifiedHiddenVarName = declaringPackage + "::" + hiddenVarName;
}
// Get the hidden variable entry from the symbol table for the ID
String hiddenVarKey = "$" + hiddenVarName;
SymbolTable.SymbolEntry hiddenEntry = parser.ctx.symbolTable.getSymbolEntry(hiddenVarKey);
// Always create a fresh variable reference to avoid AST reuse issues
OperatorNode dollarOp = new OperatorNode("$",
new IdentifierNode(qualifiedHiddenVarName, currentIndex), currentIndex);
// Copy the ID from the symbol table entry for state variables
if (hiddenEntry != null && hiddenEntry.ast() instanceof OperatorNode hiddenVarNode) {
dollarOp.id = hiddenVarNode.id;
} else if (varNode.operator.equals("state") && varNode.operand instanceof OperatorNode innerNode) {
// Fallback: copy ID from the declaration
dollarOp.id = innerNode.id;
}
// If parsingForLoopVariable is set, we just need the code reference, not a call
// This is used by sort/map/grep when parsing the comparison sub
if (parser.parsingForLoopVariable) {
return dollarOp;
}
// Parse arguments using prototype if available
ListNode arguments;
if (useExplicitParen) {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
if (hasPrototype) {
// Use prototype to parse arguments (already consumed opening paren)
arguments = consumeArgsWithPrototype(parser, lexicalPrototype, false);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
} else {
List<Node> argList = ListParser.parseList(parser, ")", 0);
arguments = new ListNode(argList, parser.tokenIndex);
}
} else {
// No explicit parentheses - parse arguments with prototype (or null for no prototype)
// This matches behavior of regular package subs which call consumeArgsWithPrototype
arguments = consumeArgsWithPrototype(parser, lexicalPrototype);
}
// Call the hidden variable directly: $hiddenVar(arguments)
// The () operator will handle dereferencing and calling
return new BinaryOperatorNode("(",
dollarOp,
arguments,
currentIndex);
}
}
}
}
// Normalize the subroutine name to include the current package
// If subName already contains "::", it's already fully qualified (e.g., from "our sub")
String fullName = subName.contains("::")
? subName
: NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
// Check if we are parsing a method;
// Otherwise, check that the subroutine exists in the global namespace - then fetch prototype and attributes
// Special case: For method calls to 'new', don't require existence check (for generated constructors)
boolean isNewMethod = isMethod && subName.equals("new");
boolean subExists = isNewMethod;
String prototype = null;
List<String> attributes = null;
if (!isNewMethod && !isMethod && GlobalVariable.existsGlobalCodeRef(fullName)) {
RuntimeScalar codeRef = GlobalVariable.getGlobalCodeRef(fullName);
if (codeRef.value instanceof RuntimeCode runtimeCode) {
prototype = runtimeCode.prototype;
attributes = runtimeCode.attributes;
subExists = runtimeCode.methodHandle != null
|| runtimeCode.compilerSupplier != null
|| runtimeCode.isBuiltin
|| prototype != null
// Forward declarations like `sub foo;` create a RuntimeCode with a non-null
// attributes list (possibly empty). Placeholders created implicitly use null.
|| attributes != null;
}
}
if (!subExists && !isNewMethod && !isMethod) {
subExists = GlobalVariable.existsGlobalCodeRefAsScalar(fullName).getBoolean();
}
parser.ctx.logDebug("SubroutineCall exists " + subExists + " prototype `" + prototype + "` attributes " + attributes);
boolean prototypeHasGlob = prototype != null && prototype.contains("*");
// If a package name follows, then it looks like a indirect method
// Unless the subName looks like an operator
// Unless the subName has a prototype with `*`
if (peek(parser).type == LexerTokenType.IDENTIFIER && isValidIndirectMethod(subName) && !prototypeHasGlob) {
int currentIndex2 = parser.tokenIndex;
String packageName = IdentifierParser.parseSubroutineIdentifier(parser);
// System.out.println("maybe indirect object: " + packageName + "->" + subName);
// PERL RULE: Indirect object syntax requires identifier to be a package
// Check packageExistsCache which is populated when 'package' statement is parsed
// Note: packageExistsCache uses the package name as-is, not normalized
Boolean isPackage = GlobalVariable.packageExistsCache.get(packageName);
LexerToken token = peek(parser);
String fullName1 = NameNormalizer.normalizeVariableName(packageName, parser.ctx.symbolTable.getCurrentPackage());
boolean isLexicalSub = parser.ctx.symbolTable.getSymbolEntry("&" + packageName) != null;
boolean isKnownSub = false;
if (GlobalVariable.existsGlobalCodeRef(fullName1)) {
RuntimeScalar codeRef = GlobalVariable.getGlobalCodeRef(fullName1);
if (codeRef.value instanceof RuntimeCode runtimeCode) {
isKnownSub = runtimeCode.methodHandle != null
|| runtimeCode.compilerSupplier != null
|| runtimeCode.isBuiltin
|| runtimeCode.prototype != null
|| runtimeCode.attributes != null;
}
}
// Reject if:
// 1. Explicitly marked as non-package (false in cache), OR
// 2. Unknown package (null) AND unknown subroutine (!isKnownSub) AND followed by '('
// - this is a function call like mycan(...)
// Allow if:
// - Marked as package (true), OR
// - Unknown (null) but NOT followed by '(' - like 'new NonExistentClass'
if ((isPackage != null && !isPackage) || (isPackage == null && !isKnownSub && token.text.equals("("))) {
parser.tokenIndex = currentIndex2;
} else {
// Not a known subroutine, check if it's valid indirect object syntax
if (!isKnownSub && !isLexicalSub && isValidIndirectMethod(packageName)) {
if (!(token.text.equals("->") || token.text.equals("=>") || INFIX_OP.contains(token.text))) {
// System.out.println(" package loaded: " + packageName + "->" + subName);
ListNode arguments;
if (token.text.equals(",")) {
arguments = new ListNode(currentIndex);
} else {
arguments = consumeArgsWithPrototype(parser, "@");
}
return new BinaryOperatorNode(
"->",
new IdentifierNode(packageName, currentIndex2),
new BinaryOperatorNode("(",
new OperatorNode("&",
new IdentifierNode(subName, currentIndex2),
currentIndex),
arguments, currentIndex2),
currentIndex2);
}
}
// backtrack
parser.tokenIndex = currentIndex2;
}
}
// Create an identifier node for the subroutine name
IdentifierNode nameNode = new IdentifierNode(subName, parser.tokenIndex);
if (subName.startsWith("v") && subName.matches("^v\\d+$")) {
if (parser.tokens.get(parser.tokenIndex).text.equals(".") || !subExists) {
return StringParser.parseVstring(parser, subName, currentIndex);
}
}
// Check if the subroutine call has parentheses
boolean hasParentheses = peek(parser).text.equals("(");
if (!subExists && !hasParentheses) {
// Perl allows calling not-yet-declared subs without parentheses when the
// following token is not an identifier (e.g. `skip "msg", 2;`).
// This is heavily used by the perl5 test harness (test.pl) inside SKIP/TODO blocks.
// Keep indirect method call disambiguation for the identifier-followed case.
// IMPORTANT: do not apply this heuristic for method calls (`->method`) because
// it can misparse expressions like `$obj->method ? 0 : 1`.
if (isMethod) {
return parseIndirectMethodCall(parser, nameNode);
}
LexerToken nextTok = peek(parser);
boolean terminator = nextTok.text.equals(";")
|| nextTok.text.equals("}")
|| nextTok.text.equals(")")
|| nextTok.text.equals("]")
|| nextTok.text.equals(",")
|| nextTok.type == LexerTokenType.EOF;
boolean infixOp = nextTok.type == LexerTokenType.OPERATOR
&& (INFIX_OP.contains(nextTok.text)
|| nextTok.text.equals("?")
|| nextTok.text.equals(":"));
if (!terminator
&& !infixOp
&& nextTok.type != LexerTokenType.IDENTIFIER
&& !nextTok.text.equals("->")
&& !nextTok.text.equals("=>")) {
ListNode arguments = consumeArgsWithPrototype(parser, "@");
// Check if this is indirect object syntax like "s2 $f"
if (arguments.elements.size() > 0) {
Node firstArg = arguments.elements.get(0);
if (firstArg instanceof OperatorNode opNode && opNode.operator.equals("$")) {
Node object = firstArg;
// Create method call: object->method()
// Need to wrap the method name like other method calls do
Node methodCall = new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
new ListNode(currentIndex),
currentIndex);
return new BinaryOperatorNode("->", object, methodCall, currentIndex);
}
}
return new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
arguments,
currentIndex);
}
return parseIndirectMethodCall(parser, nameNode);
}
// Save the current subroutine context
String previousSubroutine = parser.ctx.symbolTable.getCurrentSubroutine();
try {
// Set the subroutine being called for error messages
parser.ctx.symbolTable.setCurrentSubroutine(fullName);
// Handle the parameter list for the subroutine call
ListNode arguments;
if (peek(parser).text.equals("->")) {
// method call without parentheses
arguments = new ListNode(parser.tokenIndex);
} else if (isMethod) {
// FUNDAMENTAL PERL RULE: Method calls NEVER check prototypes!
// This applies to ALL method calls (using ->), not just constructors.
// Prototypes are only enforced for direct subroutine calls.
// Parse arguments directly without any prototype restrictions.
if (peek(parser).text.equals("(")) {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
// ListParser.parseList returns List<Node>, wrap it in ListNode
// IMPORTANT: parseList consumes the closing delimiter ")" internally
List<Node> argList = ListParser.parseList(parser, ")", 0);
arguments = new ListNode(argList, parser.tokenIndex);
// DO NOT consume ")" again - parseList already did it
} else {
// No parentheses, no arguments
arguments = new ListNode(parser.tokenIndex);
}
} else {
// Direct subroutine calls DO check prototypes
arguments = consumeArgsWithPrototype(parser, prototype);
}
// Rewrite and return the subroutine call as `&name(arguments)`
return new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
arguments,
currentIndex);
} finally {
// Restore the previous subroutine context
parser.ctx.symbolTable.setCurrentSubroutine(previousSubroutine);
}
}
private static boolean isValidIndirectMethod(String subName) {
return !CORE_PROTOTYPES.containsKey(subName) && !subName.startsWith("CORE::");
}
private static Node parseIndirectMethodCall(Parser parser, IdentifierNode nameNode) {
// If the subroutine does not exist and there are no parentheses, it is not a subroutine call
/* It can be a call to a subroutine that is not defined yet:
`File::Path::rmtree` is a bareword (string) or a file handle
$ perl -e ' print File::Path::rmtree '
(no output)
$ perl -e ' print STDOUT File::Path::rmtree '
File::Path::rmtree
`File::Path::rmtree $_` is a method call `$_->method`:
$ perl -e ' File::Path::rmtree $_ '
Can't call method "rmtree" on an undefined value at -e line 1.
$ perl -e ' File::Path::rmtree this '
Can't locate object method "rmtree" via package "File::Path" (perhaps you forgot to load "File::Path"?)
*/
if (peek(parser).text.equals("$")) {
ListNode arguments = consumeArgsWithPrototype(parser, "$");
int index = parser.tokenIndex;
// For indirect object syntax like "s2 $f", this should be treated as "$f->s2()"
// not as "s2($f)". The first argument becomes the object.
if (arguments.elements.size() > 0) {
Node object = arguments.elements.get(0);
// Create method call: object->method()
return new BinaryOperatorNode("->", object, nameNode, index);
}
// Fallback to subroutine call if no arguments
return new BinaryOperatorNode(
"(",
new OperatorNode("&", nameNode, index),
arguments,
index);
}
return nameNode;
}
public static Node parseSubroutineDefinition(Parser parser, boolean wantName, String declaration) {
// my, our, state subs are handled in StatementResolver, not here
if (declaration != null && (declaration.equals("my") || declaration.equals("state"))) {
throw new PerlCompilerException("Internal error: my/state sub should be handled in StatementResolver");
}
// This method is responsible for parsing an anonymous subroutine (a subroutine without a name)
// or a named subroutine based on the 'wantName' flag.
int currentIndex = parser.tokenIndex;
// Initialize the subroutine name to null. This will store the name of the subroutine if 'wantName' is true.
String subName = null;
// If the 'wantName' flag is true and the next token is an identifier (or starts with ' or ::), we parse the subroutine name.
// Note: ' and :: can start a subroutine name (old-style package separator or explicit main:: prefix)
if (wantName && (peek(parser).type == LexerTokenType.IDENTIFIER || peek(parser).text.equals("'") || peek(parser).text.equals("::"))) {
// 'parseSubroutineIdentifier' is called to handle cases where the subroutine name might be complex
// (e.g., namespaced, fully qualified names). It may return null if no valid name is found.
subName = IdentifierParser.parseSubroutineIdentifier(parser);
// Mark named subroutines as non-packages in packageExistsCache immediately
// This helps indirect object detection distinguish subs from packages
if (subName != null) {
GlobalVariable.packageExistsCache.put(subName, false);
}
}
// Initialize the prototype node to null. This will store the prototype of the subroutine if it exists.
String prototype = null;
// Initialize a list to store any attributes the subroutine might have.
List<String> attributes = new ArrayList<>();
// Check for invalid prototype-like constructs without parentheses
if (peek(parser).text.equals("<") || peek(parser).text.equals("__FILE__")) {
// This looks like a prototype but without parentheses - it's invalid
if (subName != null) {
String fullName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
parser.throwCleanError("Illegal declaration of subroutine " + fullName);
} else {
parser.throwCleanError("Illegal declaration of anonymous subroutine");
}
}
// While there are attributes (denoted by a colon ':'), we keep parsing them.
while (peek(parser).text.equals(":")) {
prototype = consumeAttributes(parser, attributes);
}
ListNode signature = null;
// Check if the next token is an opening parenthesis '(' indicating a prototype.
if (peek(parser).text.equals("(")) {
if (parser.ctx.symbolTable.isFeatureCategoryEnabled("signatures")) {
parser.ctx.logDebug("Signatures feature enabled");
// If the signatures feature is enabled, we parse a signature.
signature = parseSignature(parser, subName);
parser.ctx.logDebug("Signature AST: " + signature);
parser.ctx.logDebug("next token " + peek(parser));
} else {
// If the signatures feature is not enabled, we just parse the prototype as a string.
// If a prototype exists, we parse it using 'parseRawString' method which handles it like the 'q()' operator.
// This means it will take everything inside the parentheses as a literal string.
prototype = ((StringNode) StringParser.parseRawString(parser, "q")).value;
// Validate prototype - certain characters are not allowed
if (prototype.contains("<>") || prototype.contains("__FILE__")) {
if (subName != null) {
String fullName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
parser.throwCleanError("Illegal declaration of subroutine " + fullName);
} else {
parser.throwCleanError("Illegal declaration of anonymous subroutine");
}
}
// While there are attributes after the prototype (denoted by a colon ':'), we keep parsing them.
while (peek(parser).text.equals(":")) {
consumeAttributes(parser, attributes);
}
}
}
if (wantName && subName != null && !peek(parser).text.equals("{")) {
// A named subroutine can be predeclared without a block of code.
String fullName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
RuntimeCode codeRef = (RuntimeCode) GlobalVariable.getGlobalCodeRef(fullName).value;
codeRef.prototype = prototype;
codeRef.attributes = attributes;
ListNode result = new ListNode(parser.tokenIndex);
result.setAnnotation("compileTimeOnly", true);
return result;
}
if (!wantName && !peek(parser).text.equals("{")) {
parser.throwCleanError("Illegal declaration of anonymous subroutine");
}
// After parsing name, prototype, and attributes, we expect an opening curly brace '{' to denote the start of the subroutine block.
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
// Save the current subroutine context and set the new one
String previousSubroutine = parser.ctx.symbolTable.getCurrentSubroutine();
boolean previousInSubroutineBody = parser.ctx.symbolTable.isInSubroutineBody();
// Set the current subroutine name (use empty string for anonymous subs)
parser.ctx.symbolTable.setCurrentSubroutine(subName != null ? subName : "");
// We are now parsing inside a subroutine body (named or anonymous)
parser.ctx.symbolTable.setInSubroutineBody(true);
try {
// Parse the block of the subroutine, which contains the actual code.
BlockNode block = ParseBlock.parseBlock(parser);
// After the block, we expect a closing curly brace '}' to denote the end of the subroutine.
// Check if we reached EOF instead of finding the closing brace
if (parser.tokenIndex >= parser.tokens.size() ||
parser.tokens.get(parser.tokenIndex).type == LexerTokenType.EOF) {
parser.throwCleanError("Missing right curly");
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Insert signature code in the block
if (signature != null) {
block.elements.addAll(0, signature.elements);
}
if (subName == null) {
return handleAnonSub(parser, subName, prototype, attributes, block, currentIndex);
} else {
return handleNamedSub(parser, subName, prototype, attributes, block, declaration);
}
} finally {
// Restore the previous subroutine context
parser.ctx.symbolTable.setCurrentSubroutine(previousSubroutine);
parser.ctx.symbolTable.setInSubroutineBody(previousInSubroutineBody);
}
}
static String consumeAttributes(Parser parser, List<String> attributes) {
// Consume the colon
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ":");
if (parser.tokens.get(parser.tokenIndex).text.equals("=")) {
parser.throwError("Use of := for an empty attribute list is not allowed");
}
if (peek(parser).text.equals("=")) {
return null;
}
String prototype = null;
String attrString = TokenUtils.consume(parser, LexerTokenType.IDENTIFIER).text;
if (parser.tokens.get(parser.tokenIndex).text.equals("(")) {
String argString = ((StringNode) StringParser.parseRawString(parser, "q")).value;
if (attrString.equals("prototype")) {
// :prototype($)
prototype = argString;
}
attrString += "(" + argString + ")";
}
// Consume the attribute name (an identifier) and add it to the attributes list.
attributes.add(attrString);
return prototype;
}
public static ListNode handleNamedSub(Parser parser, String subName, String prototype, List<String> attributes, BlockNode block, String declaration) {
return handleNamedSubWithFilter(parser, subName, prototype, attributes, block, false, declaration);
}
public static ListNode handleNamedSubWithFilter(Parser parser, String subName, String prototype, List<String> attributes, BlockNode block, boolean filterLexicalMethods, String declaration) {
// Check if there's a lexical forward declaration (our/my/state sub name;) that this definition should fulfill
String lexicalKey = "&" + subName;
SymbolTable.SymbolEntry lexicalEntry = parser.ctx.symbolTable.getSymbolEntry(lexicalKey);
String packageToUse = parser.ctx.symbolTable.getCurrentPackage();
// If the package stash has been aliased (e.g. via `*{Pkg::} = *{Other::}`), then
// new symbols defined in this package should land in the effective stash.
packageToUse = GlobalVariable.resolveStashAlias(packageToUse);
if (lexicalEntry != null && lexicalEntry.ast() instanceof OperatorNode varNode) {
// Check if this is an "our sub" forward declaration
Boolean isOurSub = (Boolean) varNode.getAnnotation("isOurSub");
if (isOurSub != null && isOurSub) {
// Use the package from the forward declaration, not the current package
String storedFullName = (String) varNode.getAnnotation("fullSubName");
if (storedFullName != null && storedFullName.contains("::")) {
// Extract package from stored full name (e.g., "main::d" -> "main")
int lastColon = storedFullName.lastIndexOf("::");
packageToUse = storedFullName.substring(0, lastColon);
}
} else if (lexicalEntry.decl().equals("my") || lexicalEntry.decl().equals("state")) {
// This is a "my sub" or "state sub" forward declaration
// The body should be filled in by creating a runtime code object
String hiddenVarName = (String) varNode.getAnnotation("hiddenVarName");
if (hiddenVarName != null) {
// Create an anonymous sub that will be used to fill the lexical sub
// We need to compile this into a RuntimeCode object that can be executed
SubroutineNode anonSub = new SubroutineNode(
null, // anonymous (no name)
prototype,
attributes,
block,
false, // useTryCatch
parser.tokenIndex
);
// Create assignment that will execute at runtime
// Use the declaring package to create a fully qualified variable name
String declaringPackage = (String) varNode.getAnnotation("declaringPackage");
String qualifiedHiddenVarName = hiddenVarName;
if (declaringPackage != null && !hiddenVarName.contains("::")) {
qualifiedHiddenVarName = declaringPackage + "::" + hiddenVarName;
}
OperatorNode varRef = new OperatorNode("$",
new IdentifierNode(qualifiedHiddenVarName, parser.tokenIndex),
parser.tokenIndex);
BinaryOperatorNode assignment = new BinaryOperatorNode("=", varRef, anonSub, parser.tokenIndex);
// Wrap the assignment in a BEGIN block so it executes at compile time
// This ensures that "sub name { }" inside another sub still fills the forward declaration immediately
List<Node> blockElements = new ArrayList<>();
blockElements.add(assignment);
BlockNode beginBlock = new BlockNode(blockElements, parser.tokenIndex);
// Execute the BEGIN block immediately during parsing
SpecialBlockParser.runSpecialBlock(parser, "BEGIN", beginBlock);
ListNode result = new ListNode(parser.tokenIndex);
result.setAnnotation("compileTimeOnly", true);
return result;
}
}
}
// - register the subroutine in the namespace
String fullName = NameNormalizer.normalizeVariableName(subName, packageToUse);
RuntimeScalar codeRef = GlobalVariable.getGlobalCodeRef(fullName);
InheritanceResolver.invalidateCache();
if (codeRef.value == null) {
codeRef.type = RuntimeScalarType.CODE;
codeRef.value = new RuntimeCode(subName, attributes);
}
// Initialize placeholder metadata (accessed via codeRef.value)
RuntimeCode placeholder = (RuntimeCode) codeRef.value;
placeholder.prototype = prototype;
placeholder.attributes = attributes;
placeholder.subName = subName;
placeholder.packageName = parser.ctx.symbolTable.getCurrentPackage();
// Optimization - https://github.com/fglock/PerlOnJava/issues/8
// Prepare capture variables
Map<Integer, SymbolTable.SymbolEntry> outerVars = parser.ctx.symbolTable.getAllVisibleVariables();
ArrayList<Class> classList = new ArrayList<>();
ArrayList<Object> paramList = new ArrayList<>();
for (SymbolTable.SymbolEntry entry : outerVars.values()) {
if (!entry.name().equals("@_") && !entry.decl().isEmpty()) {
// Skip field declarations - they are not closure variables
// Fields have "field" as their declaration type
if (entry.decl().equals("field")) {
continue;
}
String sigil = entry.name().substring(0, 1);
// Skip code references (subroutines/methods) - they are not captured as closure variables
if (sigil.equals("&")) {
continue;
}
// For generated methods (constructor, readers, writers), skip lexical sub/method hidden variables
// These variables (like $priv__lexmethod_123) are implementation details
// User-defined methods can capture them, but generated methods should not
if (filterLexicalMethods) {
String varName = entry.name();
if (varName.contains("__lexmethod_") || varName.contains("__lexsub_")) {
continue;
}
}
String variableName = null;
if (entry.decl().equals("our")) {
// Normalize variable name for 'our' declarations
variableName = NameNormalizer.normalizeVariableName(
entry.name().substring(1),
entry.perlPackage());
} else {
OperatorNode ast = entry.ast();
int beginId = RuntimeCode.evalBeginIds.computeIfAbsent(
ast,
k -> EmitterMethodCreator.classCounter++);
variableName = NameNormalizer.normalizeVariableName(
entry.name().substring(1),
PersistentVariable.beginPackage(beginId));
}
// Determine the class type based on the sigil
classList.add(
switch (sigil) {
case "$" -> RuntimeScalar.class;
case "%" -> RuntimeHash.class;
case "@" -> RuntimeArray.class;
default -> throw new IllegalStateException("Unexpected value: " + sigil);
}
);
// Add the corresponding global variable to the parameter list
Object capturedVar = switch (sigil) {
case "$" -> GlobalVariable.getGlobalVariable(variableName);
case "%" -> GlobalVariable.getGlobalHash(variableName);
case "@" -> GlobalVariable.getGlobalArray(variableName);
default -> throw new IllegalStateException("Unexpected value: " + sigil);
};
paramList.add(capturedVar);
// System.out.println("Capture " + entry.decl() + " " + entry.name() + " as " + variableName);
}
}
// Create a new EmitterContext for generating bytecode
// Create a filtered snapshot that excludes field declarations and code references
// Fields cause bytecode generation issues when present in the symbol table
// Code references (&) should not be captured as closure variables
ScopedSymbolTable filteredSnapshot = new ScopedSymbolTable();
filteredSnapshot.enterScope();
// Copy all visible variables except field declarations and code references
Map<Integer, SymbolTable.SymbolEntry> visibleVars = parser.ctx.symbolTable.getAllVisibleVariables();
for (SymbolTable.SymbolEntry entry : visibleVars.values()) {
// Skip field declarations when creating snapshot for bytecode generation
if (entry.decl().equals("field")) {
continue;
}
// Skip code references (subroutines) - they should not be captured as closure variables
String sigil = entry.name().substring(0, 1);
if (sigil.equals("&")) {
continue;
}
filteredSnapshot.addVariable(entry.name(), entry.decl(), entry.ast());
}
// Clone the current package
filteredSnapshot.setCurrentPackage(parser.ctx.symbolTable.getCurrentPackage(),
parser.ctx.symbolTable.currentPackageIsClass());
// Clone the current subroutine
filteredSnapshot.setCurrentSubroutine(parser.ctx.symbolTable.getCurrentSubroutine());
// Clone warning flags (critical for 'no warnings' pragmas)
filteredSnapshot.warningFlagsStack.pop(); // Remove the initial value pushed by enterScope
filteredSnapshot.warningFlagsStack.push(parser.ctx.symbolTable.warningFlagsStack.peek());
// Clone feature flags (critical for 'use feature' pragmas like refaliasing)
filteredSnapshot.featureFlagsStack.pop(); // Remove the initial value pushed by enterScope
filteredSnapshot.featureFlagsStack.push(parser.ctx.symbolTable.featureFlagsStack.peek());
// Clone strict options (critical for 'use strict' pragma)
filteredSnapshot.strictOptionsStack.pop(); // Remove the initial value pushed by enterScope
filteredSnapshot.strictOptionsStack.push(parser.ctx.symbolTable.strictOptionsStack.peek());
EmitterContext newCtx = new EmitterContext(
new JavaClassInfo(),
filteredSnapshot,
null,
null,
RuntimeContextType.RUNTIME,
true,
parser.ctx.errorUtil,
parser.ctx.compilerOptions,
new RuntimeArray()
);
// Hybrid lazy/eager compilation approach:
// - Keep lazy compilation for normal code (preserves test compatibility)
// - The Supplier tries createRuntimeCode() which handles both normal compilation and interpreter fallback
// - For InterpretedCode, we replace codeRef.value (not just code fields)
Supplier<Void> subroutineCreationTaskSupplier = () -> {
// Try unified API (returns RuntimeCode - either CompiledCode or InterpretedCode)
RuntimeCode runtimeCode =
EmitterMethodCreator.createRuntimeCode(newCtx, block, false);
try {
if (runtimeCode instanceof CompiledCode compiledCode) {
// CompiledCode path - fill in the existing placeholder
Class<?> generatedClass = compiledCode.generatedClass;
// Prepare constructor with the captured variable types
Class<?>[] parameterTypes = classList.toArray(new Class<?>[0]);
Constructor<?> constructor = generatedClass.getConstructor(parameterTypes);
// Instantiate the subroutine with the captured variables
Object[] parameters = paramList.toArray();
placeholder.codeObject = constructor.newInstance(parameters);
// Retrieve the 'apply' method from the generated class
placeholder.methodHandle = RuntimeCode.lookup.findVirtual(generatedClass, "apply", RuntimeCode.methodType);
// Set the __SUB__ instance field to codeRef
Field field = placeholder.codeObject.getClass().getDeclaredField("__SUB__");
field.set(placeholder.codeObject, codeRef);
} else if (runtimeCode instanceof InterpretedCode interpretedCode) {
// InterpretedCode path - update placeholder in-place (not replace codeRef.value)
// This is critical: hash assignments copy RuntimeScalar but share the same
// RuntimeCode value object. If we replace codeRef.value, hash copies won't see
// the update. By setting methodHandle/codeObject on the placeholder, ALL
// references (including hash copies) will see the compiled code.
// Set captured variables if there are any
if (!paramList.isEmpty()) {
Object[] parameters = paramList.toArray();
RuntimeBase[] capturedVars =
new RuntimeBase[parameters.length];
for (int i = 0; i < parameters.length; i++) {
capturedVars[i] = (RuntimeBase) parameters[i];
}
interpretedCode = interpretedCode.withCapturedVars(capturedVars);
}
// Copy metadata from the placeholder
interpretedCode.prototype = placeholder.prototype;
interpretedCode.attributes = placeholder.attributes;
interpretedCode.subName = placeholder.subName;
interpretedCode.packageName = placeholder.packageName;
// Set the __SUB__ field for self-reference
interpretedCode.__SUB__ = codeRef;
// Update placeholder in-place: set methodHandle to delegate to InterpretedCode
placeholder.methodHandle = RuntimeCode.lookup.findVirtual(
InterpretedCode.class, "apply", RuntimeCode.methodType);
placeholder.codeObject = interpretedCode;
}
} catch (Exception e) {
// Handle any exceptions during subroutine creation
throw new PerlCompilerException("Subroutine error: " + e.getMessage());
}
// Clear the compilerSupplier once done (use the captured placeholder variable)
// This prevents the Supplier from being invoked multiple times
placeholder.compilerSupplier = null;
return null;
};
// Store the supplier in the placeholder
RuntimeCode placeholderForSupplier = (RuntimeCode) codeRef.value;
placeholderForSupplier.compilerSupplier = subroutineCreationTaskSupplier;
ListNode result = new ListNode(parser.tokenIndex);
result.setAnnotation("compileTimeOnly", true);
return result;
}
private static SubroutineNode handleAnonSub(Parser parser, String subName, String prototype, List<String> attributes, BlockNode block, int currentIndex) {
// Now we check if the next token is one of the illegal characters that cannot follow a subroutine.
// These are '(', '{', and '['. If any of these follow, we throw a syntax error.
LexerToken token = peek(parser);
if (token.text.equals("(") || token.text.equals("{") || token.text.equals("[")) {
// Throw an exception indicating a syntax error.
throw new PerlCompilerException(parser.tokenIndex, "Syntax error", parser.ctx.errorUtil);
}
// Finally, we return a new 'SubroutineNode' object with the parsed data: the name, prototype, attributes, block,
// `useTryCatch` flag, and token position.
return new SubroutineNode(subName, prototype, attributes, block, false, currentIndex);
}
}