-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStatementParser.java
More file actions
968 lines (838 loc) · 44.4 KB
/
StatementParser.java
File metadata and controls
968 lines (838 loc) · 44.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
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
package org.perlonjava.frontend.parser;
import org.perlonjava.backend.jvm.EmitterContext;
import org.perlonjava.core.Configuration;
import org.perlonjava.frontend.analysis.ExtractValueVisitor;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.lexer.LexerTokenType;
import org.perlonjava.runtime.mro.InheritanceResolver;
import org.perlonjava.runtime.operators.ModuleOperators;
import org.perlonjava.runtime.operators.VersionHelper;
import org.perlonjava.runtime.perlmodule.Universal;
import org.perlonjava.runtime.runtimetypes.*;
import java.util.ArrayList;
import java.util.List;
import static org.perlonjava.frontend.parser.NumberParser.parseNumber;
import static org.perlonjava.frontend.parser.ParserNodeUtils.atUnderscoreArgs;
import static org.perlonjava.frontend.parser.ParserNodeUtils.scalarUnderscore;
import static org.perlonjava.frontend.parser.SpecialBlockParser.getCurrentScope;
import static org.perlonjava.frontend.parser.SpecialBlockParser.runSpecialBlock;
import static org.perlonjava.frontend.parser.SpecialBlockParser.setCurrentScope;
import static org.perlonjava.frontend.parser.StringParser.parseVstring;
import static org.perlonjava.runtime.operators.VersionHelper.normalizeVersion;
import static org.perlonjava.runtime.perlmodule.Feature.featureManager;
import static org.perlonjava.runtime.perlmodule.Strict.useStrict;
import static org.perlonjava.runtime.perlmodule.Warnings.useWarnings;
import static org.perlonjava.runtime.runtimetypes.GlobalVariable.packageExistsCache;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarCache.scalarUndef;
/**
* The StatementParser class is responsible for parsing various types of statements
* in the Perl-like language, including while loops, for loops, if statements,
* use declarations, and package declarations.
*/
public class StatementParser {
/**
* Parses a while or until statement.
*
* @param parser The Parser instance
* @param label The label for the loop (can be null)
* @return A For3Node representing the while/until loop
*/
public static Node parseWhileStatement(Parser parser, String label) {
LexerToken operator = TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "while" "until"
int scopeIndex = parser.ctx.symbolTable.enterScope();
Node condition;
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
if (TokenUtils.peek(parser).text.equals(")")) {
// Special case for `while ()` to become `while (1)`
condition = new NumberNode("1", parser.tokenIndex);
} else {
condition = parser.parseExpression(0);
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
// Parse the body of the loop
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node body = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
Node continueNode = null;
if (TokenUtils.peek(parser).text.equals("continue")) {
TokenUtils.consume(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
continueNode = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
}
if (operator.text.equals("until")) {
condition = new OperatorNode("not", condition, condition.getIndex());
}
parser.ctx.symbolTable.exitScope(scopeIndex);
return new For3Node(label, true, null,
condition, null, body, continueNode, false, false, parser.tokenIndex);
}
/**
* Parses a for or foreach statement.
*
* @param parser The Parser instance
* @param label The label for the loop (can be null)
* @return A For1Node or For3Node representing the for/foreach loop
*/
public static Node parseForStatement(Parser parser, String label) {
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "for" or "foreach"
int scopeIndex = parser.ctx.symbolTable.enterScope();
// Parse optional loop variable
Node varNode = null;
LexerToken token = TokenUtils.peek(parser); // "my" "$" "(" "CORE::my"
if (token.type == LexerTokenType.IDENTIFIER &&
(token.text.equals("my") || token.text.equals("our") || token.text.equals("state"))) {
// Ensure `for my $x (...)` is parsed as a variable declaration, not as `$x`.
// This is critical for strict-vars correctness inside the loop body.
int declIndex = parser.tokenIndex;
parser.parsingForLoopVariable = true;
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER);
varNode = OperatorParser.parseVariableDeclaration(parser, token.text, declIndex);
parser.parsingForLoopVariable = false;
} else if (token.type == LexerTokenType.IDENTIFIER && token.text.equals("CORE")
&& parser.tokens.get(parser.tokenIndex).text.equals("CORE")
&& parser.tokens.size() > parser.tokenIndex + 1
&& parser.tokens.get(parser.tokenIndex + 1).text.equals("::")) {
// Handle CORE::my/our/state
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // CORE
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "::");
LexerToken coreOp = TokenUtils.peek(parser);
if (coreOp.type == LexerTokenType.IDENTIFIER &&
(coreOp.text.equals("my") || coreOp.text.equals("our") || coreOp.text.equals("state"))) {
int declIndex = parser.tokenIndex;
parser.parsingForLoopVariable = true;
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER);
varNode = OperatorParser.parseVariableDeclaration(parser, coreOp.text, declIndex);
parser.parsingForLoopVariable = false;
} else {
parser.parsingForLoopVariable = true;
varNode = ParsePrimary.parsePrimary(parser);
parser.parsingForLoopVariable = false;
}
} else if (token.text.equals("$")) {
parser.parsingForLoopVariable = true;
varNode = ParsePrimary.parsePrimary(parser);
parser.parsingForLoopVariable = false;
} else if (token.text.equals("\\")) {
// Handle reference loop variables: for \$x (...), for \@x (...), for \%x (...)
// We need to parse the reference manually to avoid parsePrimary trying to parse
// the following (...) as a function call or hash subscript.
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "\\");
parser.parsingForLoopVariable = true;
Node operand = ParsePrimary.parsePrimary(parser);
parser.parsingForLoopVariable = false;
varNode = new OperatorNode("\\", operand, parser.tokenIndex);
}
// If we didn't parse a loop variable, Perl expects the '(' of the for(..) header next.
// When something else appears (e.g. a bare identifier), perl5 reports:
// Missing $ on loop variable ...
if (varNode == null) {
LexerToken afterVar = TokenUtils.peek(parser);
if (!afterVar.text.equals("(")) {
parser.throwCleanError("Missing $ on loop variable " + afterVar.text);
}
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
// Parse the initialization part
Node initialization = null;
if (!TokenUtils.peek(parser).text.equals(";")) {
if (TokenUtils.peek(parser).text.equals(")")) {
initialization = new ListNode(parser.tokenIndex);
} else {
initialization = parser.parseExpression(0);
}
token = TokenUtils.peek(parser);
if (token.text.equals(")")) {
// 1-argument for loop (foreach-like)
Node node = parseOneArgumentForLoop(parser, label, varNode, initialization);
parser.ctx.symbolTable.exitScope(scopeIndex);
return node;
}
}
// 3-argument for loop
Node node = parseThreeArgumentForLoop(parser, label, varNode, initialization);
parser.ctx.symbolTable.exitScope(scopeIndex);
return node;
}
/**
* Helper method to parse a one-argument for loop (foreach-like).
*/
private static Node parseOneArgumentForLoop(Parser parser, String label, Node varNode, Node initialization) {
TokenUtils.consume(parser); // Consume ")"
// Parse the body of the loop
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node body = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Parse optional continue block
Node continueNode = null;
if (TokenUtils.peek(parser).text.equals("continue")) {
TokenUtils.consume(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
continueNode = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
}
// Use $_ as the default loop variable if not specified
if (varNode == null) {
varNode = scalarUnderscore(parser); // $_
}
if (varNode instanceof OperatorNode operatorNode && operatorNode.operator.equals("$")) {
if (operatorNode.operand instanceof IdentifierNode identifierNode) {
String identifier = identifierNode.name;
int varIndex = parser.ctx.symbolTable.getVariableIndex("$" + identifier);
if (varIndex == -1) {
// Is global variable
String fullName = NameNormalizer.normalizeVariableName(identifier, parser.ctx.symbolTable.getCurrentPackage());
identifierNode.name = fullName;
// Mark the For1Node so the emitter knows to evaluate list before local
// This ensures list is evaluated while $_ still has its parent scope value
For1Node forNode = new For1Node(label, true, varNode, initialization, body, continueNode, parser.tokenIndex);
forNode.needsArrayOfAlias = true; // Signal emitter to use array of aliases
return new BlockNode(
List.of(
new OperatorNode("local", varNode, parser.tokenIndex),
forNode
), parser.tokenIndex);
}
}
}
return new For1Node(label, true, varNode, initialization, body, continueNode, parser.tokenIndex);
}
/**
* Helper method to parse a three-argument for loop.
*/
private static Node parseThreeArgumentForLoop(Parser parser, String label, Node varNode, Node initialization) {
if (varNode != null) {
throw new PerlCompilerException(parser.tokenIndex, "Syntax error", parser.ctx.errorUtil);
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ";");
// Parse the condition part
Node condition = null;
if (!TokenUtils.peek(parser).text.equals(";")) {
condition = parser.parseExpression(0);
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ";");
// Parse the increment part
Node increment = null;
if (!TokenUtils.peek(parser).text.equals(")")) {
increment = parser.parseExpression(0);
}
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
// Parse the body of the loop
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node body = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// 3-argument for doesn't have a continue block
return new For3Node(label, true, initialization,
condition, increment, body, null, false, false, parser.tokenIndex);
}
/**
* Parses an if, unless, or elsif statement.
*
* @param parser The Parser instance
* @return An IfNode representing the if/unless/elsif statement
*/
public static Node parseIfStatement(Parser parser) {
LexerToken operator = TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "if", "unless", "elsif"
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
Node condition = parser.parseExpression(0);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
BlockNode thenBranch = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
Node elseBranch = null;
LexerToken token = TokenUtils.peek(parser);
if (token.text.equals("else")) {
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "else"
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
elseBranch = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
} else if (token.text.equals("elsif")) {
elseBranch = parseIfStatement(parser);
}
// Use a macro to emulate Test::More SKIP blocks
TestMoreHelper.handleSkipTest(parser, thenBranch);
return new IfNode(operator.text, condition, thenBranch, elseBranch, parser.tokenIndex);
}
/**
* Parses a try-catch-finally statement.
*
* @param parser The Parser instance
* @return A TryNode representing the try-catch-finally statement
*/
public static Node parseTryStatement(Parser parser) {
int index = parser.tokenIndex;
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "try"
// Parse the try block
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node tryBlock = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Parse the catch block
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "catch"
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
Node catchParameter = parser.parseExpression(0); // Parse the exception variable
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
Node catchBlock = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Parse the optional finally block
Node finallyBlock = null;
if (TokenUtils.peek(parser).text.equals("finally")) {
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "finally"
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
finallyBlock = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
}
return new BinaryOperatorNode("->",
new SubroutineNode(null, null, null,
new BlockNode(List.of(
new TryNode(tryBlock, catchParameter, catchBlock, finallyBlock, index)), index),
false, index),
atUnderscoreArgs(parser),
index);
}
/**
* Parses a when statement (part of given/when feature from Perl 5.10).
* <p>
* when(COND) { BLOCK } becomes: if ($_ ~~ COND) { BLOCK }
*
* @param parser The Parser instance
* @return A Node representing the when statement as an if statement with smartmatch
*/
public static Node parseWhenStatement(Parser parser) {
int index = parser.tokenIndex;
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "when"
// Parse the when condition (can be parenthesized or not)
Node whenCondition;
if (TokenUtils.peek(parser).text.equals("(")) {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
whenCondition = parser.parseExpression(0);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
} else {
whenCondition = parser.parseExpression(0);
}
// Parse the when block
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
BlockNode whenBlock = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
// Create smartmatch condition: $_ ~~ whenCondition
Node dollarUnderscore = new OperatorNode("$",
new IdentifierNode("_", index),
index);
Node smartmatchCondition = new BinaryOperatorNode("~~",
dollarUnderscore,
whenCondition,
index);
// Return as an if statement
return new IfNode("if", smartmatchCondition, whenBlock, null, index);
}
/**
* Parses a default statement (part of given/when feature from Perl 5.10).
* <p>
* default { BLOCK } just returns the BLOCK (it's like an else clause)
*
* @param parser The Parser instance
* @return A BlockNode representing the default block
*/
public static Node parseDefaultStatement(Parser parser) {
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "default"
// Parse the default block
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
BlockNode defaultBlock = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
return defaultBlock;
}
/**
* Parses a given-when statement (deprecated feature from Perl 5.10).
* <p>
* Transforms:
* given(EXPR) { when(COND1) { BLOCK1 } when(COND2) { BLOCK2 } default { BLOCK3 } }
* <p>
* Into AST equivalent of:
* do { $_ = EXPR; when/default statements }
* <p>
* Where when/default are parsed as regular statements that check $_.
* This is a pure AST transformation - no special emitter code needed.
*
* @param parser The Parser instance
* @return A Node representing the given-when statement as transformed AST
*/
public static Node parseGivenStatement(Parser parser) {
int index = parser.tokenIndex;
TokenUtils.consume(parser, LexerTokenType.IDENTIFIER); // "given"
int scopeIndex = parser.ctx.symbolTable.enterScope();
// Parse the condition and assign to $_
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
Node condition = parser.parseExpression(0);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
// Parse the block containing when/default statements
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
// Parse the entire block content as a normal block
// This handles regular statements as well as when/default
BlockNode blockContent = ParseBlock.parseBlock(parser);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
parser.ctx.symbolTable.exitScope(scopeIndex);
// Create the complete block: { $_ = EXPR; blockContent }
List<Node> statements = new ArrayList<>();
// $_ = condition (use proper $_ structure)
Node dollarUnderscore = new OperatorNode("$",
new IdentifierNode("_", index),
index);
statements.add(new BinaryOperatorNode("=",
dollarUnderscore,
condition,
index));
// Add all the statements from the block
statements.addAll(blockContent.elements);
return new BlockNode(statements, index, parser);
}
/**
* Parses a use or no declaration.
*
* @param parser The Parser instance
* @param token The current token
* @return A ListNode representing the use/no declaration
*/
public static Node parseUseDeclaration(Parser parser, LexerToken token) {
EmitterContext ctx = parser.ctx;
ctx.logDebug("use: " + token.text);
boolean isNoDeclaration = token.text.equals("no");
TokenUtils.consume(parser); // "use"
token = TokenUtils.peek(parser);
String fullName = null;
String packageName = null;
if (token.type != LexerTokenType.NUMBER && !token.text.matches("^v\\d+")) {
if (token.type != LexerTokenType.IDENTIFIER) {
// Not a valid module name token
throw new PerlCompilerException(parser.tokenIndex, "syntax error", parser.ctx.errorUtil);
}
ctx.logDebug("use module: " + token);
packageName = IdentifierParser.parseSubroutineIdentifier(parser);
if (packageName == null) {
throw new PerlCompilerException(parser.tokenIndex, "syntax error", parser.ctx.errorUtil);
}
fullName = NameNormalizer.moduleToFilename(packageName);
ctx.logDebug("use fullName: " + fullName);
}
// Parse Version string
int currentIndex = parser.tokenIndex;
RuntimeScalar versionScalar = scalarUndef;
Node versionNode = parseOptionalPackageVersion(parser);
if (versionNode != null) {
if (TokenUtils.peek(parser).text.equals(",")) {
// no comma allowed after version
versionNode = null;
parser.tokenIndex = currentIndex; // backtrack
}
}
if (versionNode != null) {
parser.ctx.logDebug("use version: " + versionNode + " next:" + TokenUtils.peek(parser));
// Extract version string using ExtractValueVisitor
RuntimeList versionValues = ExtractValueVisitor.getValues(versionNode);
if (!versionValues.isEmpty()) {
// String versionString = versionValues.elements.getFirst().toString();
// parser.ctx.logDebug("use version String: " + printable(versionString));
versionScalar = versionValues.getFirst();
if (packageName == null) {
parser.ctx.logDebug("use version: check Perl version");
VersionHelper.compareVersion(
new RuntimeScalar(Configuration.perlVersion),
versionScalar,
"Perl");
// Enable/disable features based on Perl version
setCurrentScope(parser.ctx.symbolTable);
// ":5.34"
String[] parts = normalizeVersion(versionScalar).split("\\.");
int majorVersion = Integer.parseInt(parts[0]);
int minorVersion = Integer.parseInt(parts[1]);
// If the minor version is odd, increment it to make it the next even version
if (minorVersion % 2 != 0) {
minorVersion++;
}
String closestVersion = minorVersion < 10
? ":default"
: ":" + majorVersion + "." + minorVersion;
featureManager.enableFeatureBundle(closestVersion);
if (minorVersion >= 12) {
// If the specified Perl version is 5.12 or higher,
// strictures are enabled lexically.
useStrict(new RuntimeArray(
new RuntimeScalar("strict")), RuntimeContextType.VOID);
}
if (minorVersion >= 35) {
// If the specified Perl version is 5.35.0 or higher,
// warnings are enabled.
useWarnings(new RuntimeArray(
new RuntimeScalar("warnings"),
new RuntimeScalar("all")), RuntimeContextType.VOID);
// Copy warning flags to ALL levels of the parser's symbol table
// This matches what's done after import() for 'use warnings'
java.util.BitSet currentWarnings = getCurrentScope().warningFlagsStack.peek();
for (int i = 0; i < parser.ctx.symbolTable.warningFlagsStack.size(); i++) {
parser.ctx.symbolTable.warningFlagsStack.set(i, (java.util.BitSet) currentWarnings.clone());
}
}
}
}
if (packageName == null) {
// `use` statement can terminate after Version.
// Do not early-return here; we still want to consume an optional statement terminator
// and return a CompilerFlagNode so lexical flag changes are applied during codegen.
}
}
// Parse the parameter list
boolean hasParentheses = TokenUtils.peek(parser).text.equals("(");
Node list = ListParser.parseZeroOrMoreList(parser, 0, false, false, false, false);
ctx.logDebug("Use statement list hasParentheses:" + hasParentheses + " ast:" + list);
StatementResolver.parseStatementTerminator(parser);
if (fullName != null) {
// execute the statement immediately, using:
// `require "fullName.pm"`
// Setup the caller stack
CallerStack.push(
ctx.symbolTable.getCurrentPackage(),
ctx.compilerOptions.fileName,
ctx.errorUtil.getLineNumber(parser.tokenIndex));
try {
ctx.logDebug("Use statement: " + fullName + " called from " + CallerStack.peek(0));
// execute 'require(fullName)'
RuntimeScalar ret = ModuleOperators.require(new RuntimeScalar(fullName));
ctx.logDebug("Use statement return: " + ret);
if (versionNode != null) {
// check module version
parser.ctx.logDebug("use version: check module version");
RuntimeArray args = new RuntimeArray();
RuntimeArray.push(args, new RuntimeScalar(packageName));
RuntimeArray.push(args, versionScalar);
Universal.VERSION(args, RuntimeContextType.SCALAR);
}
// call Module->import( LIST )
// or Module->unimport( LIST )
// Execute the argument list immediately
RuntimeList args = runSpecialBlock(parser, "BEGIN", list);
ctx.logDebug("Use statement list: " + args);
if (hasParentheses && args.isEmpty()) {
// do not import
} else {
// fetch the method using `can` operator
String importMethod = isNoDeclaration ? "unimport" : "import";
RuntimeArray canArgs = new RuntimeArray();
RuntimeArray.push(canArgs, new RuntimeScalar(packageName));
RuntimeArray.push(canArgs, new RuntimeScalar(importMethod));
RuntimeList codeList = null;
InheritanceResolver.autoloadEnabled = false;
try {
codeList = Universal.can(canArgs, RuntimeContextType.SCALAR);
} finally {
InheritanceResolver.autoloadEnabled = true;
}
ctx.logDebug("Use can(" + packageName + ", " + importMethod + "): " + codeList);
if (codeList.size() == 1) {
RuntimeScalar code = codeList.getFirst();
if (code.getBoolean()) {
// call the method
ctx.logDebug("Use call : " + importMethod + "(" + args + ")");
RuntimeArray importArgs = args.getArrayOfAlias();
RuntimeArray.unshift(importArgs, new RuntimeScalar(packageName));
setCurrentScope(parser.ctx.symbolTable);
RuntimeCode.apply(code, importArgs, RuntimeContextType.SCALAR);
}
}
}
} finally {
// restore the caller stack
CallerStack.pop();
}
}
// return the current compiler flags (marked as compile-time only to skip DEBUG opcodes)
CompilerFlagNode result = new CompilerFlagNode(
(java.util.BitSet) ctx.symbolTable.warningFlagsStack.getLast().clone(),
ctx.symbolTable.featureFlagsStack.getLast(),
ctx.symbolTable.strictOptionsStack.getLast(),
parser.tokenIndex);
result.setAnnotation("compileTimeOnly", true);
return result;
}
/**
* Parses a package declaration.
*
* @param parser The Parser instance
* @param token The current token
* @return An OperatorNode or BlockNode representing the package declaration
*/
public static Node parsePackageDeclaration(Parser parser, LexerToken token) {
TokenUtils.consume(parser);
String packageName = IdentifierParser.parseSubroutineIdentifier(parser);
if (packageName == null) {
throw new PerlCompilerException(parser.tokenIndex, "Syntax error", parser.ctx.errorUtil);
}
// Remember that this package exists
packageExistsCache.put(packageName, true);
boolean isClass = token.text.equals("class");
IdentifierNode nameNode = new IdentifierNode(packageName, parser.tokenIndex);
OperatorNode packageNode = new OperatorNode(token.text, nameNode, parser.tokenIndex);
packageNode.setAnnotation("isClass", isClass);
// Register this as a Perl 5.38+ class for proper stringification
if (isClass) {
ClassRegistry.registerClass(packageName);
}
// Parse Version string and store it in the symbol table
Node version = parseOptionalPackageVersion(parser);
parser.ctx.logDebug("package version: " + version);
if (version != null) {
// Extract the actual version value from the node
String versionString = null;
if (version instanceof NumberNode) {
versionString = ((NumberNode) version).value;
} else if (version instanceof StringNode) {
versionString = ((StringNode) version).value;
}
// Store the version in the symbol table for this package
if (versionString != null) {
parser.ctx.symbolTable.setPackageVersion(packageName, versionString);
}
}
// Parse class attributes (e.g., :isa(ParentClass))
if (isClass) {
parseClassAttributes(parser, packageNode);
}
BlockNode block = parseOptionalPackageBlock(parser, nameNode, packageNode);
if (block != null) return block;
StatementResolver.parseStatementTerminator(parser);
parser.ctx.symbolTable.setCurrentPackage(nameNode.name, isClass);
// For unit class syntax (class Name;), we need to generate a minimal class
// with just a constructor, even though there's no block
if (isClass) {
// Create an empty block for the class
BlockNode emptyBlock = new BlockNode(new ArrayList<>(), parser.tokenIndex);
emptyBlock.elements.add(packageNode);
// Transform it to generate constructor
emptyBlock = ClassTransformer.transformClassBlock(emptyBlock, nameNode.name, parser);
// Register deferred methods (constructor and any accessors)
// Same logic as in parseOptionalPackageBlock
// Register user-defined methods (none for unit class)
@SuppressWarnings("unchecked")
List<SubroutineNode> deferredMethods = (List<SubroutineNode>) emptyBlock.getAnnotation("deferredMethods");
if (deferredMethods != null) {
for (SubroutineNode method : deferredMethods) {
SubroutineParser.handleNamedSubWithFilter(parser, method.name, method.prototype,
method.attributes, (BlockNode) method.block, false, null);
}
}
// Register generated methods (constructor and accessors)
SubroutineNode deferredConstructor = (SubroutineNode) emptyBlock.getAnnotation("deferredConstructor");
if (deferredConstructor != null) {
SubroutineParser.handleNamedSubWithFilter(parser, deferredConstructor.name, deferredConstructor.prototype,
deferredConstructor.attributes, (BlockNode) deferredConstructor.block, true, null);
}
@SuppressWarnings("unchecked")
List<SubroutineNode> deferredAccessors = (List<SubroutineNode>) emptyBlock.getAnnotation("deferredAccessors");
if (deferredAccessors != null) {
for (SubroutineNode accessor : deferredAccessors) {
SubroutineParser.handleNamedSubWithFilter(parser, accessor.name, accessor.prototype,
accessor.attributes, (BlockNode) accessor.block, true, null);
}
}
return emptyBlock;
}
return packageNode;
}
/**
* Parses class attributes like :isa(ParentClass)
*
* @param parser The Parser instance
* @param packageNode The OperatorNode representing the class declaration
*/
private static void parseClassAttributes(Parser parser, OperatorNode packageNode) {
LexerToken token = TokenUtils.peek(parser);
// Check for :isa attribute
if (token.text.equals(":")) {
TokenUtils.consume(parser); // consume ':'
token = TokenUtils.peek(parser);
if (token.text.equals("isa")) {
TokenUtils.consume(parser); // consume 'isa'
// Expect opening parenthesis
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
// Parse parent class name
token = TokenUtils.peek(parser);
if (token.type != LexerTokenType.IDENTIFIER) {
throw new PerlCompilerException(parser.tokenIndex,
"Expected class name after :isa(", parser.ctx.errorUtil);
}
String parentClass = TokenUtils.consume(parser).text;
// Handle qualified class names (e.g., Parent::Class)
while (TokenUtils.peek(parser).text.equals("::")) {
TokenUtils.consume(parser); // consume '::'
token = TokenUtils.peek(parser);
if (token.type != LexerTokenType.IDENTIFIER) {
throw new PerlCompilerException(parser.tokenIndex,
"Expected identifier after '::'", parser.ctx.errorUtil);
}
parentClass += "::" + TokenUtils.consume(parser).text;
}
// Store parent class in annotations
packageNode.setAnnotation("parentClass", parentClass);
// Register in FieldRegistry for field inheritance tracking
// We'll register this after we know the class name
// Handle optional version number using the existing version parser
// This properly handles v-strings, floating point versions, etc.
Node versionNode = parseOptionalPackageVersion(parser);
if (versionNode != null) {
// System.err.println("DEBUG: :isa() has version requirement");
// Store version node for version checking
packageNode.setAnnotation("parentVersion", versionNode);
// Use the same approach as parseUseDeclaration for version checking
// Extract version value using ExtractValueVisitor
RuntimeList versionValues = ExtractValueVisitor.getValues(versionNode);
// System.err.println("DEBUG: ExtractValueVisitor returned " + versionValues.size() + " values");
if (!versionValues.isEmpty()) {
RuntimeScalar requiredVersion = versionValues.getFirst();
// System.err.println("DEBUG: Required version for " + parentClass + ": " + requiredVersion);
// Get the actual version of the parent class from the symbol table
String parentVersionStr = parser.ctx.symbolTable.getPackageVersion(parentClass);
// System.err.println("DEBUG: Parent " + parentClass + " version from symbol table: " + parentVersionStr);
if (parentVersionStr != null) {
// Use VersionHelper.compareVersion for consistent version checking
// This handles v-strings, underscores, and all version formats properly
RuntimeScalar parentVersion = new RuntimeScalar(parentVersionStr);
// System.err.println("DEBUG: Comparing versions - has: " + parentVersion + ", wants: " + requiredVersion);
// This will throw the appropriate exception if version is insufficient
VersionHelper.compareVersion(parentVersion, requiredVersion, parentClass);
// System.err.println("DEBUG: Version check passed!");
} else {
// System.err.println("DEBUG: No version found for parent class " + parentClass);
}
} else {
// System.err.println("DEBUG: ExtractValueVisitor returned empty list");
}
} else {
// System.err.println("DEBUG: :isa() has no version requirement for " + parentClass);
}
// Expect closing parenthesis
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
} else {
// Unknown attribute - throw error for now
throw new PerlCompilerException(parser.tokenIndex,
"Unknown class attribute: :" + token.text, parser.ctx.errorUtil);
}
}
}
/**
* Parses an optional package block.
*
* @param parser The Parser instance
* @param nameNode The IdentifierNode representing the package name
* @param packageNode The OperatorNode representing the package declaration
* @return A BlockNode if a block is present, null otherwise
*/
public static BlockNode parseOptionalPackageBlock(Parser parser, IdentifierNode nameNode, OperatorNode packageNode) {
LexerToken token;
token = TokenUtils.peek(parser);
if (token.type == LexerTokenType.OPERATOR && token.text.equals("{")) {
// package NAME BLOCK
//
// Two-scope design:
// 1. Outer scope (scopeIndex): Created here for the package/class block
// 2. Inner scope (blockScopeIndex): Created by ParseBlock for the block contents
//
// For packages: Both scopes exit normally during parseBlock
// For classes: Inner scope exit is delayed until after ClassTransformer
// so methods can capture class-level lexical variables
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "{");
int scopeIndex = parser.ctx.symbolTable.enterScope();
boolean isClass = packageNode.getBooleanAnnotation("isClass");
// Save the current package and class state to restore later
String previousPackage = parser.ctx.symbolTable.getCurrentPackage();
boolean previousPackageIsClass = parser.ctx.symbolTable.currentPackageIsClass();
parser.ctx.symbolTable.setCurrentPackage(nameNode.name, isClass);
// Set flag if we're entering a class block
boolean wasInClassBlock = parser.isInClassBlock;
if (isClass) {
parser.isInClassBlock = true;
}
BlockNode block;
int blockScopeIndex;
try {
if (isClass) {
// For classes, delay scope exit until after ClassTransformer runs
// This allows methods to capture class-level lexical variables
ParseBlock.BlockWithScope result = ParseBlock.parseBlock(parser, false);
block = result.block();
blockScopeIndex = result.scopeIndex();
} else {
// For packages, exit scope normally
block = ParseBlock.parseBlock(parser);
blockScopeIndex = -1; // Already exited
}
} finally {
// Always restore the isInClassBlock flag
parser.isInClassBlock = wasInClassBlock;
}
// Mark as scoped so BytecodeCompiler emits PUSH_PACKAGE (not SET_PACKAGE)
// and BlockNode.visit() brackets the block with GET_LOCAL_LEVEL/POP_LOCAL_LEVEL
// to restore the runtime package after the block exits.
packageNode.setAnnotation("isScoped", Boolean.TRUE);
// Insert packageNode as first statement in block
block.elements.addFirst(packageNode);
// Transform class blocks
// For classes: scope is still active, methods can capture lexicals
// For packages: subroutines were already registered during parseBlock
if (isClass) {
block = ClassTransformer.transformClassBlock(block, nameNode.name, parser);
// Register user-defined methods BEFORE exiting scope
// This allows them to capture class-level lexicals
@SuppressWarnings("unchecked")
List<SubroutineNode> deferredMethods = (List<SubroutineNode>) block.getAnnotation("deferredMethods");
if (deferredMethods != null) {
for (SubroutineNode method : deferredMethods) {
SubroutineParser.handleNamedSubWithFilter(parser, method.name, method.prototype,
method.attributes, (BlockNode) method.block, false, null);
}
}
// NOW exit the block scope AFTER user-defined methods are registered
parser.ctx.symbolTable.exitScope(blockScopeIndex);
// Register generated methods WITH filtering (skip lexical sub/method hidden variables)
SubroutineNode deferredConstructor = (SubroutineNode) block.getAnnotation("deferredConstructor");
if (deferredConstructor != null) {
SubroutineParser.handleNamedSubWithFilter(parser, deferredConstructor.name, deferredConstructor.prototype,
deferredConstructor.attributes, (BlockNode) deferredConstructor.block, true, null);
}
@SuppressWarnings("unchecked")
List<SubroutineNode> deferredAccessors = (List<SubroutineNode>) block.getAnnotation("deferredAccessors");
if (deferredAccessors != null) {
for (SubroutineNode accessor : deferredAccessors) {
SubroutineParser.handleNamedSubWithFilter(parser, accessor.name, accessor.prototype,
accessor.attributes, (BlockNode) accessor.block, true, null);
}
}
// Restore the package context after class transformation
parser.ctx.symbolTable.setCurrentPackage(previousPackage, previousPackageIsClass);
} else {
// For regular packages, just restore context (scope already exited)
parser.ctx.symbolTable.setCurrentPackage(previousPackage, previousPackageIsClass);
}
// Exit the outer scope (from line 644)
parser.ctx.symbolTable.exitScope(scopeIndex);
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "}");
return block;
}
return null;
}
/**
* Parses an optional package version.
*
* @param parser The Parser instance
* @return A String representing the package version, or null if not present
*/
public static Node parseOptionalPackageVersion(Parser parser) {
LexerToken token;
token = TokenUtils.peek(parser);
if (token.type == LexerTokenType.NUMBER) {
return parseNumber(parser, TokenUtils.consume(parser));
}
if (token.type == LexerTokenType.IDENTIFIER && token.text.matches("v\\d+(\\.\\d+)*")) {
return parseVstring(parser, TokenUtils.consume(parser).text, parser.tokenIndex);
}
return null;
}
}