Perlito5/Java/CORE.pm untested

filter: Statementstmt 0.0% 0 / 10 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 3 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 14 CC 1 SCAR 6.9
CC
1
Cov
0%
emit_java
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 use v5;
2  
3 package Perlito5::Java::CORE;
4 use strict;
5  
6  
7 my %FileFunc = (
8 close => <<'EOT',
9 try {
10 fh.close();
11  
12 // success
13 return PlCx.INT1;
14 }
15 catch(IOException e) {
16 PlV.sset("main::!", new PlStringLazyError(e));
17 }
18 return PlCx.UNDEF;
19 EOT
20 # binmode FILEHANDLE, LAYER
21 binmode => <<'EOT',
22 String layer;
23 int arg_count = List__.length_of_array_int();
24 if (arg_count == 0) {
25 // layer = ":raw";
26 fh.binmode = true;
27 return PlCx.INT1;
28 }
29 else {
30 layer = List__.aget(0).toString();
31 }
32 if (fh.path == null) {
33 // special file, don't know what to do
34 return PlCx.INT1;
35 }
36 return PlCORE.open(
37 want,
38 fh,
39 new PlArray(new PlString(fh.mode + layer), new PlString(fh.path.toString())),
40 ""
41 );
42 EOT
43 opendir => <<'EOT',
44 try {
45 String s = List__.aget(0).toString();
46 Path path = PlV.path.resolve(s).toRealPath();
47  
48 fh.directoryStream = Files.newDirectoryStream(path);
49 fh.directoryIterator = fh.directoryStream.iterator();
50  
51 // success
52 return PlCx.INT1;
53 }
54 catch(IOException e) {
55 PlV.sset("main::!", new PlStringLazyError(e));
56 }
57 return PlCx.UNDEF;
58 EOT
59 readdir => <<'EOT',
60 Iterator<Path> iter = fh.directoryIterator;
61 if (want == PlCx.LIST) {
62 // read all lines
63 PlArray res = new PlArray();
64 while (iter.hasNext()) {
65 res.push_void(new PlString(iter.next().getFileName().toString()));
66 }
67 res.push_void(new PlString("."));
68 res.push_void(new PlString(".."));
69 return res;
70 }
71 if (!iter.hasNext()) {
72 return PlCx.UNDEF;
73 }
74 Path entry = iter.next();
75 return new PlString(entry.getFileName().toString());
76 EOT
77 closedir => <<'EOT',
78 try {
79 fh.readlineBuffer = new StringBuilder();
80 fh.flush();
81 fh.eof = true;
82 if (fh.directoryStream != null) {
83 fh.directoryStream.close();
84 }
85 }
86 catch(IOException e) {
87 PlV.sset("main::!", new PlStringLazyError(e));
88 return PlCx.UNDEF;
89 }
90 return PlCx.INT1;
91 EOT
92 syswrite => <<'EOT',
93 int argCount = List__.to_int();
94 if (argCount < 1) {
95 PlCORE.die("Not enough arguments for syswrite");
96 }
97 PlObject st = PlCx.EMPTY;
98 if (argCount == 1) {
99 st = List__.aget(0);
100 }
101 else if (argCount == 2) {
102 // syswrite(FILEHANDLE,SCALAR,LENGTH)
103 st = List__.aget(0).substr(0, List__.aget(1).to_int());
104 }
105 else {
106 // syswrite(FILEHANDLE,SCALAR,LENGTH,OFFSET)
107 st = List__.aget(0).substr(List__.aget(2).to_int(), List__.aget(1).to_int());
108 }
109 int count = 0;
110 try {
111 String s = st.toString();
112  
113 if (fh.binmode) {
114 for (int i = 0; i < s.length(); i++) {
115 fh.outputStream.write(s.charAt(i));
116 count++;
117 }
118 }
119 else {
120 byte[] bytes = s.getBytes(fh.charset);
121 fh.outputStream.write(bytes);
122 count += bytes.length;
123 }
124 fh.outputStream.flush();
125 }
126 catch(Exception e) {
127 PlV.sset("main::!", new PlStringLazyError(e));
128 }
129 return new PlInt(count);
130 EOT
131 write => <<'EOT',
132  
133 // The current format name is stored in the variable $~ ($FORMAT_NAME), and
134 // the current top of form format name is in $^ ($FORMAT_TOP_NAME). The
135 // current output page number is stored in $% ($FORMAT_PAGE_NUMBER), and the
136 // number of lines on the page is in $= ($FORMAT_LINES_PER_PAGE). Whether to
137 // autoflush output on this handle is stored in $| ($OUTPUT_AUTOFLUSH). The
138 // string output before each top of page (except the first) is stored in $^L
139 // ($FORMAT_FORMFEED).
140  
141 PlHash formats = PlStringConstant.getConstant("Perlito5::FORMAT").hashRef.o.hash_deref_strict();
142 PlLvalue accumulator = PlStringConstant.getConstant("main::" + (char)1).scalarRef; // $^A
143  
144 String name = PlStringConstant.getConstant("main::~").scalarRef.toString();
145 if (name.equals("")) {
146 name = fh.typeglob_name;
147 }
148 if (name.length() > 6 && name.startsWith("main::")) {
149 name = name.substring(6);
150 }
151  
152 String top_name = PlStringConstant.getConstant("main::^").scalarRef.toString();
153 if (top_name.equals("")) {
154 top_name = name + "_TOP";
155 }
156 if (top_name.length() > 6 && top_name.startsWith("main::")) {
157 top_name = top_name.substring(6);
158 }
159  
160 if (!formats.hget(name).to_boolean()) {
161 PlCORE.die(PlCx.VOID, new PlArray(new PlString("Undefined format \"" + name + "\"")));
162 }
163  
164 if (formats.hget(top_name).to_boolean()) {
165 formats.hget(top_name).apply(PlCx.VOID, new PlArray());
166 }
167 formats.hget(name).apply(PlCx.VOID, new PlArray());
168 PlCORE.print(want, fh, accumulator.toString());
169 accumulator.set(PlCx.EMPTY);
170 return new PlInt(1);
171 EOT
172 readline => <<'EOT',
173 if (want == PlCx.LIST) {
174 // read all lines
175 PlArray res = new PlArray();
176 PlObject s;
177 while (!(s = PlCORE.readline(PlCx.SCALAR, fh, List__)).is_undef()) {
178 res.push_void(s);
179 }
180 return res;
181 }
182 PlObject plsep = PlV.sget("main::/");
183 boolean slurp = false;
184 if (plsep.is_undef()) {
185 slurp = true;
186 }
187 if (fh.eof) {
188 if (fh.is_argv) {
189 // "ARGV" is special
190 PlArray argv = PlV.array_get("main::ARGV");
191 PlFileHandle in = new PlFileHandle();
192 if (argv.to_int() > 0) {
193 // arg list contains file name
194 PlCORE.open(
195 PlCx.VOID,
196 in,
197 new PlArray(new PlString("<"), argv.shift()),
198 ""
199 );
200 }
201 else {
202 // read from STDIN
203 fh.is_argv = false; // clear the magic bit
204 in = PlV.STDIN;
205 }
206 fh.readlineBuffer = in.readlineBuffer;
207 fh.eof = in.eof;
208 fh.outputStream = in.outputStream;
209 fh.reader = in.reader;
210 }
211 if (fh.eof) {
212 return PlCx.UNDEF;
213 }
214 }
215 String sep = plsep.toString();
216 StringBuilder buf = fh.readlineBuffer;
217 // read from filehandle until "sep" or eof()
218 int pos = slurp ? -1 : buf.indexOf(sep);
219 while (pos < 0 && !fh.eof) {
220 // read more
221 int len = 1000;
222 char[] c = new char[len];
223 int num_chars = 0;
224 try {
225 num_chars = fh.reader.read(c, 0, len);
226 if (num_chars > 0) {
227 // TODO - use: new String(bytes,"UTF-8")
228 String s = new String(c, 0, num_chars);
229 buf.append(s);
230 }
231 }
232 catch(IOException e) {
233 PlV.sset("main::!", new PlStringLazyError(e));
234 return PlCx.UNDEF;
235 }
236 if (num_chars > 0) {
237 if (!slurp) {
238 pos = buf.indexOf(sep);
239 }
240 }
241 else {
242 // eof
243 fh.eof = true;
244 }
245 }
246 String s;
247 if (fh.eof || pos < 0) {
248 s = buf.toString();
249 fh.readlineBuffer = new StringBuilder();
250 fh.eof = true;
251 if (s.length() == 0) {
252 return PlCx.UNDEF;
253 }
254 }
255 else {
256 pos += sep.length();
257 s = buf.substring(0, pos);
258 fh.readlineBuffer = new StringBuilder(buf.substring(pos));
259 }
260 return new PlString(s);
261 EOT
262 # getc FILEHANDLE
263 getc => <<'EOT',
264 PlLvalue buf = new PlLvalue();
265 PlCORE.sysread(want, fh, PlArray.construct_list_of_aliases(buf, PlCx.INT1));
266 return buf;
267 EOT
268 # read FILEHANDLE,SCALAR,LENGTH,OFFSET?
269 read => <<'EOT',
270 return PlCORE.sysread(want, fh, List__);
271 EOT
272 # sysread FILEHANDLE,SCALAR,LENGTH,OFFSET?
273 # result is stored in $_[0]
274 # result may be utf8 or not
275 # returns number of bytes read
276 # set $! on error
277 sysread => <<'EOT',
278 int leng = List__.aget(1).to_int();
279 int ofs = List__.aget(2).to_int();
280  
281 if (fh.eof) {
282 return PlCx.UNDEF;
283 }
284 StringBuilder buf = fh.readlineBuffer;
285 // read from filehandle until "len"
286 int pos = buf.length();
287 while (pos < leng && !fh.eof) {
288 // read more
289 int len = 1000;
290 char[] c = new char[len];
291 int num_chars = 0;
292 try {
293 num_chars = fh.reader.read(c, 0, len);
294 if (num_chars > 0) {
295 // TODO - use: new String(bytes,"UTF-8")
296 String s = new String(c, 0, num_chars);
297 buf.append(s);
298 }
299 }
300 catch(IOException e) {
301 PlV.sset("main::!", new PlStringLazyError(e));
302 return PlCx.UNDEF;
303 }
304 if (num_chars > 0) {
305 pos = buf.length();
306 }
307 else {
308 // eof
309 fh.eof = true;
310 }
311 }
312 String s;
313 if (fh.eof || pos < leng) {
314 s = buf.toString();
315 fh.readlineBuffer = new StringBuilder();
316 fh.eof = true;
317 if (s.length() == 0) {
318 return PlCx.UNDEF;
319 }
320 }
321 else {
322 s = buf.substring(0, leng);
323 fh.readlineBuffer = new StringBuilder(buf.substring(leng));
324 }
325  
326 leng = s.length();
327 if (ofs == 0) {
328 List__.aset(0, s);
329 }
330 else {
331 die("TODO: sysread with OFFSET");
332 }
333 return new PlInt(leng);
334 EOT
335 # seek FILEHANDLE,POSITION,WHENCE
336 seek => <<'EOT',
337 int position = List__.aget(0).to_int();
338 int whence = List__.aget(1).to_int();
339 try {
340  
341 // TODO - random access files, more tests
342 // See: http://stackoverflow.com/questions/262618/java-bufferedreader-back-to-the-top-of-a-text-file
343  
344 // position = 0
345 if (fh.reader == null) {
346 PlV.sset("main::!", new PlString("File is not open"));
347 return PlCx.UNDEF;
348 }
349 fh.reader.reset();
350 fh.readlineBuffer = new StringBuilder();
351 fh.eof = false;
352  
353 if (position > 0) {
354 PlCORE.read(PlCx.VOID, fh, new PlArray(PlCx.UNDEF, new PlInt(position)));
355 }
356  
357 }
358 catch(IOException e) {
359 PlV.sset("main::!", new PlStringLazyError(e));
360 return PlCx.UNDEF;
361 }
362 return PlCx.INT1;
363 EOT
364  
365 );
366  
367  
368 sub emit_java {
369 return <<'EOT',
370  
371 class PlCORE {
372 EOT
373 # emit all file-related functions
374 ( map {
375 " public static final PlObject $_(int want, PlFileHandle fh, PlArray List__) {\n"
376 . $FileFunc{$_}
377 . " }\n"
378 } sort keys %FileFunc
379 ),
380 <<'EOT',
381 public static final PlObject write(int want, PlArray List__) {
382 return PlCORE.write(PlCx.VOID, PlV.selectedFileHandle, List__);
383 }
384 public static final PlObject close(int want, PlArray List__) {
385 return PlCORE.close(PlCx.VOID, PlV.selectedFileHandle, List__);
386 }
387 public static final PlObject open(int want, PlFileHandle fh, PlArray List__, String namespace) {
388 // open FILEHANDLE,EXPR
389 // open FILEHANDLE,MODE,EXPR
390 // open FILEHANDLE,MODE,EXPR,LIST
391 // open FILEHANDLE,MODE,REFERENCE
392 // open FILEHANDLE
393 try {
394 int argCount = List__.to_int();
395 Path path = null;
396 // PlCORE.say("open " + List__.toString());
397  
398 PlFileHandle.allOpenFiles.add(fh);
399 fh.readlineBuffer = new StringBuilder();
400 fh.flush();
401 fh.eof = false;
402 if (fh.outputStream != null) {
403 fh.outputStream.close();
404 }
405 if (fh.reader != null) {
406 fh.reader.close();
407 }
408  
409 // As a shortcut a one-argument call takes the filename from the
410 // global scalar variable of the same name as the filehandle
411 PlObject arg =
412 argCount == 0 ? PlV.sget(fh.typeglob_name)
413 : argCount == 1 ? List__.aget(0)
414 : List__.aget(1);
415  
416 String mode = List__.aget(0).toString();
417 String s = arg.toString();
418 if (argCount < 2) {
419 mode = "";
420 if (s.length() > 0 && s.charAt(0) == '+') {
421 mode = mode + s.substring(0, 1);
422 s = s.substring(1);
423 }
424 if (s.length() > 1 && s.substring(0, 2).equals(">>")) {
425 mode = mode + s.substring(0, 2);
426 s = s.substring(2);
427 }
428 else if (s.length() > 0 && (s.charAt(0) == '>' || s.charAt(0) == '<')) {
429 mode = mode + s.substring(0, 1);
430 s = s.substring(1);
431 }
432 if (s.length() > 0 && s.charAt(0) == '&') {
433 mode = mode + s.substring(0, 1);
434 s = s.substring(1);
435 }
436 if (s.length() > 0 && s.charAt(0) == '=') {
437 mode = mode + s.substring(0, 1);
438 s = s.substring(1);
439 }
440 while (s.length() > 0 && (s.charAt(0) == ' ' || s.charAt(0) == '\t')) {
441 s = s.substring(1);
442 }
443 }
444  
445 String charset = "ISO-8859-1";
446 int pos;
447 pos = mode.indexOf(":raw");
448 if (pos > 0) {
449 charset = "ISO-8859-1";
450 if ((pos + 4) > mode.length()) {
451 mode = mode.substring(0, pos).trim();
452 }
453 else {
454 mode = ( mode.substring(0, pos) + mode.substring(pos + 4) ).trim();
455 }
456 }
457 pos = mode.indexOf(":bytes");
458 if (pos > 0) {
459 charset = "ISO-8859-1";
460 if ((pos + 6) > mode.length()) {
461 mode = mode.substring(0, pos).trim();
462 }
463 else {
464 mode = ( mode.substring(0, pos) + mode.substring(pos + 6) ).trim();
465 }
466 }
467 pos = mode.indexOf(":encoding(");
468 if (pos > 0) {
469 // extract the charset specification
470 int last = mode.indexOf(")", pos);
471 if (last > 0) {
472 charset = mode.substring(pos + 10, last);
473 if ((last + 1) > mode.length()) {
474 mode = mode.substring(0, pos).trim();
475 }
476 else {
477 mode = ( mode.substring(0, pos) + mode.substring(last + 1) ).trim();
478 }
479  
480 if (charset.equals("Latin1")) {
481 charset = "ISO-8859-1";
482 }
483 if (charset.equals("utf8")) {
484 charset = "UTF-8";
485 }
486 if (charset.equals("utf16")) {
487 charset = "UTF-16";
488 }
489 }
490 }
491 pos = mode.indexOf(":utf8");
492 if (pos > 0) {
493 charset = "UTF-8";
494 if ((pos + 5) > mode.length()) {
495 mode = mode.substring(0, pos).trim();
496 }
497 else {
498 mode = ( mode.substring(0, pos) + mode.substring(pos + 5) ).trim();
499 }
500 }
501 // PlCORE.say("charset [" + charset + "] mode [" + mode + "]");
502  
503 // save the info for binmode()
504 fh.mode = mode; // ">", "+<"
505 fh.charset = charset; // "UTF-8"
506  
507 // modes that don't need a "path"
508  
509 if (arg.ref_str().equals("SCALAR")) {
510 // read-write to Perl scalarref
511 PlObject o = arg.scalar_deref("main");
512 fh.reader = new PlStringReader(o);
513 fh.reader.mark(o.toString().length());
514 fh.outputStream = null;
515 return PlCx.INT1;
516 }
517 else if (mode.equals("<&") || mode.equals(">&")) {
518 // "dup" a filehandle
519 PlFileHandle fh2 = PerlOp.get_filehandle(arg, namespace);
520 fh.dupFileHandle(fh2);
521 return PlCx.INT1;
522 }
523  
524 // the other modes need a "path"
525  
526 path = PlV.path.resolve(s);
527 // save the info for binmode()
528 fh.path = path; // filename
529 // PlCORE.say("path " + mode + " " + path.toString() + " arg " + arg.toString());
530  
531 if (mode.equals("<") || mode.equals("")) {
532 fh.reader = Files.newBufferedReader(path, Charset.forName(charset));
533 fh.outputStream = null;
534 }
535 else if (mode.equals(">")) {
536 fh.reader = null;
537 fh.outputStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
538 }
539 else if (mode.equals(">>")) {
540 fh.reader = null;
541 fh.outputStream = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);
542 }
543 else if (mode.equals("+<")) {
544 // read/write
545 // TODO - share the IO buffer for reads and writes
546 fh.reader = Files.newBufferedReader(path, Charset.forName(charset));
547 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
548 }
549 else if (mode.equals("+>")) {
550 // read/write, truncate first
551 // TODO - share the IO buffer for reads and writes
552 fh.reader = Files.newBufferedReader(path, Charset.forName(charset));
553 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
554 }
555 else if (mode.equals("<-")) {
556 // In the two-argument (and one-argument) form, opening "<-" or
557 // "-" opens STDIN and opening ">-" opens STDOUT.
558 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
559 }
560 else if (mode.equals(">-")) {
561 // In the two-argument (and one-argument) form, opening "<-" or
562 // "-" opens STDIN and opening ">-" opens STDOUT.
563 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
564 }
565 else if (mode.equals("|-")) {
566 // For three or more arguments if MODE is "|-", the filename is
567 // interpreted as a command to which output is to be piped, and if
568 // MODE is "-|", the filename is interpreted as a command that
569 // pipes output to us. In the two-argument (and one-argument)
570 // form, one should replace dash ("-") with the command. See
571 // "Using open() for IPC" in perlipc for more examples of this.
572 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
573 }
574 else if (mode.equals("-|")) {
575 // For three or more arguments if MODE is "|-", the filename is
576 // interpreted as a command to which output is to be piped, and if
577 // MODE is "-|", the filename is interpreted as a command that
578 // pipes output to us. In the two-argument (and one-argument)
579 // form, one should replace dash ("-") with the command. See
580 // "Using open() for IPC" in perlipc for more examples of this.
581 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
582 }
583 else {
584 PlCORE.die("TODO - not implemented: open() mode '" + mode + "'");
585 }
586 path = path.toRealPath();
587 // PlCORE.say("path " + mode + " " + path.toString());
588  
589 // success
590 return PlCx.INT1;
591 }
592 catch(NoSuchFileException e) {
593 PlV.sset("main::!", new PlString("No such file or directory"));
594 }
595 catch(Exception e) {
596 PlV.sset("main::!", new PlStringLazyError(e));
597 }
598 return PlCx.UNDEF;
599 }
600 public static final PlObject print(int want, PlFileHandle fh, String... args) {
601 try {
602 StringBuilder printBuffer = fh.printBuffer;
603 for (String s : args) {
604 printBuffer.append(s);
605 }
606 if (!PlV.Scalar_OUTPUT_RECORD_SEPARATOR.is_undef()) {
607 printBuffer.append(PlV.Scalar_OUTPUT_RECORD_SEPARATOR.toString());
608 }
609 if (fh.output_autoflush) {
610 // $| autoflush is active
611 fh.flush();
612 }
613 else {
614 int s_length = printBuffer.length();
615 if (s_length > 0) {
616 char cc = printBuffer.charAt(s_length-1);
617 if (cc == '\n' || cc == '\r') {
618 fh.flush();
619 }
620 else if (s_length > PlFileHandle.BUFFER_THRESHOLD) {
621 fh.flush();
622 }
623 }
624 }
625 return PlCx.INT1;
626 }
627 catch(Exception e) {
628 PlV.sset("main::!", new PlStringLazyError(e));
629 return PlCx.UNDEF;
630 }
631 }
632 public static final PlObject say(int want, PlFileHandle fh, String... args) {
633 PlObject sep = PlV.Scalar_OUTPUT_RECORD_SEPARATOR.get();
634 PlV.Scalar_OUTPUT_RECORD_SEPARATOR.set(new PlString("\n"));
635 PlObject ret = PlCORE.print(want, fh, args);
636 PlV.Scalar_OUTPUT_RECORD_SEPARATOR.set(sep);
637 return ret;
638 }
639  
640 EOT
641 <<'EOT',
642  
643 // shortcut functions for internal use: say, warn, die
644 public static final PlObject say(String s) {
645 return PlCORE.say(PlCx.VOID, PlV.selectedFileHandle, s);
646 }
647 public static final PlObject warn(String s) {
648 return PlCORE.warn(PlCx.VOID, new PlArray(new PlString(s)));
649 }
650 public static final PlObject die(String s) {
651 return PlCORE.die(PlCx.VOID, new PlArray(new PlString(s)));
652 }
653 public static final PlObject die(PlObject s) {
654 return PlCORE.die(PlCx.VOID, new PlArray(s));
655 }
656  
657 public static final PlObject mkdir(int want, PlArray List__) {
658 try {
659 Path path = PlV.path.resolve(List__.aget(0).toString());
660 int mask = List__.aget(1).to_int();
661 Set<PosixFilePermission> perms = PerlOp.MaskToPermissions(mask);
662 FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
663 Files.createDirectory(path, attr);
664 return PlCx.INT1;
665 }
666 catch(IOException e) {
667 PlV.sset("main::!", new PlStringLazyError(e));
668 }
669 return PlCx.UNDEF;
670 }
671 public static final PlObject require(int want, PlObject file, boolean is_bareword) {
672 // TODO - require-version
673 if (is_bareword) {
674 file = new PlString("Perlito5::Grammar::Use::modulename_to_filename").apply(PlCx.SCALAR, new PlArray(file));
675 }
676 return new PlString("Perlito5::Grammar::Use::require").apply(want, new PlArray(file));
677 }
678 public static final PlObject rmdir(int want, PlArray List__) {
679 try {
680 Path path = PlV.path.resolve(List__.aget(0).toString()).toRealPath();
681 Files.delete(path);
682 return PlCx.INT1;
683 }
684 catch(NoSuchFileException e) {
685 PlV.sset("main::!", new PlString("No such file or directory"));
686 }
687 catch(DirectoryNotEmptyException e) {
688 PlV.sset("main::!", new PlString("Directory not empty"));
689 }
690 catch(IOException e) {
691 PlV.sset("main::!", new PlStringLazyError(e));
692 }
693 return PlCx.UNDEF;
694 }
695 public static final PlObject chdir(int want, PlArray List__) {
696 try {
697 Path path = PlV.path.resolve(List__.aget(0).toString()).toRealPath();
698 PlV.path = path;
699 // TODO - test that the destination is a directory
700 return PlCx.INT1;
701 }
702 catch(NoSuchFileException e) {
703 PlV.sset("main::!", new PlString("No such file or directory"));
704 }
705 catch(DirectoryNotEmptyException e) {
706 PlV.sset("main::!", new PlString("Directory not empty"));
707 }
708 catch(IOException e) {
709 PlV.sset("main::!", new PlStringLazyError(e));
710 }
711 return PlCx.UNDEF;
712 }
713 public static final PlObject unlink(int want, PlArray List__) {
714 try {
715 for (int i = 0; i < List__.to_int(); i++) {
716 Path path = PlV.path.resolve(List__.aget(i).toString()).toRealPath();
717 Files.delete(path);
718 }
719 return PlCx.INT1;
720 }
721 catch(NoSuchFileException e) {
722 PlV.sset("main::!", new PlString("No such file or directory"));
723 }
724 catch(DirectoryNotEmptyException e) {
725 PlV.sset("main::!", new PlString("Directory not empty"));
726 }
727 catch(IOException e) {
728 PlV.sset("main::!", new PlStringLazyError(e));
729 }
730 return PlCx.UNDEF;
731 }
732 public static final PlObject rename(int want, PlArray List__) {
733 try {
734 Files.move(
735 PlV.path.resolve( List__.aget(0).toString() ),
736 PlV.path.resolve( List__.aget(1).toString() ),
737 java.nio.file.StandardCopyOption.REPLACE_EXISTING
738 );
739 return PlCx.INT1;
740 }
741 catch(NoSuchFileException e) {
742 PlV.sset("main::!", new PlString("No such file or directory"));
743 }
744 catch(IOException e) {
745 PlV.sset("main::!", new PlStringLazyError(e));
746 }
747 return PlCx.UNDEF;
748 }
749 public static final PlObject lstat(int want, PlArray List__) {
750 // TODO
751 return PlCORE.stat(want, List__);
752 }
753 public static final PlObject stat(int want, PlArray List__) {
754 // TODO - "_" filehandle
755 PlArray res = new PlArray();
756 PlObject arg = List__.aget(0);
757 try {
758 // 0 dev device number of filesystem
759 // 1 ino inode number
760 // 2 mode file mode (type and permissions)
761 // 3 nlink number of (hard) links to the file
762 // 4 uid numeric user ID of file's owner
763 // 5 gid numeric group ID of file's owner
764 // 6 rdev the device identifier (special files only)
765 // 7 size total size of file, in bytes
766 // 8 atime last access time in seconds since the epoch
767 // 9 mtime last modify time in seconds since the epoch
768 // 10 ctime inode change time in seconds since the epoch (*)
769 // 11 blksize preferred I/O size in bytes for interacting with the
770 // file (may vary from file to file)
771 // 12 blocks actual number of system-specific blocks allocated
772 // on disk (often, but not always, 512 bytes each)
773 res.aset(7, PerlOp.p5size(arg));
774 res.aset(9, PerlOp.p5mtime(arg));
775 if (want == PlCx.SCALAR) {
776 return PlCx.TRUE;
777 }
778 return res;
779 }
780 catch(Exception e) {
781 PlV.sset("main::!", new PlStringLazyError(e));
782 }
783 if (want == PlCx.SCALAR) {
784 return PlCx.FALSE;
785 }
786 return res;
787 }
788 public static final PlObject select(PlFileHandle fh) {
789 // select FILEHANDLE
790 PlFileHandle fOld = PlV.selectedFileHandle;
791 PlV.selectedFileHandle = fh;
792  
793 // point the "format" variables to the selected filehandle
794 PlV.sset_alias("main::" + (char)12, fh.format_formfeed); // $^L
795 PlV.sset_alias("main::%", fh.format_page_number); // $%
796 PlV.sset_alias("main::-", fh.format_lines_left); // $-
797 PlV.sset_alias("main:::", fh.format_line_break_characters); // $:
798 PlV.sset_alias("main::=", fh.format_lines_per_page); // $=
799 PlV.sset_alias("main::^", fh.format_top_name); // $^
800 PlV.sset_alias("main::~", fh.format_name); // $~
801  
802 return fOld;
803 }
804 public static final PlObject select(int want, PlArray List__) {
805 int arg_count = List__.length_of_array_int();
806 if (arg_count == 0) {
807 // Returns the currently selected filehandle
808 return PlV.selectedFileHandle;
809 }
810 if (arg_count == 4) {
811 if (List__.aget(0).is_undef() && List__.aget(1).is_undef() && List__.aget(2).is_undef()) {
812 // You can effect a sleep of 250 milliseconds this way: select(undef, undef, undef, 0.25);
813 PlCORE.sleep(want, new PlArray(List__.aget(3)));
814 return PlCx.INT0;
815 }
816 }
817 return PlCORE.die("select() not implemented");
818 }
819 public static final PlObject exit(int want, PlArray List__) {
820 int arg = List__.aget(0).to_int();
821  
822 PlV.teardown();
823 System.exit(arg);
824 return PlCx.UNDEF;
825 }
826 public static final PlObject warn(int want, PlArray List__) {
827 try {
828 int arg_count = List__.length_of_array_int();
829 if (arg_count == 0) {
830 List__.push_void("Warning: something's wrong");
831 }
832 if (arg_count != 1 || !List__.aget(0).is_ref()) {
833 String s = List__.toString();
834 int s_length = s.length();
835 if (s_length > 0 && (s.charAt(s_length-1) == '\n' || s.charAt(s_length-1) == '\r')) {
836 // don't add file+line
837 }
838 else {
839 // TODO - add module name, line number
840 s = s + " at " + PlV.sget("main::0") + "\n";
841 }
842 List__.set(new PlArray(new PlString(s)));
843 }
844 if (PlV.hash_get("main::SIG").hget("__WARN__").is_coderef()) {
845 // execute $SIG{__WARN__}
846 // localize $SIG{__WARN__} during the call
847 int tmp = PerlOp.local_length();
848 PlObject c = PlV.hash_get("main::SIG").hget("__WARN__");
849 PlV.hash_get("main::SIG").hget_lvalue_local("__WARN__");
850 c.apply(want, List__);
851 PerlOp.cleanup_local(tmp, PlCx.UNDEF);
852 }
853 else {
854 String s = List__.toString();
855 byte[] bytes = s.getBytes(PlV.STDERR.charset);
856 PlV.STDERR.outputStream.write(bytes);
857 PlV.STDERR.outputStream.flush();
858 }
859 return PlCx.INT1;
860 }
861 catch(Exception e) {
862 PlV.sset("main::!", new PlStringLazyError(e));
863 return PlCx.UNDEF;
864 }
865 }
866 public static final PlObject die(int want, PlArray List__) {
867 int arg_count = List__.length_of_array_int();
868 if (arg_count == 0) {
869 List__.push_void("Died");
870 }
871 if (arg_count != 1 || !List__.aget(0).is_ref()) {
872 String s = List__.toString();
873 int s_length = s.length();
874 if (s_length > 0 && (s.charAt(s_length-1) == '\n' || s.charAt(s_length-1) == '\r')) {
875 // don't add file+line
876 }
877 else {
878 // TODO - add module name, line number
879 s = s + " at " + PlV.sget("main::0") + "\n";
880 // Java stack trace
881 s = s + Arrays.toString(new Throwable().getStackTrace());
882 }
883 List__.set(new PlArray(new PlString(s)));
884 }
885 if (PlV.hash_get("main::SIG").hget("__DIE__").is_coderef()) {
886 // execute $SIG{__DIE__}
887 // localize $SIG{__DIE__} during the call
888 int tmp = PerlOp.local_length();
889 PlObject c = PlV.hash_get("main::SIG").hget("__DIE__");
890 PlV.hash_get("main::SIG").hget_lvalue_local("__DIE__");
891 c.apply(want, List__);
892 PerlOp.cleanup_local(tmp, PlCx.UNDEF);
893 }
894 PlObject arg = List__.aget(0);
895 throw new PlDieException(arg);
896 }
897 // public static final PlString ref(int want, PlArray List__) {
898 // return List__.aget(0).ref();
899 // }
900 public static final PlObject values(int want, PlObject List__) {
901 return want == PlCx.LIST ? List__.values() : List__.values().scalar();
902 }
903 public static final PlObject keys(int want, PlObject List__) {
904 return want == PlCx.LIST ? List__.keys() : List__.keys().scalar();
905 }
906 public static final PlObject each(int want, PlObject List__) {
907 return want == PlCx.LIST ? List__.each() : List__.each().aget(0);
908 }
909 public static final PlObject chomp(int want, PlObject Object__) {
910 String sep = PlV.sget("main::/").toString();
911 int sepSize = sep.length();
912 int result = 0;
913 String toChomp = Object__.toString();
914 if(toChomp.substring(toChomp.length() - sepSize, toChomp.length()).equals(sep)) {
915 toChomp = toChomp.substring(0, toChomp.length() - sepSize);
916 result += sepSize;
917 }
918  
919 Object__.set(new PlString(toChomp));
920
921 return new PlInt(result);
922 }
923 public static final PlObject chomp(int want, PlArray List__) {
924 int result = 0;
925 for(int i = 0; i < List__.to_int(); ++i) {
926 PlObject item = List__.aget_lvalue(i);
927 result += chomp(want, item).to_int();
928 }
929  
930 return new PlInt(result);
931 }
932 public static final PlString chop(int want, PlObject Object__) {
933 String str = Object__.toString();
934 String returnValue = "";
935 if (str.length() > 0) {
936 returnValue = str.substring(str.length() -1);
937 Object__.set(new PlString(str.substring(0, str.length()-1)));
938 }
939  
940 return new PlString(returnValue);
941 }
942 public static final PlObject chop(int want, PlArray List__) {
943 PlString result = PlCx.EMPTY;
944 for(int i = 0; i < List__.to_int(); ++i) {
945 PlObject item = List__.aget_lvalue(i);
946 result = chop(want, item);
947 }
948  
949 return result;
950 }
951 public static final PlScalarImmutable scalar(int want, PlArray List__) {
952 if (List__.to_int() == 0) {
953 return PlCx.UNDEF;
954 }
955 return List__.aget(-1).scalar();
956 }
957 public static final PlObject splice(int want, PlArray List__) {
958 PlArray res = new PlArray(List__);
959 List__.a.clear();
960 if (want == PlCx.LIST) {
961 return res;
962 }
963 if (res.to_int() == 0) {
964 return PlCx.UNDEF;
965 }
966 return res.aget(-1);
967 }
968 public static final PlObject split(int want, PlObject plReg, PlObject plArg, PlObject plCount) {
969 if (want == PlCx.SCALAR) {
970 return PlCORE.split(PlCx.LIST, plReg, plArg, plCount).length_of_array();
971 }
972 int limit = plCount.to_int();
973 PlArray res = new PlArray();
974 if (limit == 0) {
975  
976 // TODO - possible optimization for: split("", $str)
977 // if (plReg.is_string() && plReg.toString().length() == 0) {
978 // // split "", $string, 0
979 // return new PlArray(plArg.toString().toCharArray());
980 // }
981  
982 // strip trailing empty strings and undef
983 res = (PlArray)PlCORE.split(PlCx.LIST, plReg, plArg, PlCx.MIN1);
984 while (res.to_int() > 0) {
985 PlObject item = res.aget(-1);
986 if (item.is_undef() || item.toString().length() == 0) {
987 res.pop();
988 }
989 else {
990 return res;
991 }
992 }
993 return res;
994 }
995 String arg = plArg.toString();
996 if (arg.length() == 0) {
997 return res;
998 }
999 // make sure pattern is a RegExp
1000 if (plReg.is_lvalue()) {
1001 plReg = plReg.get();
1002 }
1003  
1004 // --- TODO ---
1005  
1006 if (!plReg.is_regex()) {
1007 String regs = plReg.toString();
1008 if (regs.equals(" ")) {
1009  
1010 // ltrim
1011 int i = 0;
1012 while (i < arg.length() && Character.isWhitespace(arg.charAt(i))) {
1013 i++;
1014 }
1015 if (i > 0) {
1016 arg = arg.substring(i);
1017 }
1018  
1019 plReg = PlCx.SPLIT_SPACE;
1020 }
1021 else {
1022 plReg = new PlRegex(regs, Pattern.MULTILINE, false);
1023 }
1024 }
1025  
1026 Pattern pat = ((PlRegex)plReg).p;
1027  
1028 // // make sure pattern is a RegExp
1029 // if (typeof pattern === "object" && (pattern instanceof RegExp)) {
1030 // pattern = pattern.source;
1031 // }
1032 // else {
1033 // pattern = p5str(pattern);
1034 // if (pattern == " ") {
1035 // // single space string is special
1036 // pattern = "(?: |\t|\n)+";
1037 // s = s.replace(/^(?: |\t|\n)+/, "");
1038 // }
1039 // }
1040 // // add "g", "m" modifiers
1041 // var flags = "g";
1042 // if (pattern.substr(0, 1) == "^" || pattern.substr(-1,1) == "$") {
1043 // flags = flags + "m";
1044 // }
1045 // --- /TODO ---
1046  
1047 int pos = 0;
1048 int next = pos;
1049 int count = 1;
1050 String cap;
1051 Matcher matcher = pat.matcher(arg).useTransparentBounds(true);
1052 while (pos < arg.length() && !(limit > 0 && count >= limit) && matcher.find(next)) {
1053 boolean matched = true;
1054 if (matcher.end() == pos) {
1055 // pointer didn't move
1056 next++;
1057 matched = matcher.find(next);
1058 }
1059 if (matched) {
1060 cap = arg.substring(pos, matcher.start());
1061 res.push_void(cap);
1062 pos = matcher.end();
1063 next = pos;
1064 // PlCORE.say("match: match [" + cap + "] next pos " + pos);
1065 count++;
1066 for (int i = 1; i <= matcher.groupCount(); i++) {
1067 cap = matcher.group(i);
1068 if (cap == null) {
1069 res.push_void(PlCx.UNDEF);
1070 }
1071 else {
1072 res.push_void(cap);
1073 }
1074 }
1075 }
1076 }
1077 if ( pos >= arg.length()) {
1078 cap = "";
1079 }
1080 else {
1081 cap = arg.substring(pos);
1082 }
1083 res.push_void(cap);
1084 return res;
1085 }
1086 public static final PlObject splice(int want, PlArray List__, PlObject offset) {
1087 int size = List__.to_int();
1088 int pos = offset.to_int();
1089 if (pos < 0) {
1090 pos = List__.a.size() + pos;
1091 }
1092 if (pos < 0 || pos > List__.a.size()) {
1093 return PlCx.UNDEF;
1094 }
1095 PlArray res = new PlArray();
1096 for (int i = pos; i < size; i++) {
1097 res.unshift(List__.pop());
1098 }
1099 if (want == PlCx.LIST) {
1100 return res;
1101 }
1102 if (res.to_int() == 0) {
1103 return PlCx.UNDEF;
1104 }
1105 return res.aget(-1);
1106 }
1107 public static final PlObject splice(int want, PlArray List__, PlObject offset, PlObject length) {
1108 int size = List__.to_int();
1109 int pos = offset.to_int();
1110 if (pos < 0) {
1111 pos = List__.a.size() + pos;
1112 }
1113 if (pos < 0 || pos > List__.a.size()) {
1114 return PlCx.UNDEF;
1115 }
1116  
1117 int last = length.to_int();
1118 if (last < 0) {
1119 last = List__.a.size() + last;
1120 }
1121 else {
1122 last = pos + last;
1123 }
1124 if (last < 0) {
1125 return PlCx.UNDEF;
1126 }
1127 if (last > size) {
1128 last = size;
1129 }
1130  
1131 int diff = last - pos;
1132 PlArray res = new PlArray();
1133 for (int i = pos; i < last; i++) {
1134 res.push_void(List__.a.get(i));
1135 }
1136 for (int i = pos; i < (size - diff); i++) {
1137 List__.a.set(i, List__.a.get(i+diff));
1138 }
1139 for (int i = 0; i < diff; i++) {
1140 List__.pop();
1141 }
1142 if (want == PlCx.LIST) {
1143 return res;
1144 }
1145 if (res.to_int() == 0) {
1146 return PlCx.UNDEF;
1147 }
1148 return res.aget(-1);
1149 }
1150 public static final PlObject splice(int want, PlArray List__, PlObject offset, PlObject length, PlArray list) {
1151 int size = List__.to_int();
1152 int pos = offset.to_int();
1153 if (pos < 0) {
1154 pos = List__.a.size() + pos;
1155 }
1156 if (pos < 0 || pos > List__.a.size()) {
1157 return PlCx.UNDEF;
1158 }
1159  
1160 int last = length.to_int();
1161 if (last < 0) {
1162 last = List__.a.size() + last;
1163 }
1164 else {
1165 last = pos + last;
1166 }
1167 if (last < 0) {
1168 return PlCx.UNDEF;
1169 }
1170 if (last > size) {
1171 last = size;
1172 }
1173  
1174 int diff = last - pos;
1175 PlArray res = new PlArray();
1176  
1177 for (int i = pos; i < last; i++) {
1178 res.push_void(List__.a.get(i));
1179 }
1180 for (int i = pos; i < (size - diff); i++) {
1181 List__.a.set(i, List__.a.get(i+diff));
1182 }
1183 for (int i = 0; i < diff; i++) {
1184 List__.pop();
1185 }
1186  
1187 List__.a.addAll(pos, list.a);
1188 if (want == PlCx.LIST) {
1189 return res;
1190 }
1191 if (res.to_int() == 0) {
1192 return PlCx.UNDEF;
1193 }
1194 return res.aget(-1);
1195 }
1196  
1197 EOT
1198 <<'EOT',
1199  
1200 public static final PlInt hex(int want, PlObject List__) {
1201 String s = List__.toString();
1202  
1203 final int length = s.length();
1204 int c;
1205  
1206 for (int i = 0; i < length; i++ ) {
1207 c = s.codePointAt(i);
1208 if (c > 254) {
1209 PlCORE.die("Wide character in hex");
1210 }
1211 }
1212  
1213 if (s.startsWith("0x") || s.startsWith("0X")) {
1214 s = s.substring(2);
1215 }
1216 else if (s.startsWith("x") || s.startsWith("X")) {
1217 s = s.substring(1);
1218 }
1219 s = s.replace("_","");
1220 try {
1221 return new PlInt(Long.parseLong(s, 16));
1222 } catch (java.lang.NumberFormatException e) {
1223 // result = e.getMessage();
1224 }
1225 return new PlInt(0);
1226 }
1227 public static final PlInt oct(int want, PlObject List__) {
1228 String s = List__.toString();
1229 return new PlInt(PerlOp.oct(s));
1230 }
1231 public static final PlString sprintf(int want, PlObject List__) {
1232 String format = List__.aget(0).toString();
1233 // "%3s"
1234 int length = format.length();
1235 int offset = 0;
1236 int args_max = List__.to_int();
1237 int args_index = 0;
1238 Object args[] = new Object[args_max];
1239 String detail = "";
1240 int start_detail = -1;
1241 for ( ; offset < length; ) {
1242 int c = format.codePointAt(offset);
1243 switch (c) {
1244 case '%':
1245 offset++;
1246 boolean scanning = true;
1247 start_detail = offset;
1248 for ( ; offset < length && scanning ; ) {
1249 c = format.codePointAt(offset);
1250 switch (c) {
1251 case '%':
1252 scanning = false;
1253 offset++;
1254 break;
1255 case 'v':
1256 // TODO - format value like "v1.v2.v3"
1257 // replace "%vd" with "%s"
1258 scanning = false;
1259 StringBuilder sbv = new StringBuilder();
1260 if (offset > 0) {
1261 sbv.append(format.substring(0, offset));
1262 }
1263 sbv.append("s"); // replace "vd" with "s"
1264 if (offset + 2 < format.length()) {
1265 sbv.append(format.substring(offset + 2)); // skip "v" and "d"
1266 }
1267 format = sbv.toString();
1268 length = format.length();
1269 args[args_index] = PlV.sub_sprintf_vd.apply(PlCx.SCALAR, PlArray.construct_list_of_aliases(List__.aget(args_index+1))).toString();
1270 args_index++;
1271 if (args_index > args_max) {
1272 // panic
1273 offset = length;
1274 }
1275 offset++; // skip "v"
1276 break;
1277 case 'c': case 's': case 'd': case 'u': case 'o':
1278 case 'x': case 'e': case 'f': case 'g':
1279 case 'X': case 'E': case 'G': case 'b':
1280 case 'B': case 'p': case 'n':
1281 case 'i': case 'D': case 'U': case 'O': case 'F':
1282 scanning = false;
1283 switch (c) {
1284 case 's':
1285 args[args_index] = List__.aget(args_index+1).toString();
1286 break;
1287 case 'd': case 'o': case 'x': case 'X':
1288 case 'u': case 'b': case 'B': case 'p':
1289 case 'c':
1290 args[args_index] = List__.aget(args_index+1).to_long();
1291  
1292 if (c == 'u') {
1293 long arg = (long)(args[args_index]);
1294 arg = arg & 4294967295L; // 0xFFFFFFFF;
1295 args[args_index] = arg;
1296 StringBuilder sb = new StringBuilder();
1297 if (offset > 0) {
1298 sb.append(format.substring(0, offset));
1299 }
1300 sb.append("d");
1301 if (offset + 1 < format.length()) {
1302 sb.append(format.substring(offset + 1));
1303 }
1304 format = sb.toString();
1305 length = format.length();
1306 //PlCORE.say("format [" + format + "]");
1307 }
1308  
1309 break;
1310 case 'f': case 'e': case 'g':
1311 case 'E': case 'G':
1312 detail = format.substring(start_detail, offset);
1313 if (detail.equals(".") || detail.equals("+.")) {
1314 StringBuilder sb = new StringBuilder();
1315 sb.append(format.substring(0, offset));
1316 sb.append("0");
1317 sb.append(format.substring(offset));
1318 format = sb.toString();
1319 length = format.length();
1320 }
1321 args[args_index] = List__.aget(args_index+1).to_double();
1322 break;
1323 default:
1324 break;
1325 }
1326 args_index++;
1327 if (args_index > args_max) {
1328 // panic
1329 offset = length;
1330 }
1331 offset++;
1332 break;
1333 default:
1334 offset++;
1335 break;
1336 }
1337 }
1338 break;
1339 default:
1340 offset++;
1341 break;
1342 }
1343 }
1344 return new PlString(String.format(format, args));
1345 }
1346 public static final PlString crypt(int want, PlArray List__) {
1347 if(List__.to_int() < 2) {
1348 die("Not enough arguments for crypt");
1349 }
1350 if(List__.to_int() > 2) {
1351 die("Too many arguments for crypt");
1352 }
1353 String plainText = List__.shift().toString();
1354 String salt = List__.shift().toString();
1355  
1356 while(salt.length() < 2) {
1357 salt = salt.concat(".");
1358 }
1359
1360 return new PlString(PlCrypt.crypt(salt, plainText));
1361 }
1362 public static final PlString join(int want, String s1, PlObject... args) {
1363 StringBuilder sb = new StringBuilder();
1364 boolean first = true;
1365 for (PlObject s : args) {
1366 if (s.is_hash()) {
1367 // @x = %x;
1368 s = s.to_array();
1369 }
1370 if (s.is_array()) {
1371 // @x = ( @x, @y );
1372 for (int i = 0; i < s.to_long(); i++) {
1373 if (first)
1374 first = false;
1375 else
1376 sb.append(s1);
1377 sb.append(s.aget(i).toString());
1378 }
1379 }
1380 else {
1381 if (first)
1382 first = false;
1383 else
1384 sb.append(s1);
1385 sb.append(s.toString());
1386 }
1387 }
1388 return new PlString(sb.toString());
1389 }
1390 public static final PlObject reverse(int want, PlArray List__) {
1391 if (want == PlCx.LIST) {
1392 PlArray ret = PlArray.construct_list_of_aliases(List__);
1393 Collections.reverse(ret.a);
1394 return ret;
1395 }
1396 StringBuilder sb = new StringBuilder();
1397 if (List__.to_int() == 0) {
1398 sb.append( PlV.Scalar_ARG.get() );
1399 }
1400 else {
1401 for (int i = 0; i < List__.to_int(); i++) {
1402 sb.append( List__.aget(i).toString() );
1403 }
1404 }
1405 return new PlString(sb.reverse().toString());
1406 }
1407 public static final PlString fc(int want, PlObject Object__) {
1408 return new PlString(Object__.toString().toLowerCase());
1409 }
1410 public static final PlObject pack(int want, PlArray List__) {
1411 String template = List__.shift().toString();
1412 StringBuilder result = new StringBuilder();
1413  
1414 // Character mode is the default unless the format string starts with "U"
1415 boolean characterMode = true;
1416 if (template.length() > 0 && template.charAt(0) == 'U') {
1417 characterMode = false;
1418 }
1419  
1420 for(int i = 0; i < template.length(); ++i) {
1421 int size;
1422 if (template.length() > (i+1) && template.charAt(i+1) == '*') {
1423 size = List__.to_int();
1424 }
1425 else {
1426 size = pack_size(template, i);
1427 }
1428  
1429 switch(template.charAt(i)) {
1430 case 'a':
1431 {
1432 result.append(pack_a(List__.shift().toString(), size));
1433 break;
1434 }
1435 case 'A':
1436 {
1437 result.append(pack_A(List__.shift().toString(), size));
1438 break;
1439 }
1440 case 'Z':
1441 {
1442 result.append(pack_Z(List__.shift().toString(), size));
1443 break;
1444 }
1445 case 'b':
1446 {
1447 result.append(pack_b(List__.shift().toString(), size));
1448 break;
1449 }
1450 case 'B':
1451 {
1452 result.append(pack_B(List__.shift().toString(), size));
1453 break;
1454 }
1455 case 'h':
1456 {
1457 result.append(pack_h(List__.shift().toString(), size));
1458 break;
1459 }
1460 case 'H':
1461 {
1462 result.append(pack_H(List__.shift().toString(), size));
1463 break;
1464 }
1465 case 'c':
1466 {
1467 result.append(pack_c(List__.shift().toString()));
1468 break;
1469 }
1470 case 'C':
1471 {
1472 if (size == 0) {
1473 // C0
1474 characterMode = true;
1475 }
1476 for (int j = 0; j < size; j++) {
1477 result.append(pack_C(List__.shift().toString()));
1478 }
1479 break;
1480 }
1481 case 'W':
1482 {
1483 for (int j = 0; j < size; j++) {
1484 result.appendCodePoint( List__.shift().to_int() );
1485 }
1486 break;
1487 }
1488 case 'U':
1489 {
1490 if (size == 0) {
1491 // U0
1492 characterMode = false;
1493 }
1494 if (characterMode) {
1495 // character mode C0
1496 StringBuilder sb = new StringBuilder();
1497 for (int j = 0; j < size; j++) {
1498 sb.appendCodePoint( List__.shift().to_int() );
1499 }
1500 byte[] bytes = sb.toString().getBytes(PlCx.UTF8);
1501 for (byte b : bytes) {
1502 int ub = b < 0 ? 256 + b : b;
1503 result.appendCodePoint(ub);
1504 }
1505 }
1506 else {
1507 // U0 mode
1508 for (int j = 0; j < size; j++) {
1509 result.appendCodePoint( List__.shift().to_int() );
1510 }
1511 }
1512 break;
1513 }
1514 case 's':
1515 {
1516 result.append(pack_s(List__.shift().to_int()));
1517 break;
1518 }
1519 case 'S':
1520 {
1521 result.append(pack_S(List__.shift().to_int()));
1522 break;
1523 }
1524 case 'l':
1525 {
1526 result.append(pack_l(List__.shift().to_int()));
1527 break;
1528 }
1529 case 'L':
1530 {
1531 result.append(pack_L(List__.shift().to_int()));
1532 break;
1533 }
1534 case 'q':
1535 {
1536 result.append(pack_q(List__.shift().to_int()));
1537 break;
1538 }
1539 case 'Q':
1540 {
1541 result.append(pack_Q(List__.shift().to_int()));
1542 break;
1543 }
1544 case 'i':
1545 {
1546 result.append(pack_i(List__.shift().to_int()));
1547 break;
1548 }
1549 case 'I':
1550 {
1551 result.append(pack_I(List__.shift().to_int()));
1552 break;
1553 }
1554 case 'n':
1555 {
1556 for (int j = 0; j < size; j++) {
1557 result.append(pack_n(List__.shift().to_int()));
1558 }
1559 break;
1560 }
1561 case 'N':
1562 {
1563 result.append(pack_N(List__.shift().to_int()));
1564 break;
1565 }
1566 case 'v':
1567 {
1568 for (int j = 0; j < size; j++) {
1569 result.append(pack_v(List__.shift().to_int()));
1570 }
1571 break;
1572 }
1573 case 'V':
1574 {
1575 result.append(pack_V(List__.shift().to_int()));
1576 break;
1577 }
1578 case 'j':
1579 {
1580 result.append(pack_j(List__.shift().to_int()));
1581 break;
1582 }
1583 case 'J':
1584 {
1585 result.append(pack_J(List__.shift().to_int()));
1586 break;
1587 }
1588 case 'f':
1589 {
1590 result.append(pack_f(List__.shift().to_double()));
1591 break;
1592 }
1593 case 'd':
1594 case 'F':
1595 {
1596 result.append(pack_d(List__.shift().to_double()));
1597 break;
1598 }
1599 case 'p':
1600 {
1601 for(int k = 0; k < size; ++k) {
1602 PlObject o = List__.shift();
1603 if(o.is_undef()) {
1604 result.append(pack_q(0));
1605
1606 } else {
1607 result.append(pack_p(o.toString()));
1608 }
1609 }
1610 }
1611 case 'u':
1612 {
1613 result.append(pack_u(List__.shift().toString()));
1614 break;
1615 }
1616 case 'w':
1617 {
1618 String[] input = new String[size];
1619 for(int j = 0; j < size; ++j) {
1620 input[j] = List__.shift().toString();
1621 }
1622 result.append(pack_w(input, size));
1623 break;
1624 }
1625 case 'x':
1626 {
1627 result.append(pack_x(size));
1628 break;
1629 }
1630 case 'X':
1631 {
1632 int length = result.length();
1633 result.delete(Math.max(0,length - size), length);
1634 break;
1635 }
1636 case '@':
1637 {
1638 int length = result.length();
1639 if(size > length) {
1640 result.append(new char[size - length]);
1641 }
1642 break;
1643 }
1644 case '.':
1645 {
1646 int length = result.length();
1647 if(size > length) {
1648 result.append(new char[size - length]);
1649 }
1650 break;
1651 }
1652 default:
1653 }
1654 }
1655  
1656 return new PlString(result.toString());
1657 }
1658 public static final PlObject unpack(int want, PlArray List__) {
1659 String template = List__.aget(0).toString();
1660 String input = List__.aget(1).toString();
1661 PlArray result = new PlArray();
1662 int inputIndex = 0;
1663  
1664 // Character mode is the default unless the format string starts with "U"
1665 boolean characterMode = true;
1666 if (template.length() > 0 && template.charAt(0) == 'U') {
1667 characterMode = false;
1668 }
1669  
1670 for(int i = 0; i < template.length(); ++i) {
1671 int size;
1672 if (template.length() > (i+1) && template.charAt(i+1) == '*') {
1673 size = -1;
1674 }
1675 else {
1676 size = pack_size(template, i);
1677 }
1678  
1679 switch(template.charAt(i)) {
1680 case 'a':
1681 {
1682 // TODO
1683 // result.push_void(unpack_a(List__.shift().toString(), size));
1684 break;
1685 }
1686 case 'A':
1687 {
1688 // TODO
1689 // result.push_void(unpack_A(List__.shift().toString(), size));
1690 break;
1691 }
1692 case 'Z':
1693 {
1694 // TODO
1695 // result.push_void(unpack_Z(List__.shift().toString(), size));
1696 break;
1697 }
1698 case 'b':
1699 {
1700 // TODO
1701 // result.push_void(unpack_b(List__.shift().toString(), size));
1702 break;
1703 }
1704  
1705 case 'C':
1706 {
1707 if (size == 0) {
1708 // C0
1709 characterMode = true;
1710 }
1711 if (size < 0) {
1712 while (inputIndex < input.length()) {
1713 result.push_void( new PlInt( input.charAt(inputIndex++) & 0xFF ) );
1714 }
1715 }
1716 else {
1717 for (int j = 0; j < size; j++) {
1718 if (inputIndex < input.length()) {
1719 result.push_void( new PlInt( input.charAt(inputIndex++) & 0xFF ) );
1720 }
1721 }
1722 }
1723 break;
1724 }
1725 case 'W':
1726 {
1727 // TODO
1728 // for (int j = 0; j < size; j++) {
1729 // result.pushCodePoint( List__.shift().to_int() );
1730 // }
1731 break;
1732 }
1733 case 'U':
1734 {
1735 if (size == 0) {
1736 // U0
1737 characterMode = false;
1738 break;
1739 }
1740 if (characterMode) {
1741 // character mode C0
1742  
1743 if (inputIndex >= input.length()) {
1744 break;
1745 }
1746  
1747 // decode from UTF-8 ("bytes") to internal representation
1748 String s = input.substring(inputIndex);
1749 char[] chars = s.toCharArray();
1750 byte[] bytes = new byte[chars.length];
1751 for (int j = 0; j < bytes.length; j++){
1752 bytes[j] = (byte)(chars[j]);
1753 }
1754 String internal = new String(bytes, PlCx.UTF8);
1755 int internalIndex = 0;
1756
1757 // unpack
1758 StringBuilder sb = new StringBuilder();
1759 if (size < 0) {
1760 while (internalIndex < internal.length()) {
1761 int ichar = internal.charAt(internalIndex++);
1762 sb.appendCodePoint(ichar);
1763 result.push_void( new PlInt(ichar) );
1764 }
1765 }
1766 else {
1767 for (int j = 0; j < size; j++) {
1768 if (internalIndex < internal.length()) {
1769 int ichar = internal.charAt(internalIndex++);
1770 sb.appendCodePoint(ichar);
1771 result.push_void( new PlInt(ichar) );
1772 }
1773 }
1774 }
1775  
1776 // move the input pointer by the number of "bytes" consumed (not chars)
1777 byte[] bytesUsed = sb.toString().getBytes(PlCx.UTF8);
1778 inputIndex += bytesUsed.length;
1779  
1780 break;
1781 }
1782 else {
1783 // U0 mode
1784 if (size < 0) {
1785 while (inputIndex < input.length()) {
1786 result.push_void( new PlInt( input.charAt(inputIndex++) ) );
1787 }
1788 }
1789 else {
1790 for (int j = 0; j < size; j++) {
1791 if (inputIndex < input.length()) {
1792 result.push_void( new PlInt( input.charAt(inputIndex++) ) );
1793 }
1794 }
1795 }
1796 break;
1797 }
1798 }
1799  
1800 default:
1801 }
1802 }
1803 return result;
1804 }
1805 private static final int pack_size(String s, int pos) {
1806 int howMany = 0;
1807 while(s.length() > (pos + 1 + howMany) && java.lang.Character.isDigit(s.charAt(pos + 1 + howMany))) {
1808 ++howMany;
1809 }
1810 if(howMany != 0) {
1811 return java.lang.Integer.parseInt(s.substring(pos + 1, pos + 1 + howMany));
1812 }
1813 return 1;
1814 }
1815 private static final String pack_a(String s, int size) {
1816 if(s.length() >= size) {
1817 return s.substring(0,size);
1818 }
1819 String padding = new String(new char[size - s.length()]);
1820 return s + padding;
1821 }
1822 private static final String unpack_a(String s, int size) {
1823 if(s.length() >= size) {
1824 return s.substring(0,size);
1825 }
1826 return s;
1827 }
1828 private static final String pack_A(String s, int size) {
1829 if(s.length() >= size) {
1830 return s.substring(0,size);
1831 }
1832 String padding = new String(new char[size - s.length()]).replace('\0', ' ');
1833 return s + padding;
1834 }
1835 private static final String unpack_A(String s, int size) {
1836 if(s.length() >= size) {
1837 return s.substring(0,size);
1838 }
1839 return s;
1840 }
1841 private static final String pack_Z(String s, int size) {
1842 s = s.substring(0, java.lang.Math.min(size - 1, s.length()));
1843 return s + new String(new char[size - s.length()]);
1844 }
1845 private static final String unpack_Z(String s, int size) {
1846 if(s.length() >= size) {
1847 return s.substring(0,size);
1848 }
1849 return s;
1850 }
1851 private static final String pack_b(String s, int size) {
1852 s = s.substring(0, Math.min(size, s.length()));
1853 int wanted8strings = (size + 7) / 8;
1854 s += new String(new char[(wanted8strings * 8) - s.length()]).replace('\0', '0');
1855 StringBuilder input = new StringBuilder();
1856 for(int i = 0; i < s.length(); ++i) {
1857 if(s.codePointAt(i) % 2 == 1) {
1858 input.append("1");
1859 }
1860 else {
1861 input.append("0");
1862 }
1863 }
1864 StringBuilder result = new StringBuilder();
1865 s = input.toString();
1866 for(int i = 0; i < wanted8strings; ++i) {
1867 String part = s.substring(i * 8, i * 8 + 8);
1868 int first = java.lang.Integer.parseInt(new StringBuilder(part.substring(0,4)).reverse().toString(), 2);
1869 int second = java.lang.Integer.parseInt(new StringBuilder(part.substring(4,8)).reverse().toString(), 2);
1870 result.append(Character.toString((char)(first + second * 16)));
1871 }
1872 return result.toString();
1873 }
1874 private static final String unpack_b(String s, int size) {
1875 byte[] bytes = s.getBytes();
1876 StringBuilder result = new StringBuilder();
1877 byte mask = (byte)128;
1878 for(int i = 0; i < size; ++i) {
1879 byte b = bytes[i / 8];
1880 if((b & mask) > 0) {
1881 result.append("1");
1882 } else {
1883 result.append("0");
1884 }
1885 if(mask == 1) {
1886 mask = (byte)128;
1887 } else {
1888 mask /= 2;
1889 }
1890 }
1891 return result.toString();
1892 }
1893 private static final String pack_B(String s, int size) {
1894 s = s.substring(0, Math.min(size, s.length()));
1895 int wanted8strings = (size + 7) / 8;
1896 s += new String(new char[(wanted8strings * 8) - s.length()]).replace('\0', '0');
1897 StringBuilder input = new StringBuilder();
1898 for(int i = 0; i < s.length(); ++i) {
1899 if(s.codePointAt(i) % 2 == 1) {
1900 input.append("1");
1901 }
1902 else {
1903 input.append("0");
1904 }
1905 }
1906 StringBuilder result = new StringBuilder();
1907 s = input.toString();
1908 for(int i = 0; i < wanted8strings; ++i) {
1909 String part = s.substring(i * 8, i * 8 + 8);
1910 int ascii = java.lang.Integer.parseInt(part, 2);
1911 result.append(Character.toString((char)ascii));
1912 }
1913 return result.toString();
1914 }
1915 private static final String pack_h(String s, int size) {
1916 int index = 0;
1917 if(s.length() < size * 2) {
1918 s += new String(new char[size * 2 - s.length()]).replace('\0', '0');
1919 }
1920 StringBuilder result = new StringBuilder();
1921 while(index < size) {
1922 String part = s.substring(index + 1, index + 2) + s.substring(index, index + 1);
1923 int ascii = java.lang.Integer.parseInt(part, 16);
1924 result.append(Character.toString((char)ascii));
1925 index += 2;
1926 }
1927 return result.toString();
1928 }
1929 private static final String pack_H(String s, int size) {
1930 int index = 0;
1931 if(s.length() < size * 2) {
1932 s += new String(new char[size * 2 - s.length()]).replace('\0', '0');
1933 }
1934 StringBuilder result = new StringBuilder();
1935 while(index < size) {
1936 String part = s.substring(index, index + 2);
1937 int ascii = java.lang.Integer.parseInt(part, 16);
1938 result.append(Character.toString((char)ascii));
1939 index += 2;
1940 }
1941 return result.toString();
1942 }
1943 private static String pack_c(String s) {
1944 try {
1945 int ascii = java.lang.Integer.parseInt(s) % 128;
1946 return Character.toString((char)ascii);
1947 } catch(Exception e) {
1948 return "";
1949 }
1950 }
1951 private static String pack_C(String s) {
1952 try {
1953 int ascii = (java.lang.Integer.parseInt(s) + 256) % 256;
1954 return Character.toString((char)ascii);
1955 } catch(Exception e) {
1956 return "";
1957 }
1958 }
1959 private static String pack_number_2_string(long value, int size, boolean signed) {
1960 StringBuilder result = new StringBuilder();
1961 for(int i = 0; i < size; ++i) {
1962 result.append((char)((value / (int)Math.pow(2,8*i)) % 256));
1963 }
1964 return result.toString();
1965 }
1966 private static String pack_s(long s) {
1967 return pack_number_2_string(s, 2, true);
1968 }
1969 private static String pack_S(long s) {
1970 return pack_number_2_string(s, 2, false);
1971 }
1972 public static final String pack_l(long s) {
1973 return pack_number_2_string(s, 4, true);
1974 }
1975 public static final String pack_L(long s) {
1976 return pack_number_2_string(s, 4, false);
1977 }
1978 public static final String pack_q(long s) {
1979 return pack_number_2_string(s, 8, true);
1980 }
1981 public static final String pack_Q(long s) {
1982 return pack_number_2_string(s, 8, false);
1983 }
1984 public static final String pack_i(long s) {
1985 return pack_number_2_string(s, 4, true);
1986 }
1987 public static final String pack_I(long s) {
1988 return pack_number_2_string(s, 4, false);
1989 }
1990 public static final String pack_n(long s) {
1991 return new StringBuilder(pack_number_2_string(s, 2, false)).reverse().toString();
1992 }
1993 public static final String pack_N(long s) {
1994 return new StringBuilder(pack_number_2_string(s, 4, false)).reverse().toString();
1995 }
1996 public static final String pack_v(long s) {
1997 return pack_number_2_string(s, 2, false);
1998 }
1999 public static final String pack_V(long s) {
2000 return pack_number_2_string(s, 4, false);
2001 }
2002 public static final String pack_j(long s) {
2003 return pack_number_2_string(s, 8, true);
2004 }
2005 public static final String pack_J(long s) {
2006 return pack_number_2_string(s, 8, false);
2007 }
2008 public static final String pack_f(double d) {
2009 float f = (float)d;
2010 int intBits = java.lang.Float.floatToRawIntBits(f);
2011 char one = (char)(intBits / (int)Math.pow(2, 24));
2012 char two = (char)((intBits / (int)Math.pow(2, 16)) % 256);
2013 char three = (char)((intBits / (int)Math.pow(2, 8)) % 256);
2014 char four = (char)(intBits % 256);
2015 StringBuilder result = new StringBuilder();
2016 result.append(Character.toString(four));
2017 result.append(Character.toString(three));
2018 result.append(Character.toString(two));
2019 result.append(Character.toString(one));
2020 return result.toString();
2021 }
2022 public static final String pack_d(double d) {
2023 long intBits = java.lang.Double.doubleToRawLongBits(d);
2024 char one = (char)(intBits / (long)Math.pow(2, 56));
2025 char two = (char)((intBits / (long)Math.pow(2, 48)) % 256);
2026 char three = (char)((intBits / (long)Math.pow(2, 40)) % 256);
2027 char four = (char)((intBits / (long)Math.pow(2, 32)) % 256);
2028 char five = (char)((intBits / (long)Math.pow(2, 24)) % 256);
2029 char six = (char)((intBits / (long)Math.pow(2, 16)) % 256);
2030 char seven = (char)((intBits / (long)Math.pow(2, 8)) % 256);
2031 char eight = (char)(intBits % 256);
2032 StringBuilder result = new StringBuilder();
2033 result.append(eight);
2034 result.append(seven);
2035 result.append(six);
2036 result.append(five);
2037 result.append(four);
2038 result.append(three);
2039 result.append(two);
2040 result.append(one);
2041 return result.toString();
2042 }
2043 private static StringBuilder pack_pointers = new StringBuilder();
2044 private static Map<Long, Integer> pack_pointers_size = new HashMap<Long, Integer>();
2045 private static final long pack_pointers_magic_value = 654321;
2046 public static final String pack_p(String s) {
2047 long pointer = pack_pointers.length() + pack_pointers_magic_value;
2048 pack_pointers.append(s);
2049  
2050 pack_pointers_size.put(pointer, s.length());
2051 return pack_q((long)(pointer));
2052 }
2053 public static final String pack_u(String s) {
2054 int index = 0;
2055 StringBuilder result = new StringBuilder();
2056 StringBuilder line = new StringBuilder();
2057 int tooMany = 0;
2058 while(s.length() > index * 3) {
2059 String cur = s.substring(index * 3, Math.min(index * 3 + 3, s.length()));
2060 while(cur.length() < 3) {
2061 ++tooMany;
2062 cur += '\0';
2063 }
2064 byte[] bytes = cur.getBytes();
2065 char value1 = (char)((bytes[0] >> 2) + 32);
2066 char value2 = (char)(((bytes[0] & 3) << 4) + (bytes[1] >> 4) + 32);
2067 char value3 = (char)(((bytes[1] & 15) << 2) + (bytes[2] >> 6) + 32);
2068 char value4 = (char)((bytes[2] & 63) + 32);
2069  
2070 line.append(value1);
2071 line.append(value2);
2072 line.append(value3);
2073 line.append(value4);
2074
2075 if(line.length() == 60 && index != 0) {
2076 line.insert(0, (char)(32 + (45 - tooMany)));
2077 line.append("\n");
2078 result.append(line.toString());
2079 line = new StringBuilder();
2080 }
2081 ++index;
2082 }
2083 if(line.length() > 0) {
2084 line.insert(0, (char)(32 + ((index * 3 - tooMany) % 45)));
2085 line.append("\n");
2086 result.append(line);
2087 }
2088  
2089 return result.toString().replaceAll(" ", "`");
2090 }
2091 public static final String pack_w(String[] s, int size) {
2092 java.math.BigInteger max_byte = new java.math.BigInteger("128");
2093 StringBuilder result = new StringBuilder();
2094 for(int i = 0; i < size; ++i) {
2095 java.math.BigInteger current = new java.math.BigInteger(s[i]);
2096 if(current.signum() < 0) {
2097 throw new PlDieException(new PlString("Cannot compress negative numbers in pack"));
2098 }
2099 while(current.compareTo(max_byte) > 0) {
2100 int part = current.mod(max_byte).intValue();
2101 result.append((char) (part + 128));
2102 current = current.divide(max_byte);
2103 }
2104 result.append((char)current.intValue());
2105 }
2106  
2107 return result.toString();
2108 }
2109 public static final String pack_x(int size) {
2110 return new String(new char[size]);
2111 }
2112 public static final PlObject times(int want, PlArray List__) {
2113 ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
2114 long cpu = bean.isCurrentThreadCpuTimeSupported( ) ?
2115 bean.getCurrentThreadCpuTime( ) : 0L;
2116 long user = bean.isCurrentThreadCpuTimeSupported( ) ?
2117 bean.getCurrentThreadUserTime( ) : 0L;
2118 long system = cpu - user;
2119 return new PlArray(
2120 new PlDouble( user / 1000000000.0 ),
2121 new PlDouble( system / 1000000000.0 ),
2122 new PlDouble( 0.0 ),
2123 new PlDouble( 0.0 )
2124 );
2125 }
2126 public static final PlObject localtime(int want, PlArray List__) {
2127 PlArray res = new PlArray();
2128 ZonedDateTime date;
2129 if (List__.to_boolean()) {
2130 long arg = List__.aget(0).to_long();
2131 date = Instant.ofEpochSecond(arg).atZone(ZoneId.systemDefault());
2132 }
2133 else {
2134 date = ZonedDateTime.now();
2135 }
2136 if (want == PlCx.SCALAR) {
2137 return new PlString(date.format( DateTimeFormatter.RFC_1123_DATE_TIME ));
2138 }
2139 // 0 1 2 3 4 5 6 7 8
2140 // ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
2141 res.push_void(date.getSecond());
2142 res.push_void(date.getMinute());
2143 res.push_void(date.getHour());
2144 res.push_void(date.getDayOfMonth());
2145 res.push_void(date.getMonth().getValue() - 1);
2146 res.push_void(date.getYear() - 1900);
2147 res.push_void(date.getDayOfWeek().getValue());
2148 res.push_void(date.getDayOfYear() - 1);
2149 res.push_void(
2150 date.getZone().getRules().isDaylightSavings(date.toInstant()) ? PlCx.INT1 : PlCx.INT0
2151 );
2152 return res;
2153 }
2154 public static final PlObject gmtime(int want, PlArray List__) {
2155 PlArray res = new PlArray();
2156 ZonedDateTime date;
2157 if (List__.to_boolean()) {
2158 long arg = List__.aget(0).to_long();
2159 date = Instant.ofEpochSecond(arg).atZone(ZoneId.of("UTC"));
2160 }
2161 else {
2162 date = ZonedDateTime.now(ZoneOffset.UTC);
2163 }
2164 if (want == PlCx.SCALAR) {
2165 return new PlString(date.format( DateTimeFormatter.RFC_1123_DATE_TIME ));
2166 }
2167 // 0 1 2 3 4 5 6 7 8
2168 // ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
2169 res.push_void(date.getSecond());
2170 res.push_void(date.getMinute());
2171 res.push_void(date.getHour());
2172 res.push_void(date.getDayOfMonth());
2173 res.push_void(date.getMonth().getValue() - 1);
2174 res.push_void(date.getYear() - 1900);
2175 res.push_void(date.getDayOfWeek().getValue());
2176 res.push_void(date.getDayOfYear() - 1);
2177 res.push_void(
2178 date.getZone().getRules().isDaylightSavings(date.toInstant()) ? PlCx.INT1 : PlCx.INT0
2179 );
2180 return res;
2181 }
2182 public static final PlInt time(int want, PlArray List__) {
2183 return new PlInt( (long)Math.floor(System.currentTimeMillis() * 0.001 + 0.5));
2184 }
2185 public static final PlDouble sleep(int want, PlArray List__) {
2186 long s;
2187 if (List__.to_int() == 0) {
2188 s = Long.MAX_VALUE;
2189 }
2190 else {
2191 s = ((Double)(List__.shift().to_double() * 1000)).longValue();
2192 }
2193 try {
2194 TimeUnit.MILLISECONDS.sleep(s);
2195 } catch (InterruptedException e) {
2196 //Handle exception
2197 PlCORE.die("interrupted");
2198 }
2199 return new PlDouble(s / 1000.0);
2200 }
2201 public static final PlObject system(int want, PlArray List__) {
2202 // TODO - see perldoc -f system
2203 try {
2204 Process p;
2205 if (List__.to_int() > 1) {
2206 String[] args = new String[List__.to_int()];
2207 int i = 0;
2208 for (PlObject s : List__.a) {
2209 args[i++] = s.toString();
2210 }
2211 p = Runtime.getRuntime().exec(args);
2212 }
2213 else {
2214 p = Runtime.getRuntime().exec(List__.aget(0).toString());
2215 }
2216 // String s = null;
2217 // BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
2218 // BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
2219 // System.out.println("STDOUT\n");
2220 // while ((s = stdInput.readLine()) != null) {
2221 // System.out.println(" " + s);
2222 // }
2223 // System.out.println("STDERR\n");
2224 // while ((s = stdError.readLine()) != null) {
2225 // System.out.println(" " + s);
2226 // }
2227 int ret = p.waitFor() * 256;
2228 PlV.sset("main::?", new PlInt(ret));
2229 return new PlInt(ret);
2230 } catch (InterruptedException e) {
2231 //Handle exception
2232 return PlCORE.die("interrupted");
2233 }
2234 catch (IOException e) {
2235 // System.out.println("IOexception: ");
2236 // e.printStackTrace();
2237 PlV.sset("main::!", new PlStringLazyError(e));
2238 return PlCx.MIN1;
2239 }
2240 }
2241 public static final PlObject qx(int want, PlArray List__) {
2242 // TODO - see perldoc -f qx
2243 try {
2244 String[] args = new String[List__.to_int()];
2245 int i = 0;
2246 for (PlObject s : List__.a) {
2247 args[i++] = s.toString();
2248 }
2249 PlArray res = new PlArray();
2250 String s = null;
2251 Process p = Runtime.getRuntime().exec(args);
2252 // ??? set PlCx.UTF8
2253 BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
2254 // System.out.println("STDOUT\n");
2255 while ((s = stdInput.readLine()) != null) {
2256 // System.out.println(" " + s);
2257 res.push_void(s + "\n");
2258 }
2259 // BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
2260 // System.out.println("STDERR\n");
2261 // while ((s = stdError.readLine()) != null) {
2262 // System.out.println(" " + s);
2263 // }
2264 if (want == PlCx.LIST) {
2265 return res;
2266 }
2267 return PlCORE.join(want, "", res);
2268 }
2269 catch (IOException e) {
2270 // System.out.println("IOexception: ");
2271 // e.printStackTrace();
2272 return PlCx.UNDEF;
2273 }
2274 }
2275 public static final PlObject caller(int wantarray, PlArray List__) {
2276 PlObject arg = List__.aget(0);
2277 boolean argDefined = !arg.is_undef();
2278 int item = arg.to_int();
2279  
2280 PlArray callerName = PlV.array_get("Perlito5::CALLER");
2281 if (callerName.length_of_array().to_boolean()) {
2282 // maybe we are inside an import() subroutine
2283  
2284 PlObject arr = callerName.aget(0); // XXX this should be "item"
2285 // XXX FIXME TODO - workaround for "export to level"
2286 if (arr.is_arrayref()) {
2287 if (wantarray == PlCx.LIST) {
2288 return arr.array_deref_strict();
2289 }
2290 return arr.aget(0);
2291 }
2292 // fallback to normal caller()
2293 };
2294  
2295 String fullName = "";
2296  
2297 // A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().
2298 // The last element of the array represents the bottom of the stack,
2299 // which is the least recent method invocation in the sequence.
2300 callerName = new PlArray();
2301 PlArray codeRef = new PlArray();
2302 Thread t = Thread.currentThread();
2303 StackTraceElement[] stackTraceElements = t.getStackTrace();
2304 for (StackTraceElement elem : stackTraceElements) {
2305 // PlCORE.say(
2306 // elem.getClassName() + " \t" +
2307 // elem.getMethodName() + " \t" +
2308 // elem.getFileName() + " \t" +
2309 // elem.getLineNumber()
2310 // );
2311 if (elem.getMethodName().equals("apply")) {
2312 // stack trace element comes from PlClosure.apply()
2313 // TODO - move this inner loop outside, this is very expensive
2314 // TODO - this code doesn't account for inner-subs - it might match an outer sub instead
2315 // TODO - this code doesn't account for package name changes inside a sub
2316 // TODO - this code skips anonymous subroutines
2317 // TODO - the "perlSubName" resolution is ambiguous,
2318 // because a sub can be exported to several namespaces:
2319 // Exporter::import and MyClass::import can point to the same Java code
2320 // this loop does a symbol table scan - PlV.cvar
2321 SCAN_SUBNAME:
2322 for (String name : PlStringConstant.constants.keySet()) {
2323 PlObject value = PlV.cget_no_autoload(name);
2324 if (value.is_lvalue()) {
2325 value = value.get();
2326 }
2327 if (value.is_coderef()) {
2328 PlClosure code = (PlClosure)value;
2329 if ( code.javaClassName() != null &&
2330 elem.getClassName().equals(code.javaClassName()) &&
2331 elem.getLineNumber() > code.firstLineNumber() &&
2332 elem.getLineNumber() < code.lastLineNumber() &&
2333 !code.pkg_name.startsWith("Perlito5::")
2334 ) {
2335 // PlCORE.say(
2336 // elem.getClassName() + " \t" +
2337 // elem.getMethodName() + " \t" +
2338 // elem.getFileName() + " \t" +
2339 // elem.getLineNumber()
2340 // );
2341 // PlCORE.say("\tPerl sub &" + perlSubName.toString());
2342 callerName.push_void(new PlString(name));
2343 codeRef.push_void(value);
2344 break SCAN_SUBNAME;
2345 }
2346 }
2347 }
2348 }
2349 }
2350  
2351 PlObject plCoderef = codeRef.aget(item);
2352 PlObject plCallerCoderef = codeRef.aget(item + 1);
2353 PlObject packageName = PlCx.UNDEF;
2354 if (plCallerCoderef.is_coderef()) {
2355 packageName = new PlString(((PlClosure)plCallerCoderef).pkg_name);
2356 }
2357 else if (plCoderef.is_coderef()) {
2358 packageName = new PlString("main");
2359 }
2360  
2361 if (wantarray != PlCx.LIST) {
2362 // caller() in scalar or void context
2363 return packageName;
2364 }
2365  
2366 PlObject plFullName = callerName.aget(item); // "subroutine" comes from the current level
2367 PlObject lineNumber = PlCx.UNDEF;
2368 String fileName = "";
2369 if (plCoderef.is_coderef()) {
2370 lineNumber = new PlInt(((PlClosure)plCoderef).perlLineNumber());
2371 fileName = ((PlClosure)plCoderef).perlFileName();
2372 }
2373  
2374  
2375 if (!argDefined) {
2376 // caller() in list context, without args
2377 return new PlArray( packageName, new PlString(fileName), lineNumber );
2378 }
2379  
2380 // caller(EXPR) in list context, with args
2381 // TODO - add other components
2382 // # 0 1 2 3 4
2383 // ($package, $filename, $line, $subroutine, $hasargs,
2384 // # 5 6 7 8 9 10
2385 // $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
2386 return new PlArray( packageName, new PlString(fileName), lineNumber, plFullName );
2387 }
2388 }
2389  
2390 EOT
2391  
2392 } # end of emit_java()
2393  
2394 1;
2395  
2396 __END__