-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSubroutineParser.java
More file actions
1435 lines (1276 loc) · 77.9 KB
/
SubroutineParser.java
File metadata and controls
1435 lines (1276 loc) · 77.9 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.frontend.parser;
import org.perlonjava.app.cli.CompilerOptions;
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.debugger.DebugState;
import org.perlonjava.runtime.mro.InheritanceResolver;
import org.perlonjava.runtime.perlmodule.Universal;
import org.perlonjava.runtime.perlmodule.Warnings;
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);
if (CompilerOptions.DEBUG_ENABLED) 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);
// Propagate hiddenVarName annotation so that emitters can detect lexical subs
dollarOp.setAnnotation("hiddenVarName", hiddenVarName);
// 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.subroutine != null
|| 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();
}
if (CompilerOptions.DEBUG_ENABLED) 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.subroutine != null
|| 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 '('
// AND name is not package-qualified (no ::) - this is a function call like mycan(...)
// Allow if:
// - Marked as package (true), OR
// - Unknown (null) but NOT followed by '(' - like 'new NonExistentClass'
// - Name contains '::' (qualified names are always treated as packages in indirect syntax)
if ((isPackage != null && !isPackage) || (isPackage == null && !isKnownSub && token.text.equals("(") && !packageName.contains("::"))) {
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;
}
}
// Handle indirect object syntax with variable class: new $type $arg -> $type->new($arg)
// This is similar to the IDENTIFIER case above, but for variable class names
// Only applies when the subroutine doesn't exist (otherwise it's a function call)
if (!subExists && peek(parser).text.equals("$") && isValidIndirectMethod(subName) && !prototypeHasGlob) {
int currentIndex2 = parser.tokenIndex;
// Parse the variable that holds the class name
// Set flag to allow $var( pattern (normally a syntax error)
boolean savedIndirectObj = parser.parsingIndirectObject;
parser.parsingIndirectObject = true;
Node classVar = ParsePrimary.parsePrimary(parser);
parser.parsingIndirectObject = savedIndirectObj;
if (classVar != null) {
LexerToken nextTok = peek(parser);
// Check this isn't actually a binary operator like $type + 1
if (!(nextTok.text.equals("->") || nextTok.text.equals("=>") || INFIX_OP.contains(nextTok.text))) {
// Parse arguments for the method call
ListNode arguments;
if (nextTok.text.equals(",") || nextTok.text.equals(";") ||
nextTok.text.equals(")") || nextTok.text.equals("}") ||
nextTok.type == LexerTokenType.EOF) {
// No arguments after class variable
arguments = new ListNode(currentIndex);
} else {
// Parse remaining arguments
arguments = consumeArgsWithPrototype(parser, "@");
}
// Create method call: $classVar->method(args)
return new BinaryOperatorNode(
"->",
classVar,
new BinaryOperatorNode("(",
new OperatorNode("&",
new IdentifierNode(subName, currentIndex2),
currentIndex),
arguments, currentIndex2),
currentIndex2);
}
// Not indirect object syntax - 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("=>")) {
// Check if this looks like indirect object syntax: method $object, args
// In Perl, "release $ctx, V" means ($ctx->release(), "V") - a list of two elements
// NOT $ctx->release("V") - we don't pass additional args to the method
if (nextTok.text.equals("$")) {
// This might be indirect object syntax - only consume the object
ListNode objectArg = consumeArgsWithPrototype(parser, "$");
if (objectArg.elements.size() > 0) {
Node firstArg = objectArg.elements.get(0);
if (firstArg instanceof OperatorNode opNode && opNode.operator.equals("$")) {
Node object = firstArg;
// Create method call: object->method()
// The remaining args (after comma) are left for the outer context
Node methodCall = new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
new ListNode(currentIndex),
currentIndex);
return new BinaryOperatorNode("->", object, methodCall, currentIndex);
}
}
// Not indirect object syntax - treat the parsed arg as a regular call
return new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
objectArg,
currentIndex);
}
// If the next token is "{", this is indirect object syntax when sub doesn't exist.
// Perl parses "unknownmethod { expr } args" as "(expr)->unknownmethod(args)"
// The block is evaluated and its result becomes the method invocant.
// Any following expressions become arguments to the method call.
if (nextTok.text.equals("{")) {
// Consume the opening brace
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
// Parse the block as an expression - it will be evaluated at runtime
// to determine the invocant (class/object) for the method call
Node blockExpr = ParseBlock.parseBlock(parser);
// Consume the closing brace
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Parse any additional arguments after the block
// These become arguments to the method call
ListNode arguments = consumeArgsWithPrototype(parser, "@");
// Create method call: (block_result)->method(args)
Node methodCall = new BinaryOperatorNode("(",
new OperatorNode("&", nameNode, currentIndex),
arguments,
currentIndex);
return new BinaryOperatorNode("->", blockExpr, methodCall, currentIndex);
}
ListNode arguments = consumeArgsWithPrototype(parser, "@");
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");
}
}
// Build display name for attribute warnings
String attrSubDisplayName;
if (subName != null) {
attrSubDisplayName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
} else {
attrSubDisplayName = parser.ctx.symbolTable.getCurrentPackage() + "::__ANON__";
}
// While there are attributes (denoted by a colon ':'), we keep parsing them.
// Track prevAttrPrototype to detect ":prototype(X) : prototype(Y)" across colon-separated calls
String prevAttrProto = null;
while (peek(parser).text.equals(":")) {
String attrPrototype = consumeAttributes(parser, attributes, null, attrSubDisplayName, prevAttrProto);
if (attrPrototype != null) {
prevAttrProto = attrPrototype; // remember for "discards earlier" warning in next call
prototype = attrPrototype;
}
}
// Ensure attributes.pm is loaded when attribute syntax is used, so that
// attributes::get() is available (Perl 5 implicitly loads attributes.pm)
if (!attributes.isEmpty()) {
org.perlonjava.runtime.operators.ModuleOperators.require(new RuntimeScalar("attributes.pm"));
}
ListNode signature = null;
// Scope index for signature parameter variables (for strict vars checking).
// Entered before parseSignature() so that default value expressions can
// reference earlier parameters, and exited after the block body is parsed.
int signatureScopeIndex = -1;
// Check if the next token is an opening parenthesis '(' indicating a prototype.
if (peek(parser).text.equals("(")) {
if (parser.ctx.symbolTable.isFeatureCategoryEnabled("signatures")) {
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("Signatures feature enabled");
// Enter a scope for signature parameter variables so the parse-time
// strict vars check can find them. SignatureParser.parseParameter()
// registers each parameter directly in this scope.
signatureScopeIndex = parser.ctx.symbolTable.enterScope();
// If the signatures feature is enabled, we parse a signature.
signature = parseSignature(parser, subName);
if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("Signature AST: " + signature);
if (CompilerOptions.DEBUG_ENABLED) 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");
}
}
// Emit "Illegal character in prototype" warning for (proto) syntax
// For (proto) syntax, Perl uses "?" as the name for anonymous subs
{
String protoDisplayName;
if (subName != null) {
protoDisplayName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
} else {
protoDisplayName = "?";
}
emitIllegalProtoWarning(parser, prototype, protoDisplayName);
}
// Build display name for :prototype() warnings
// For :prototype(), Perl uses the full qualified name or __ANON__
String subDisplayName;
if (subName != null) {
subDisplayName = NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage());
} else {
subDisplayName = parser.ctx.symbolTable.getCurrentPackage() + "::__ANON__";
}
// While there are attributes after the prototype (denoted by a colon ':'), we keep parsing them.
while (peek(parser).text.equals(":")) {
String attrPrototype = consumeAttributes(parser, attributes, prototype, subDisplayName);
if (attrPrototype != null) {
prototype = attrPrototype;
}
}
}
}
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());
RuntimeScalar codeRefScalar = GlobalVariable.defineGlobalCodeRef(fullName);
RuntimeCode codeRef = (RuntimeCode) codeRefScalar.value;
// Mark as explicitly declared so *{glob}{CODE} returns this code ref
codeRef.isDeclared = true;
// Only set prototype/attributes on a forward declaration if the sub
// doesn't already have a body. Perl 5 ignores prototype changes from
// forward redeclarations of already-defined subs.
boolean hasBody = codeRef.subroutine != null || codeRef.methodHandle != null
|| codeRef.compilerSupplier != null;
if (!hasBody) {
codeRef.prototype = prototype;
codeRef.attributes = attributes;
} else {
// When redeclaring an existing sub with attributes (e.g., sub X : method),
// merge the new attributes into the existing ones. This matches Perl's behavior
// where `sub X { ... } sub X : method` adds the method attribute to X.
if (attributes != null && !attributes.isEmpty()) {
if (codeRef.attributes == null) {
codeRef.attributes = new java.util.ArrayList<>(attributes);
} else {
for (String attr : attributes) {
if (!codeRef.attributes.contains(attr)) {
codeRef.attributes.add(attr);
}
}
}
}
// Emit "Prototype mismatch" warning when redeclaring with different prototype
String oldProto = codeRef.prototype;
if (prototype != null || oldProto != null) {
String oldDisplay = oldProto == null ? ": none" : " (" + oldProto + ")";
String newDisplay = prototype == null ? "none" : "(" + prototype + ")";
String oldForCompare = oldProto == null ? "none" : "(" + oldProto + ")";
if (!oldForCompare.equals(newDisplay)) {
String location = "";
if (parser.ctx.errorUtil != null) {
int line = parser.ctx.errorUtil.getLineNumber(parser.tokenIndex);
location = " at " + parser.ctx.compilerOptions.fileName + " line " + line + ".\n";
}
String msg = "Prototype mismatch: sub " + fullName + oldDisplay + " vs " + newDisplay + location;
org.perlonjava.runtime.operators.WarnDie.warn(
new RuntimeScalar(msg), new RuntimeScalar(""));
}
}
}
// Validate attributes on forward declarations too
if (attributes != null && !attributes.isEmpty()) {
String packageToUse = parser.ctx.symbolTable.getCurrentPackage();
// For cross-package declarations like "sub Y::bar : foo", use the
// original CV's package (where the code was first compiled), not
// the syntactic target package. This matches Perl 5 behavior.
if (codeRef.packageName != null) {
packageToUse = codeRef.packageName;
} else if (subName.contains("::")) {
packageToUse = subName.substring(0, subName.lastIndexOf("::"));
}
callModifyCodeAttributes(packageToUse, codeRefScalar, attributes, parser, currentIndex);
}
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)
// Use fully qualified name so ByteCodeSourceMapper records the declaration-time
// package, not whatever package might be set inside the sub body
String qualifiedSubName = subName != null
? NameNormalizer.normalizeVariableName(subName, parser.ctx.symbolTable.getCurrentPackage())
: "";
parser.ctx.symbolTable.setCurrentSubroutine(qualifiedSubName);
// 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 {
// Exit the signature scope if we entered one
if (signatureScopeIndex >= 0) {
parser.ctx.symbolTable.exitScope(signatureScopeIndex);
}
// Restore the previous subroutine context
parser.ctx.symbolTable.setCurrentSubroutine(previousSubroutine);
parser.ctx.symbolTable.setInSubroutineBody(previousInSubroutineBody);
}
}
static String consumeAttributes(Parser parser, List<String> attributes) {
return consumeAttributes(parser, attributes, null, null, null);
}
/**
* Parse attributes after a colon. Returns a prototype string if :prototype(...) is found.
*
* @param parser The parser
* @param attributes List to accumulate parsed attribute strings
* @param priorPrototype The prototype set by (proto) syntax, for "overridden" warning (may be null)
* @param subDisplayName The sub name for warning messages (may be null for anon subs)
* @return The prototype string from :prototype(...), or null if not found
*/
static String consumeAttributes(Parser parser, List<String> attributes, String priorPrototype, String subDisplayName) {
return consumeAttributes(parser, attributes, priorPrototype, subDisplayName, null);
}
/**
* Parse attributes after a colon. Returns a prototype string if :prototype(...) is found.
*
* @param parser The parser
* @param attributes List to accumulate parsed attribute strings
* @param parenPrototype The prototype from (proto) syntax, for "overridden" warning (may be null)
* @param subDisplayName The sub name for warning messages (may be null for anon subs)
* @param prevAttrPrototype Prototype from a previous :prototype(...) call, for "discards" warning (may be null)
* @return The prototype string from :prototype(...), or null if not found
*/
static String consumeAttributes(Parser parser, List<String> attributes, String parenPrototype,
String subDisplayName, String prevAttrPrototype) {
// 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;
// Loop to handle space-separated attributes after a single colon
// e.g., `: locked method` parses both `locked` and `method`
while (peek(parser).type == LexerTokenType.IDENTIFIER) {
String attrString = TokenUtils.consume(parser, LexerTokenType.IDENTIFIER).text;
if (parser.tokens.get(parser.tokenIndex).text.equals("(")) {
String argString;
try {
// Parse the parenthesized parameter using raw string parsing.
// Unlike q(), Perl's attribute parameter parsing preserves backslashes:
// :Foo(\() gives parameter \( not ( — backslash is kept literally.
StringParser.ParsedString rawStr = StringParser.parseRawStrings(
parser, parser.ctx, parser.tokens, parser.tokenIndex, 1);
parser.tokenIndex = rawStr.next;
argString = rawStr.buffers.getFirst();
} catch (PerlCompilerException e) {
// Rethrow with Perl-compatible message for unterminated parens
if (e.getMessage() != null && e.getMessage().contains("Can't find string terminator")) {
String loc = parser.ctx.errorUtil.warningLocation(parser.tokenIndex);
throw new PerlCompilerException(
"Unterminated attribute parameter in attribute list" + loc + ".\n");
}
throw e;
}
if (attrString.equals("prototype")) {
// :prototype($)
// Validate prototype characters first (Perl emits this before "overridden")
emitIllegalProtoWarning(parser, argString, subDisplayName);
// Emit "Prototype overridden" warning if prior prototype was set from (proto) syntax
if (parenPrototype != null && subDisplayName != null) {
String msg = "Prototype '" + parenPrototype + "' overridden by attribute 'prototype("
+ argString + ")' in " + subDisplayName;
String loc = parser.ctx.errorUtil.warningLocation(parser.tokenIndex);
org.perlonjava.runtime.operators.WarnDie.warn(
new RuntimeScalar(msg), new RuntimeScalar(loc));
}
// Emit "discards earlier prototype" warning if :prototype was already set
// (either in this same call or from a previous :prototype() call)
String existingAttrProto = prototype != null ? prototype : prevAttrPrototype;
if (existingAttrProto != null && subDisplayName != null) {
String msg = "Attribute prototype(" + argString
+ ") discards earlier prototype attribute in same sub";
String loc = parser.ctx.errorUtil.warningLocation(parser.tokenIndex);
org.perlonjava.runtime.operators.WarnDie.warn(
new RuntimeScalar(msg), new RuntimeScalar(loc));
}
prototype = argString;
}
attrString += "(" + argString + ")";
}
// Consume the attribute name (an identifier) and add it to the attributes list.
attributes.add(attrString);
}
// Check for invalid separator characters after attributes
// Valid separators are: colon (:), semicolon (;), opening/closing brace ({, }), assignment (=), EOF
if (!attributes.isEmpty()) {
LexerToken nextToken = peek(parser);
if (nextToken.type == LexerTokenType.OPERATOR) {
String t = nextToken.text;
if (!t.equals(":") && !t.equals(";") && !t.equals("{") && !t.equals("}") && !t.equals("=")
&& !t.equals("(") && !t.equals(",") && !t.equals(")")
&& !t.equals("$") && !t.equals("@") && !t.equals("%")) {
// Check for :: (double colon is invalid separator in attr list)
if (t.equals("::") || (t.length() == 1 && !Character.isWhitespace(t.charAt(0)))) {
throw new PerlCompilerException(parser.tokenIndex,
"Invalid separator character '" + t.charAt(0) + "' in attribute list",
parser.ctx.errorUtil);
}
}
}
}
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.defineGlobalCodeRef(fullName);
InheritanceResolver.invalidateCache();
// Check if we're redefining an existing subroutine that already has code.
// In that case, create a NEW RuntimeCode so that saved code references
// (from \&sub or can()) continue pointing to the old implementation.
// This matches Perl's behavior where:
// my $orig = \&foo; sub foo { "new" }; $orig->() returns "old"
boolean isRedefinition = false;
String oldPrototype = null;
boolean isConstantSub = false;
boolean isBuiltinSub = false; // Java-registered (XS-like) methods don't trigger redefine warnings
if (codeRef.value instanceof RuntimeCode existingCode) {
// Check if the existing code has actual implementation OR pending compilation
// compilerSupplier != null means there's a lazy definition waiting to be compiled
isRedefinition = existingCode.subroutine != null
|| existingCode.methodHandle != null
|| existingCode.codeObject != null
|| existingCode.compilerSupplier != null;
if (isRedefinition) {
oldPrototype = existingCode.prototype;
// A constant sub has empty prototype "()" - detect for "Constant subroutine" warning
isConstantSub = "".equals(oldPrototype);
// Java-registered methods (via registerMethod) have isStatic=true and methodHandle set
isBuiltinSub = existingCode.isStatic && existingCode.methodHandle != null;
}
}
// Emit "Prototype mismatch" and "Subroutine redefined" warnings
// Skip warnings for Java-registered (XS-like) built-in methods being overridden by Perl stubs
if (isRedefinition && block != null && !isBuiltinSub) {
String location = "";
if (parser.ctx.errorUtil != null) {
int line = parser.ctx.errorUtil.getLineNumber(parser.tokenIndex);
location = " at " + parser.ctx.compilerOptions.fileName + " line " + line + ".\n";
}
// Prototype mismatch is a default warning (always on unless explicitly disabled)
boolean dollarW = GlobalVariable.getGlobalVariable("main::" + Character.toString('W' - 'A' + 1)).getBoolean();
{
// Perl format: "sub NAME: none vs (new)" or "sub NAME (old) vs none"
// When prototype is null, display as ": none"; when defined, display as " (proto)"
String oldDisplay = oldPrototype == null ? ": none" : " (" + oldPrototype + ")";
String newDisplay = prototype == null ? "none" : "(" + prototype + ")";
String oldForCompare = oldPrototype == null ? "none" : "(" + oldPrototype + ")";
if (!oldForCompare.equals(newDisplay)) {
String msg = "Prototype mismatch: sub " + fullName + oldDisplay + " vs " + newDisplay + location;
org.perlonjava.runtime.operators.WarnDie.warn(
new RuntimeScalar(msg), new RuntimeScalar(""));