-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEmitRegex.java
More file actions
372 lines (318 loc) · 17.3 KB
/
EmitRegex.java
File metadata and controls
372 lines (318 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package org.perlonjava.backend.jvm;
import org.objectweb.asm.Opcodes;
import org.perlonjava.frontend.analysis.EmitterVisitor;
import org.perlonjava.frontend.astnode.*;
import org.perlonjava.runtime.perlmodule.Strict;
import org.perlonjava.runtime.runtimetypes.PerlCompilerException;
import org.perlonjava.runtime.runtimetypes.RuntimeContextType;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The EmitRegex class is responsible for handling regex-related operations
* within the code generation process. It provides methods to handle binding
* and non-binding regex operations, as well as specific regex operations like
* transliteration and replacement.
*/
public class EmitRegex {
// Callsite ID counter for /o modifier support (unique across all JVM compilations)
private static int nextCallsiteId = 100000; // Start at 100000 to avoid collision with interpreter IDs
/**
* Handles the binding regex operation where a variable is bound to a regex operation.
* This method processes the binary operator node representing the binding operation.
* Example: $variable =~ /pattern/
*
* @param emitterVisitor The visitor used to emit bytecode.
* @param node The binary operator node representing the binding regex operation.
*/
static void handleBindRegex(EmitterVisitor emitterVisitor, BinaryOperatorNode node) {
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
if (node.right instanceof OperatorNode right
&& right.operand instanceof ListNode listNode
&& !right.operator.equals("quoteRegex")) {
// Regex operator: $v =~ /regex/; (but NOT qr//)
// Bind the variable to the regex operation
// Do not mutate the original AST: create a local copy of the operator and its operand list.
ListNode boundListNode = new ListNode(new ArrayList<>(listNode.elements), listNode.tokenIndex);
boundListNode.handle = listNode.handle;
boundListNode.elements.add(node.left);
OperatorNode boundRight = new OperatorNode(right.operator, boundListNode, right.tokenIndex);
boundRight.id = right.id;
if (right.annotations != null) {
boundRight.annotations = new HashMap<>(right.annotations);
}
boundRight.accept(emitterVisitor); // Use caller's context for regex operations
return;
}
// Handle non-regex operator case (e.g., $v =~ $qr OR $v =~ qr//)
node.right.accept(scalarVisitor);
int regexSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledRegex = regexSlot >= 0;
if (!pooledRegex) {
regexSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ASTORE, regexSlot);
node.left.accept(scalarVisitor);
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ALOAD, regexSlot);
emitterVisitor.ctx.mv.visitInsn(Opcodes.SWAP);
if (pooledRegex) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
emitMatchRegex(emitterVisitor); // Use caller's context for regex matching
}
/**
* Handles the non-binding regex operation (!~).
* Negates the result of a binding regex operation.
* Example: $variable !~ /pattern/
*
* @param emitterVisitor The visitor used to emit bytecode.
* @param node The binary operator node representing the non-binding regex operation.
*/
static void handleNotBindRegex(EmitterVisitor emitterVisitor, BinaryOperatorNode node) {
// Check if using !~ with tr///r or y///r (which doesn't make sense)
if (node.right instanceof OperatorNode operatorNode
&& (operatorNode.operator.equals("tr") || operatorNode.operator.equals("transliterate"))
&& operatorNode.operand instanceof ListNode listNode
&& listNode.elements.size() >= 3) {
// Check if the modifiers (third element) contain 'r'
Node modifiersNode = listNode.elements.get(2);
if (modifiersNode instanceof StringNode stringNode) {
String modifiers = stringNode.value;
if (modifiers.contains("r")) {
throw new PerlCompilerException(node.tokenIndex,
"Using !~ with tr///r doesn't make sense",
emitterVisitor.ctx.errorUtil);
}
}
}
// Check if using !~ with s///r (which doesn't make sense)
if (node.right instanceof OperatorNode operatorNode
&& operatorNode.operator.equals("replaceRegex")
&& operatorNode.operand instanceof ListNode listNode
&& listNode.elements.size() >= 2) {
// Check if the modifiers (second element) contain 'r'
Node modifiersNode = listNode.elements.get(1);
if (modifiersNode instanceof StringNode stringNode) {
String modifiers = stringNode.value;
if (modifiers.contains("r")) {
throw new PerlCompilerException(node.tokenIndex,
"Using !~ with s///r doesn't make sense",
emitterVisitor.ctx.errorUtil);
}
}
}
emitterVisitor.visit(
new OperatorNode("not",
new BinaryOperatorNode(
"=~",
node.left,
node.right,
node.tokenIndex
), node.tokenIndex
));
}
/**
* Handles system command execution (backticks or qx operator).
* Example: `command` or qx/command/ or readpipe($expr)
*/
static void handleSystemCommand(EmitterVisitor emitterVisitor, OperatorNode node) {
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
Node commandNode;
// Handle two cases:
// 1. readpipe() with no args -> operand is OperatorNode for $_
// 2. readpipe($expr) or `cmd` -> operand is ListNode with command
if (node.operand instanceof ListNode operand) {
commandNode = operand.elements.getFirst();
} else {
// readpipe() with no arguments uses $_
commandNode = node.operand;
}
commandNode.accept(scalarVisitor);
emitterVisitor.pushCallContext();
// Create an OperatorNode for systemCommand
OperatorNode systemCmdNode = new OperatorNode("systemCommand", commandNode, node.tokenIndex);
EmitOperator.emitOperator(systemCmdNode, emitterVisitor);
}
/**
* Handles transliteration operations (tr/// or y///).
* Example: $string =~ tr/abc/def/
*/
static void handleTransliterate(EmitterVisitor emitterVisitor, OperatorNode node) {
// Defensive: ensure operand is a ListNode
ListNode operand = (node.operand instanceof ListNode)
? (ListNode) node.operand
: ListNode.makeList(node.operand);
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
// Process the three required components: source, target, and flags
operand.elements.get(0).accept(scalarVisitor); // Source characters
operand.elements.get(1).accept(scalarVisitor); // Target characters
operand.elements.get(2).accept(scalarVisitor); // Flags/modifiers
// Compile the transliteration operation
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/operators/RuntimeTransliterate", "compile",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/operators/RuntimeTransliterate;", false);
// Use default variable $_ if none specified
handleVariableBinding(operand, 3, scalarVisitor);
// Push call context for SCALAR or LIST context.
emitterVisitor.pushCallContext();
// Execute the transliteration
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/perlonjava/runtime/operators/RuntimeTransliterate", "transliterate", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
// Clean up stack if in void context
EmitOperator.handleVoidContext(emitterVisitor);
}
/**
* Handles regex replacement operations (s///).
* Example: $string =~ s/pattern/replacement/
*/
static void handleReplaceRegex(EmitterVisitor emitterVisitor, OperatorNode node) {
// Defensive: ensure operand is a ListNode
ListNode operand = (node.operand instanceof ListNode)
? (ListNode) node.operand
: ListNode.makeList(node.operand);
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
// Process pattern, replacement, and flags
operand.elements.get(0).accept(scalarVisitor); // Pattern
operand.elements.get(1).accept(scalarVisitor); // Replacement
operand.elements.get(2).accept(scalarVisitor); // Flags
// Push the caller's @_ so $_[0] etc. work in s/// replacement
// @_ is at local variable slot 1 in subroutines
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ALOAD, 1);
// Create the replacement regex (4-argument version with caller's @_)
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/regex/RuntimeRegex", "getReplacementRegex",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
int regexSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledRegex = regexSlot >= 0;
if (!pooledRegex) {
regexSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ASTORE, regexSlot);
// Use default variable $_ if none specified
handleVariableBinding(operand, 3, scalarVisitor);
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ALOAD, regexSlot);
emitterVisitor.ctx.mv.visitInsn(Opcodes.SWAP);
if (pooledRegex) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
emitMatchRegex(emitterVisitor);
}
/**
* Handles quoted regex operations (qr//).
* Example: qr/pattern/
*/
static void handleQuoteRegex(EmitterVisitor emitterVisitor, OperatorNode node) {
// Defensive: ensure operand is a ListNode
ListNode operand = (node.operand instanceof ListNode)
? (ListNode) node.operand
: ListNode.makeList(node.operand);
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
// Process pattern and flags
operand.elements.get(0).accept(scalarVisitor); // Pattern
operand.elements.get(1).accept(scalarVisitor); // Flags
// Create the quoted regex
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/regex/RuntimeRegex", "getQuotedRegex",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
if (emitterVisitor.ctx.contextType == RuntimeContextType.VOID) {
emitterVisitor.ctx.mv.visitInsn(Opcodes.POP);
}
}
/**
* Handles regex match operations (m//).
* Example: $string =~ m/pattern/
*/
static void handleMatchRegex(EmitterVisitor emitterVisitor, OperatorNode node) {
// Defensive: ensure operand is a ListNode
ListNode operand = (node.operand instanceof ListNode)
? (ListNode) node.operand
: ListNode.makeList(node.operand);
EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR);
// Check if /o modifier is present
boolean hasOModifier = false;
Node flagsNode = operand.elements.get(1);
if (flagsNode instanceof StringNode) {
hasOModifier = ((StringNode) flagsNode).value.contains("o");
}
// Process pattern and flags
operand.elements.get(0).accept(scalarVisitor); // Pattern
flagsNode.accept(scalarVisitor); // Flags
// Create the regex matcher (use 3-argument version for /o)
if (hasOModifier) {
int callsiteId = nextCallsiteId++;
emitterVisitor.ctx.mv.visitLdcInsn(callsiteId);
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/regex/RuntimeRegex", "getQuotedRegex",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
} else {
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/regex/RuntimeRegex", "getQuotedRegex",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
}
int regexSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot();
boolean pooledRegex = regexSlot >= 0;
if (!pooledRegex) {
regexSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable();
}
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ASTORE, regexSlot);
// Use default variable $_ if none specified
handleVariableBinding(operand, 2, scalarVisitor);
emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ALOAD, regexSlot);
emitterVisitor.ctx.mv.visitInsn(Opcodes.SWAP);
if (pooledRegex) {
emitterVisitor.ctx.javaClassInfo.releaseSpillSlot();
}
emitMatchRegex(emitterVisitor);
}
/**
* Helper method to emit bytecode for regex matching operations.
* Handles different context types (SCALAR, VOID) appropriately.
* When 'use bytes' is in effect, converts the input string to its
* UTF-8 byte representation before matching.
*/
private static void emitMatchRegex(EmitterVisitor emitterVisitor) {
// When 'use bytes' is in effect, convert the input string to byte representation
// so that regex character classes like [\x7f-\xa0] match against UTF-8 bytes
if (emitterVisitor.ctx.symbolTable != null &&
emitterVisitor.ctx.symbolTable.isStrictOptionEnabled(Strict.HINT_BYTES)) {
// Stack: regex, string (top) -> regex, bytesString (top)
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/operators/StringOperators", "toBytesString",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;",
false);
}
emitterVisitor.pushCallContext();
// Invoke the regex matching operation
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/regex/RuntimeRegex", "matchRegex",
"(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", false);
if (emitterVisitor.ctx.contextType == RuntimeContextType.VOID) {
// Discard result if in void context
emitterVisitor.ctx.mv.visitInsn(Opcodes.POP);
return;
}
// Handle the result based on context type
if (emitterVisitor.ctx.contextType == RuntimeContextType.SCALAR) {
// Convert result to Scalar if in scalar context
emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/perlonjava/runtime/runtimetypes/RuntimeBase", "scalar", "()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false);
}
}
/**
* Handles variable binding for regex operations, using $_ as default if no variable is specified.
*
* @param operand The ListNode containing operation elements
* @param variableIndex The index where the variable binding should be found in the operand list
* @param scalarVisitor The visitor used to emit scalar context bytecode
*/
private static void handleVariableBinding(ListNode operand, int variableIndex, EmitterVisitor scalarVisitor) {
// Check if a variable was provided in the operand list
Node variable = null;
if (operand.elements.size() > variableIndex) {
variable = operand.elements.get(variableIndex);
}
// If no variable was specified, use the default $_ variable
if (variable == null) {
variable = new OperatorNode("$", new IdentifierNode("_", operand.tokenIndex), operand.tokenIndex);
}
// Generate bytecode for the variable access
variable.accept(scalarVisitor);
}
}