-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathScalarUtil.java
More file actions
423 lines (391 loc) · 16.9 KB
/
ScalarUtil.java
File metadata and controls
423 lines (391 loc) · 16.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
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.io.ClosedIOHandle;
import org.perlonjava.runtime.runtimetypes.*;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarType.*;
/**
* Utility class for Scalar operations in Perl.
* Extends PerlModuleBase to leverage module initialization and method registration.
*/
public class ScalarUtil extends PerlModuleBase {
/**
* Constructor for ScalarUtil.
* Initializes the module with the name "Scalar::Util".
*/
public ScalarUtil() {
super("Scalar::Util");
}
/**
* Static initializer to set up the Scalar::Util module.
* This method initializes the exporter and defines the symbols that can be exported.
*/
public static void initialize() {
ScalarUtil scalarUtil = new ScalarUtil();
scalarUtil.initializeExporter(); // Use the base class method to initialize the exporter
// Set $VERSION so CPAN.pm can detect our bundled version
GlobalVariable.getGlobalVariable("Scalar::Util::VERSION").set(new RuntimeScalar("1.70"));
scalarUtil.defineExport("EXPORT_OK", "blessed", "refaddr", "reftype", "weaken", "unweaken", "isweak",
"dualvar", "isdual", "isvstring", "looks_like_number", "openhandle", "readonly",
"set_prototype", "tainted");
try {
// Register methods with their respective signatures
scalarUtil.registerMethod("blessed", "$");
scalarUtil.registerMethod("refaddr", "$");
scalarUtil.registerMethod("reftype", "$");
scalarUtil.registerMethod("weaken", "$");
scalarUtil.registerMethod("unweaken", "$");
scalarUtil.registerMethod("isweak", "$");
scalarUtil.registerMethod("dualvar", "$$");
scalarUtil.registerMethod("isdual", "$");
scalarUtil.registerMethod("isvstring", "$");
scalarUtil.registerMethod("looks_like_number", "$");
scalarUtil.registerMethod("openhandle", "$");
scalarUtil.registerMethod("readonly", "$");
scalarUtil.registerMethod("set_prototype", "$$");
scalarUtil.registerMethod("tainted", "$");
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing Scalar::Util method: " + e.getMessage());
}
}
/**
* Triggers FETCH on a tied scalar so that get-magic is fired exactly
* once for blessed/reftype/refaddr. Also unwraps READONLY_SCALAR.
*/
private static RuntimeScalar magicallyDeref(RuntimeScalar scalar) {
if (scalar == null) return scalar;
if (scalar.type == TIED_SCALAR) {
scalar = scalar.tiedFetch();
}
if (scalar != null && scalar.type == READONLY_SCALAR) {
scalar = (RuntimeScalar) scalar.value;
}
return scalar;
}
/**
* Checks if a scalar is blessed and returns the blessing information.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return If args is a blessed reference, the name of the package that it is blessed into is returned. Otherwise "undef" is returned.
*/
public static RuntimeList blessed(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for blessed() method");
}
RuntimeScalar scalar = magicallyDeref(args.get(0));
int blessId = blessedId(scalar);
// Return undef for unblessed references (blessId == 0)
if (blessId == 0) {
// In Perl, qr// objects are implicitly blessed into "Regexp"
if (scalar.type == RuntimeScalarType.REGEX) {
return new RuntimeScalar("Regexp").getList();
}
return new RuntimeScalar().getList(); // undef
}
return new RuntimeScalar(NameNormalizer.getBlessStr(blessId)).getList();
}
/**
* Returns the memory address of a reference.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList containing the memory address, or undef if not a reference.
*/
public static RuntimeList refaddr(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for refaddr() method");
}
RuntimeScalar scalar = magicallyDeref(args.get(0));
// refaddr returns undef for non-references
// For references, return the identity hash code of the underlying referenced object
switch (scalar.type) {
case REFERENCE:
case ARRAYREFERENCE:
case HASHREFERENCE:
case CODE:
case FORMAT:
case REGEX:
// Return identity of the underlying value object
return new RuntimeScalar(System.identityHashCode(scalar.value)).getList();
case GLOB:
case GLOBREFERENCE:
if (scalar.value instanceof RuntimeGlob glob) {
// Named globs can be represented by detached RuntimeGlob
// instances that intentionally compare/stringify by name.
// Use the same stable glob identity here so refaddr(\*STDIN)
// agrees across repeated references.
return new RuntimeScalar(Integer.toUnsignedLong(glob.hashCode())).getList();
}
return new RuntimeScalar(System.identityHashCode(scalar.value)).getList();
default:
// Return undef for non-references
return new RuntimeScalar().getList();
}
}
/**
* Returns the type of reference.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList containing the reference type.
*/
public static RuntimeList reftype(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for reftype() method");
}
RuntimeScalar scalar = magicallyDeref(args.get(0));
String type = switch (scalar.type) {
case REFERENCE -> {
// Inspect the referent to distinguish SCALAR refs from REF (ref-to-ref)
if (scalar.value instanceof RuntimeScalar inner) {
if (inner.type == READONLY_SCALAR) inner = (RuntimeScalar) inner.value;
yield switch (inner.type) {
case VSTRING -> "VSTRING";
case REGEX, ARRAYREFERENCE, HASHREFERENCE, CODE, GLOBREFERENCE, REFERENCE -> "REF";
case GLOB -> "GLOB";
default -> "SCALAR";
};
}
yield "SCALAR";
}
case ARRAYREFERENCE -> "ARRAY";
case HASHREFERENCE -> "HASH";
case CODE -> "CODE";
case GLOB -> {
if (scalar.value instanceof RuntimeIO) yield "IO";
yield null;
}
case GLOBREFERENCE -> {
if (scalar.value instanceof RuntimeIO) yield "IO";
yield "GLOB";
}
case FORMAT -> "FORMAT";
case REGEX -> "REGEXP";
default -> null;
};
return (type != null ? new RuntimeScalar(type) : new RuntimeScalar()).getList();
}
/**
* Placeholder for the weaken functionality.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList.
*/
public static RuntimeList weaken(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for weaken() method");
}
RuntimeScalar ref = args.get(0);
WeakRefRegistry.weaken(ref);
return new RuntimeScalar().getList();
}
/**
* Restore a weak reference to a strong reference.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList.
*/
public static RuntimeList unweaken(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for unweaken() method");
}
RuntimeScalar ref = args.get(0);
WeakRefRegistry.unweaken(ref);
return new RuntimeScalar().getList();
}
/**
* Check if a reference has been weakened via weaken().
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the reference is weak.
*/
public static RuntimeList isweak(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for isweak() method");
}
RuntimeScalar ref = args.get(0);
boolean wasWeak = WeakRefRegistry.isweak(ref);
if (wasWeak
&& DestroyDispatch.hasRescuedObjects()
&& RuntimeCode.argsStackDepth() <= 3
&& !ModuleInitGuard.inModuleInit()) {
ReachabilityWalker.sweepWeakRefs(false);
ReachabilityWalker.sweepWeakRefs(false);
return new RuntimeScalar(true).getList();
}
return new RuntimeScalar(wasWeak).getList();
}
// isweak() may trigger a full sweep when DBIC-style DESTROY-rescued
// objects exist. It deliberately returns the pre-sweep weak status:
// DBIC's leak tracer evaluates defined($weakref) before isweak($weakref),
// so returning false after the sweep clears the scalar would look like a
// corrupted registry slot instead of normal weak-ref collection.
/**
* Dualvar functionality.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList.
*/
public static RuntimeList dualvar(RuntimeArray args, int ctx) {
if (args.size() != 2) {
throw new IllegalStateException("Bad number of arguments for dualvar() method");
}
var scalar = new RuntimeScalar();
scalar.type = RuntimeScalarType.DUALVAR;
scalar.value = new DualVar(args.get(0), args.get(1));
return scalar.getList();
}
/**
* Placeholder for the isdual functionality.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the scalar is dual.
*/
public static RuntimeList isdual(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for isdual() method");
}
RuntimeScalar s = args.get(0);
if (s.type == READONLY_SCALAR) s = (RuntimeScalar) s.value;
return new RuntimeScalar(s.type == DUALVAR).getList();
}
/**
* Placeholder for the isvstring functionality.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the scalar is a vstring.
*/
public static RuntimeList isvstring(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for isvstring() method");
}
RuntimeScalar s = args.get(0);
if (s.type == READONLY_SCALAR) s = (RuntimeScalar) s.value;
return new RuntimeScalar(s.type == VSTRING).getList();
}
/**
* Checks if a scalar looks like a number.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the scalar looks like a number.
*/
public static RuntimeList looks_like_number(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for looks_like_number() method");
}
boolean isNumber = ScalarUtils.looksLikeNumber(args.get(0));
return new RuntimeScalar(isNumber).getList();
}
/**
* Checks if a value is an open filehandle.
* Returns the filehandle itself if it's open, undef otherwise.
*
* @param args The arguments passed to the method (a single value).
* @param ctx The context in which the method is called.
* @return The filehandle if open, undef otherwise.
*/
public static RuntimeList openhandle(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for openhandle() method");
}
RuntimeScalar arg = args.get(0);
if (arg.type == READONLY_SCALAR) arg = (RuntimeScalar) arg.value;
// Check if it's a GLOB or GLOBREFERENCE (filehandle)
if (arg.type == GLOB || arg.type == GLOBREFERENCE) {
if (isOpenGlob(arg.value)) {
return arg.getList(); // Return the filehandle itself
}
}
// Check for blessed object with *{} overload
// In Perl 5, openhandle() recognizes objects with *{} overloading
// (e.g., File::Temp objects) as filehandles.
int blessId = RuntimeScalarType.blessedId(arg);
if (blessId < 0) {
// Blessed object with overloading - try *{} dereference
try {
RuntimeGlob glob = arg.globDeref();
if (glob != null) {
RuntimeScalar io = glob.getIO();
if (io != null && io.value instanceof RuntimeIO runtimeIO) {
if (!(runtimeIO.ioHandle instanceof ClosedIOHandle)) {
return arg.getList(); // Return the original object
}
}
}
} catch (Exception e) {
// globDeref failed - not a glob-like object, fall through to return undef
}
}
return new RuntimeScalar().getList(); // Return undef
}
/**
* Helper to check if a glob/IO value represents an open filehandle.
*/
private static boolean isOpenGlob(Object value) {
if (value instanceof RuntimeGlob glob) {
RuntimeScalar io = glob.getIO();
if (io != null && io.value instanceof RuntimeIO runtimeIO) {
return !(runtimeIO.ioHandle instanceof ClosedIOHandle);
}
} else if (value instanceof RuntimeIO runtimeIO) {
return !(runtimeIO.ioHandle instanceof ClosedIOHandle);
}
return false;
}
/**
* Check if a scalar is read-only.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the scalar is readonly.
*/
public static RuntimeList readonly(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for readonly() method");
}
RuntimeScalar arg = args.get(0);
return new RuntimeScalar(arg instanceof RuntimeScalarReadOnly).getList();
}
/**
* Sets the prototype for a subroutine.
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList.
*/
public static RuntimeList set_prototype(RuntimeArray args, int ctx) {
if (args.size() != 2) {
throw new IllegalStateException("Bad number of arguments for set_prototype() method");
}
RuntimeScalar scalar = args.get(0);
if (scalar.type == READONLY_SCALAR) scalar = (RuntimeScalar) scalar.value;
RuntimeScalar prototypeScalar = args.get(1);
if (scalar.type != CODE) {
throw new IllegalArgumentException("First argument must be a CODE reference");
}
RuntimeCode runtimeCode = (RuntimeCode) scalar.value;
// Set prototype to null if prototypeScalar is undef, otherwise use the string value
runtimeCode.prototype = prototypeScalar.getDefinedBoolean() ? prototypeScalar.toString() : null;
// Return the code reference (not undef)
return scalar.getList();
}
/**
* Checks if a scalar is tainted (contains data from external sources).
*
* @param args The arguments passed to the method.
* @param ctx The context in which the method is called.
* @return A RuntimeList indicating if the scalar is tainted.
*/
public static RuntimeList tainted(RuntimeArray args, int ctx) {
if (args.size() != 1) {
throw new IllegalStateException("Bad number of arguments for tainted() method");
}
return new RuntimeScalar(args.get(0).isTainted()).getList();
}
}