-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSignatureParser.java
More file actions
586 lines (510 loc) · 24.7 KB
/
SignatureParser.java
File metadata and controls
586 lines (510 loc) · 24.7 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
package org.perlonjava.frontend.parser;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.frontend.lexer.LexerToken;
import org.perlonjava.frontend.lexer.LexerTokenType;
import org.perlonjava.runtime.runtimetypes.NameNormalizer;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import java.util.ArrayList;
import java.util.List;
import static org.perlonjava.frontend.parser.OperatorParser.dieWarnNode;
import static org.perlonjava.frontend.parser.ParserNodeUtils.atUnderscore;
import static org.perlonjava.frontend.parser.PrototypeArgs.consumeArgsWithPrototype;
/**
* SignatureParser handles parsing of Perl 5.42 subroutine signatures.
*
* <p>Supported signature features:
* <ul>
* <li>Empty signatures: {@code sub foo() { }}</li>
* <li>Mandatory parameters: {@code sub foo($a, $b) { }}</li>
* <li>Ignored parameters: {@code sub foo($a, $, $c) { }}</li>
* <li>Optional parameters: {@code sub foo($a = 10) { }}</li>
* <li>Default from previous parameter: {@code sub foo($a, $b = $a) { }}</li>
* <li>Defined-or defaults: {@code sub foo($a //= 'default') { }}</li>
* <li>Logical-or defaults: {@code sub foo($a ||= 100) { }}</li>
* <li>Slurpy arrays: {@code sub foo($a, @rest) { }}</li>
* <li>Slurpy hashes: {@code sub foo(%opts) { }}</li>
* <li>Anonymous slurpy: {@code sub foo($a, @) { }}</li>
* <li>Named parameters: {@code sub foo(:$named = 'default') { }}</li>
* </ul>
*/
public class SignatureParser {
private final Parser parser;
private final List<Node> astNodes = new ArrayList<>();
private final List<Node> parameterVariables = new ArrayList<>();
private final List<Node> namedParameterNodes = new ArrayList<>();
private int minParams = 0;
private int maxParams = 0;
private boolean hasSlurpy = false;
private String namedArgsHashName = null; // Track the hash name for named parameters
private String subroutineName = null; // Optional subroutine name for error messages
private boolean isMethod = false; // True if parsing method signature (has implicit $self)
private SignatureParser(Parser parser) {
this.parser = parser;
this.isMethod = parser.isInMethod;
}
private SignatureParser(Parser parser, String subroutineName) {
this.parser = parser;
this.subroutineName = subroutineName;
this.isMethod = parser.isInMethod;
}
/**
* Parses a Perl subroutine signature and generates the corresponding AST.
*
* @param parser The parser instance
* @return A ListNode containing the generated AST nodes
* @throws PerlCompilerException if the signature syntax is invalid
*/
public static ListNode parseSignature(Parser parser) {
return new SignatureParser(parser).parse();
}
/**
* Parses a Perl subroutine signature and generates the corresponding AST.
*
* @param parser The parser instance
* @param subroutineName The name of the subroutine for error messages
* @return A ListNode containing the generated AST nodes
* @throws PerlCompilerException if the signature syntax is invalid
*/
public static ListNode parseSignature(Parser parser, String subroutineName) {
return new SignatureParser(parser, subroutineName).parse();
}
/**
* Parses a Perl method signature and generates the corresponding AST.
* Methods have an implicit $self parameter that affects argument counts in error messages.
*
* @param parser The parser instance
* @param methodName The name of the method for error messages
* @param isMethod True if this is a method (has implicit $self)
* @return A ListNode containing the generated AST nodes
* @throws PerlCompilerException if the signature syntax is invalid
*/
public static ListNode parseSignature(Parser parser, String methodName, boolean isMethod) {
SignatureParser sigParser = new SignatureParser(parser, methodName);
sigParser.isMethod = isMethod;
return sigParser.parse();
}
private ListNode parse() {
consumeOpenParen();
// Handle empty signature
if (peekToken().text.equals(")")) {
consumeCloseParen();
return generateSignatureAST();
}
// Parse parameters
while (true) {
parseParameter();
// Check what comes after the parameter
LexerToken next = peekToken();
if (next.text.equals(")")) {
break;
} else if (next.text.equals(",")) {
consumeCommas();
// Check for trailing comma
if (peekToken().text.equals(")")) {
break;
}
} else {
// Check for missing comma between parameters (special case)
if (next.text.equals("$") || next.text.equals("@") || next.text.equals("%")) {
parser.throwError("syntax error");
}
parser.throwError("Expected ',' or ')' in signature prototype");
}
}
consumeCloseParen();
return generateSignatureAST();
}
private void parseParameter() {
// Check for named parameter (starts with :)
boolean isNamed = false;
if (peekToken().text.equals(":")) {
consumeToken(); // consume ':'
isNamed = true;
}
LexerToken sigilToken = consumeToken();
String sigil = sigilToken.text;
validateSigil(sigil);
if (hasSlurpy) {
parser.throwError("Slurpy parameter not last");
}
// Check if this is a slurpy parameter
boolean isSlurpy = sigil.equals("@") || sigil.equals("%");
// Named parameters cannot be slurpy
if (isNamed && isSlurpy) {
parser.throwError("Named parameters cannot be slurpy");
}
// Parse parameter name (if present)
String paramName = null;
if (peekToken().type == LexerTokenType.IDENTIFIER) {
paramName = consumeToken().text;
}
// Named parameters must have a name
if (isNamed && paramName == null) {
parser.throwError("Named parameter must have a name");
}
// Create parameter variable or undef placeholder
Node paramVariable = createParameterVariable(sigil, paramName);
if (isNamed) {
// Named parameters are handled separately, not part of @_ unpacking
namedParameterNodes.add(paramVariable);
handleNamedParameter(paramVariable, paramName);
} else {
parameterVariables.add(paramVariable);
if (isSlurpy) {
handleSlurpyParameter();
} else {
handleScalarParameter(paramVariable);
}
}
}
private void validateSigil(String sigil) {
// Check for $# which is tokenized as a single token
if (sigil.equals("$#")) {
parser.throwError("'#' not allowed immediately following a sigil in a subroutine signature");
}
if (!sigil.equals("$") && !sigil.equals("@") && !sigil.equals("%")) {
parser.throwError("A signature parameter must start with '$', '@' or '%'");
}
// Check for double sigil or invalid character after sigil
LexerToken next = peekToken();
if (next.text.equals("$") || next.text.equals("@") || next.text.equals("%")) {
parser.throwError("Illegal character following sigil in a subroutine signature");
}
if (next.text.equals("#")) {
parser.throwError("'#' not allowed immediately following a sigil in a subroutine signature");
}
}
private Node createParameterVariable(String sigil, String name) {
if (name != null) {
return new OperatorNode(sigil, new IdentifierNode(name, parser.tokenIndex), parser.tokenIndex);
} else {
return new OperatorNode("undef", null, parser.tokenIndex);
}
}
private void handleSlurpyParameter() {
hasSlurpy = true;
maxParams = Integer.MAX_VALUE;
// Verify no more parameters after slurpy
LexerToken next = peekToken();
if (next.text.equals(",")) {
consumeToken(); // consume comma
next = peekToken();
if (!next.text.equals(")")) {
if (next.text.equals("@") || next.text.equals("%")) {
parser.throwError("Multiple slurpy parameters not allowed");
} else {
parser.throwError("Slurpy parameter not last");
}
}
}
}
private void handleScalarParameter(Node paramVariable) {
LexerToken next = peekToken();
// Check for default value
if (next.text.equals("=") || next.text.equals("||=") || next.text.equals("//=")) {
String defaultOp = consumeToken().text;
Node defaultValue = parseDefaultValue(paramVariable);
if (defaultValue != null) {
astNodes.add(generateDefaultAssignment(paramVariable, defaultValue, defaultOp, maxParams));
}
} else {
// Mandatory parameter
minParams++;
}
maxParams++;
}
private void handleNamedParameter(Node paramVariable, String paramName) {
LexerToken next = peekToken();
// Named parameters are always optional and extracted from a hash in @_
// Generate: my %h = @_; $named = (delete $h{named}) // default_value;
Node defaultValue = null;
String defaultOp = "//="; // default to defined-or operator for named params
// Check for default value
if (next.text.equals("=") || next.text.equals("||=") || next.text.equals("//=")) {
defaultOp = consumeToken().text;
defaultValue = parseDefaultValue(paramVariable);
}
// Generate the extraction code for named parameter
// This returns a ListNode with the hash declaration and extraction statements
Node extractionCode = generateNamedParameterExtraction(paramVariable, paramName, defaultValue, defaultOp);
// Add the extraction statements to astNodes
if (extractionCode instanceof ListNode) {
astNodes.addAll(((ListNode) extractionCode).elements);
} else {
astNodes.add(extractionCode);
}
}
private Node generateDefaultAssignment(Node variable, Node defaultValue, String op, int paramIndex) {
if (variable == null || (variable instanceof OperatorNode && ((OperatorNode) variable).operator.equals("undef"))) {
// Anonymous parameter with default - no-op
return new ListNode(parser.tokenIndex);
}
if (op.equals("=")) {
// Simple default: assign if not enough arguments
// @_ < (paramIndex + 1) && ($var = defaultValue)
return new BinaryOperatorNode(
"&&",
new BinaryOperatorNode(
"<",
atUnderscore(parser),
new NumberNode(Integer.toString(paramIndex + 1), parser.tokenIndex),
parser.tokenIndex),
new BinaryOperatorNode(
"=",
variable,
defaultValue,
parser.tokenIndex),
parser.tokenIndex);
}
// //= or ||= operators
return new BinaryOperatorNode(op, variable, defaultValue, parser.tokenIndex);
}
private Node parseDefaultValue(Node paramVariable) {
// Check if there's actually a default expression
LexerToken next = peekToken();
if (next.type == LexerTokenType.EOF || next.text.equals(",") || next.text.equals(")")) {
boolean isUndef = paramVariable instanceof OperatorNode && ((OperatorNode) paramVariable).operator.equals("undef");
if (paramVariable != null && !isUndef) {
parser.throwError("Optional parameter lacks default expression");
}
return null;
}
// Parse the default value expression
ListNode arguments = consumeArgsWithPrototype(parser, "$", false);
return arguments.elements.getFirst();
}
/**
* Generates AST for extracting a named parameter from @_.
*
* <p>Named parameters are passed as key-value pairs in @_. This method generates:
* <pre>{@code
* my %__named_args__ = @_; # Only once for all named params
* my $paramName = (delete $__named_args__{paramName}) // defaultValue;
* }</pre>
*
* <p>The generated AST structure:
* <ol>
* <li>Hash declaration: {@code my %__named_args__ = @_} (first param only)</li>
* <li>Delete operation: {@code delete $__named_args__{paramName}}</li>
* <li>Default application: {@code deleteExpr // defaultValue}</li>
* <li>Variable assignment: {@code my $paramName = extractionValue}</li>
* </ol>
*
* @param paramVariable The variable node to assign the extracted value to
* @param paramName The name of the parameter (for hash key lookup)
* @param defaultValue The default value expression, or null if no default
* @param defaultOp The default operator ("=", "//=", or "||=")
* @return A ListNode containing the hash declaration and extraction statements
*/
private Node generateNamedParameterExtraction(Node paramVariable, String paramName, Node defaultValue, String defaultOp) {
List<Node> statements = new ArrayList<>();
// Create the hash only once for all named parameters
if (namedArgsHashName == null) {
namedArgsHashName = "__named_args__";
IdentifierNode hashIdent = new IdentifierNode(namedArgsHashName, parser.tokenIndex);
Node hashVar = new OperatorNode("%", hashIdent, parser.tokenIndex);
// Create: my %__named_args__ = @_
Node hashDecl = new BinaryOperatorNode(
"=",
new OperatorNode("my", hashVar, parser.tokenIndex),
atUnderscore(parser),
parser.tokenIndex);
statements.add(hashDecl);
}
// Create: $__named_args__{named}
// Note: use $ sigil for single element access, not %
IdentifierNode hashIdent = new IdentifierNode(namedArgsHashName, parser.tokenIndex);
// Hash subscripts need HashLiteralNode wrapping the key
// Use ArrayList because the codegen may modify the list (e.g., auto-quoting identifiers)
List<Node> keyList = new ArrayList<>();
keyList.add(new IdentifierNode(paramName, parser.tokenIndex));
HashLiteralNode hashKey = new HashLiteralNode(keyList, parser.tokenIndex);
Node hashAccess = new BinaryOperatorNode(
"{",
new OperatorNode("$", hashIdent, parser.tokenIndex),
hashKey,
parser.tokenIndex);
// Create: delete $__named_args__{named}
// The delete operator expects its operand to be a ListNode
Node deleteExpr = new OperatorNode("delete", new ListNode(List.of(hashAccess), parser.tokenIndex), parser.tokenIndex);
Node extractionValue;
if (defaultValue != null) {
// (delete $h{named}) // defaultValue
if (defaultOp.equals("=")) {
defaultOp = "//";
} else if (defaultOp.equals("||=")) {
defaultOp = "||";
} else if (defaultOp.equals("//=")) {
defaultOp = "//";
}
extractionValue = new BinaryOperatorNode(
defaultOp,
deleteExpr,
defaultValue,
parser.tokenIndex);
} else {
extractionValue = deleteExpr;
}
// Add the extraction assignment with 'my' declaration
// my $named = (delete $h{named}) // default
Node myParam = new OperatorNode("my", paramVariable, parser.tokenIndex);
statements.add(new BinaryOperatorNode("=", myParam, extractionValue, parser.tokenIndex));
// Return a list node containing the hash declaration (if first time) and the extraction
return new ListNode(statements, parser.tokenIndex);
}
private ListNode generateSignatureAST() {
List<Node> allNodes = new ArrayList<>();
// Add argument count validation
allNodes.add(generateArgCountValidation());
// Add parameter assignment from @_
if (!parameterVariables.isEmpty()) {
allNodes.add(generateParameterAssignment());
}
// Add default value assignments and named parameter extractions
// (Named parameters are declared within their extraction code)
allNodes.addAll(astNodes);
return new ListNode(allNodes, parser.tokenIndex);
}
private Node generateArgCountValidation() {
// If we have named parameters, we need different validation
// Named parameters are passed as key-value pairs, so we need to allow extra arguments
if (!namedParameterNodes.isEmpty()) {
// With named parameters: minParams <= @_
// (We don't check maxParams because named parameters can take any number of key-value pairs)
return new BinaryOperatorNode(
"||",
new ListNode(List.of(
new BinaryOperatorNode("<=",
new NumberNode(Integer.toString(minParams), parser.tokenIndex),
atUnderscore(parser),
parser.tokenIndex)
), parser.tokenIndex),
dieWarnNode(parser, "die", new ListNode(List.of(
generateTooFewArgsMessage()), parser.tokenIndex), parser.tokenIndex),
parser.tokenIndex);
} else {
// Without named parameters: check both min and max
// We need to check separately for too few vs too many to generate appropriate error messages
// First check: minParams <= @_ (too few arguments check)
Node tooFewCheck = new BinaryOperatorNode(
"||",
new ListNode(List.of(
new BinaryOperatorNode("<=",
new NumberNode(Integer.toString(minParams), parser.tokenIndex),
atUnderscore(parser),
parser.tokenIndex)
), parser.tokenIndex),
dieWarnNode(parser, "die", new ListNode(List.of(
generateTooFewArgsMessage()), parser.tokenIndex), parser.tokenIndex),
parser.tokenIndex);
// Second check: @_ <= maxParams (too many arguments check)
Node tooManyCheck = new BinaryOperatorNode(
"||",
new ListNode(List.of(
new BinaryOperatorNode("<=",
atUnderscore(parser),
new NumberNode(Integer.toString(maxParams), parser.tokenIndex),
parser.tokenIndex)
), parser.tokenIndex),
dieWarnNode(parser, "die", new ListNode(List.of(
generateTooManyArgsMessage()), parser.tokenIndex), parser.tokenIndex),
parser.tokenIndex);
// Return both checks in sequence
return new ListNode(List.of(tooFewCheck, tooManyCheck), parser.tokenIndex);
}
}
private Node generateTooFewArgsMessage() {
if (subroutineName != null) {
// Generate: "Too few arguments for subroutine 'Package::name' (got " . (scalar(@_) + adjustment) . "; expected at least " . minParams . ")"
String fullName = NameNormalizer.normalizeVariableName(subroutineName, parser.ctx.symbolTable.getCurrentPackage());
// For methods, add 1 to account for implicit $self parameter (both in got and expected)
int adjustedMin = isMethod ? minParams + 1 : minParams;
Node argCount;
if (isMethod) {
// For methods: scalar(@_) + 1 (to account for $self that was already shifted)
argCount = new BinaryOperatorNode("+",
new OperatorNode("scalar", atUnderscore(parser), parser.tokenIndex),
new NumberNode("1", parser.tokenIndex),
parser.tokenIndex);
} else {
argCount = new OperatorNode("scalar", atUnderscore(parser), parser.tokenIndex);
}
return new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new StringNode("Too few arguments for subroutine '" + fullName + "' (got ", parser.tokenIndex),
argCount,
parser.tokenIndex),
new StringNode(minParams == maxParams ? "; expected " : "; expected at least ", parser.tokenIndex),
parser.tokenIndex),
new NumberNode(Integer.toString(adjustedMin), parser.tokenIndex),
parser.tokenIndex),
new StringNode(")", parser.tokenIndex),
parser.tokenIndex);
} else {
return new StringNode("Too few arguments", parser.tokenIndex);
}
}
private Node generateTooManyArgsMessage() {
if (subroutineName != null) {
// Generate: "Too many arguments for subroutine 'Package::name' (got " . (scalar(@_) + adjustment) . "; expected at most " . maxParams . ")"
String fullName = NameNormalizer.normalizeVariableName(subroutineName, parser.ctx.symbolTable.getCurrentPackage());
// For methods, add 1 to account for implicit $self parameter (both in got and expected)
int adjustedMax = isMethod ? maxParams + 1 : maxParams;
Node argCount;
if (isMethod) {
// For methods: scalar(@_) + 1 (to account for $self that was already shifted)
argCount = new BinaryOperatorNode("+",
new OperatorNode("scalar", atUnderscore(parser), parser.tokenIndex),
new NumberNode("1", parser.tokenIndex),
parser.tokenIndex);
} else {
argCount = new OperatorNode("scalar", atUnderscore(parser), parser.tokenIndex);
}
return new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new BinaryOperatorNode(".",
new StringNode("Too many arguments for subroutine '" + fullName + "' (got ", parser.tokenIndex),
argCount,
parser.tokenIndex),
new StringNode(minParams == maxParams ? "; expected " : "; expected at most ", parser.tokenIndex),
parser.tokenIndex),
new NumberNode(Integer.toString(adjustedMax), parser.tokenIndex),
parser.tokenIndex),
new StringNode(")", parser.tokenIndex),
parser.tokenIndex);
} else {
return new StringNode("Too many arguments", parser.tokenIndex);
}
}
private Node generateParameterAssignment() {
// my ($a, $b, @rest) = @_
return new BinaryOperatorNode(
"=",
new OperatorNode("my",
new ListNode(parameterVariables, parser.tokenIndex),
parser.tokenIndex),
atUnderscore(parser),
parser.tokenIndex);
}
// Token handling utilities
private void consumeOpenParen() {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, "(");
}
private void consumeCloseParen() {
TokenUtils.consume(parser, LexerTokenType.OPERATOR, ")");
}
private void consumeCommas() {
while (peekToken().text.equals(",")) {
consumeToken();
}
}
private LexerToken peekToken() {
return TokenUtils.peek(parser);
}
private LexerToken consumeToken() {
return TokenUtils.consume(parser);
}
}