-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass-shell-node.php
More file actions
1401 lines (1334 loc) · 48.5 KB
/
Copy pathclass-shell-node.php
File metadata and controls
1401 lines (1334 loc) · 48.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Shell: the TSL front-end that turns typed lines and `.tsl` files into Messages.
*
* One grammar serves both callers. `wp nodes cli` feeds keystrokes in as
* TM_BYTESTREAM through `TTY_In_Node`; `Topology_Loader` feeds a whole topology
* file in through `eval_script()`. Both land in `parse()`, which interpolates
* `<var>` and `<ns:key>` tokens, tokenizes quote-aware, runs the builtins that
* touch only shell state, and mints a Message for every other verb. The two
* contexts differ in two switches: `want_reply( false )` marks each command
* TM_NOREPLY because a booting worker has no console for the reply, and
* `fatal_errors( true )` turns a cycle or an unterminated quote into a throw so
* a mangled `.tsl` never half-builds a graph.
*
* `parse_statements()` reads the same grammar statically — no interpolation, no
* dispatch, no node construction — so `Topology_Analyzer` and the topology
* editor can describe a file without running it.
*
* `src/runtime/shell-node.js` mirrors this file for the browser graph, pinned
* to it by the shared `tests/fixtures/statements/` corpus.
*
* @package Newspack_Nodes
*/
namespace Newspack_Nodes;
\defined( 'ABSPATH' ) || exit;
/**
* Shell node — the REPL and TSL parser, always anonymous.
*
* `name()` is fatal on any argument: a named Shell would be addressable, and
* whatever reaches it could mint signed commands at will, so unaddressability
* is the boundary (ADR-7). It sinks into whatever wired it — the console tap in
* `wp nodes cli`, the command interpreter at worker boot — and is never itself a
* node in the graph it builds.
*/
class Shell_Node extends Node {
/** Current cwd — the node-path non-builtin commands route to by default; empty = local interpreter. */
public string $path = '';
/** Prompt `TTY_In_Node` renders; `cd`, a held continuation and a Dumper `prompt` reply all rewrite it. */
public string $prompt = '/> ';
/**
* Lines printed by the local `status` builtin on demand; empty = silent no-op.
*
* @var array<int,string>
*/
public array $status_lines = [];
/** Backslash-continuation accumulator. */
private string $continuation = '';
/**
* Open-quote continuation accumulator (raw, pre-interpolation). Tachikoma
* parity: an open quote continues the statement onto the next line, newline
* included in the token; flush_pending() errors if EOF arrives first.
*/
private string $quote_continuation = '';
/** Prompt to restore when the open quote closes ('' = none stashed). */
private string $prompt_stash = '';
/**
* Script-context error handling: REPLs log-and-continue (safe default) so
* a typo'd include or quote doesn't kill the session; Topology_Loader
* turns this on so a cyclic include or an unterminated quote in a .tsl
* fails loud at worker boot rather than booting a half-built or silently
* mangled graph. Mirrors the want_reply() setter shape.
*/
private bool $fatal_errors = false;
/**
* Resolved include paths on the current ancestor chain — a repeat is a cycle.
*
* @var list<string>
*/
private array $include_stack = [];
/**
* Resolved include paths already evaluated within the CURRENT top-level
* script (`#pragma once`) — scoped per fill() entered with an empty
* include_stack, not per Shell lifetime, so a long-lived REPL re-running
* `include foo` after editing foo.tsl isn't a silent no-op.
*
* @var array<string,true>
*/
private array $included = [];
/** When true, every parsed line dumps its interpolated/tokenized form to $output_stream. */
private bool $show_parse = false;
/**
* Interactive REPLs want their command replies (default). A script/topology
* loader sets this false so commands go out TM_NOREPLY — the interpreter then
* suppresses replies that would otherwise dead-end (no console at boot).
* Mirrors Tachikoma Shell's $self->{want_reply}.
*/
private bool $want_reply = true;
/**
* Verb aliases the interpreter's dispatch table resolves — the ONE table the
* static front-end applies, to token[0] and only token[0], so a topology
* written with the short form reads the same as the long form to every static
* analysis. parse() needs no table: duplicate `case` labels are its aliases,
* as duplicate `%BUILTINS` keys are Tachikoma's. This canonicalization is a
* deliberate divergence — `make`/`connect`/`disconnect` are the INTERPRETER's
* aliases, and consumers match `'make_node' === $statement['verb']`.
*
* @var array<string,string>
*/
private const VERB_ALIASES = [
'make' => 'make_node',
'connect' => 'connect_node',
'disconnect' => 'disconnect_node',
'command' => 'command_node',
'cmd' => 'command_node',
];
/**
* Per-quote-type escape rules, following Shell3's string1/string2/string3
* expansion. Double quotes expand the sequences; single quotes and backticks
* resolve only their own quote char and the backslash, so a `\n` written
* inside them stays two characters. An unlisted `\X` keeps both characters,
* as Perl does.
*
* `<` and `>` are double-quote escapes because `interpolate()` runs first and
* copies an escape pair verbatim: `"\<partition\>"` is how an author defers a
* token that would otherwise expand here and now.
*
* @var array<string,array<string,string>>
*/
private const ESCAPES = [
'"' => [
'e' => "\e",
'n' => "\n",
'r' => "\r",
't' => "\t",
'"' => '"',
'\\' => '\\',
'<' => '<',
'>' => '>',
],
"'" => [
"'" => "'",
'\\' => '\\',
],
'`' => [
'`' => '`',
'\\' => '\\',
],
];
/**
* `<name> [ <op> [ <value> ] ]` — the operator set of Shell3's `$H{'var'}`.
* A name may carry dot separators (`message.from`), and the `s` flag lets a
* value span the newlines an open-quote continuation folded into the line.
*/
private const VAR_GRAMMAR = '/^([^\s=+\-*\/.|]+(?:\.[^\s=+\-*\/.|]+)*)\s*(\/\/=|\|\|=|[.+\-*\/]=|\+\+|--|=)?(.*)$/s';
/**
* Shell egress. A TM_BYTESTREAM is raw REPL input: parse each statement into a
* Message and dispatch it. TM_EOF drains (input closed). Anything else passes
* straight through to the sink, mirroring Tachikoma::Nodes::Shell::fill, which
* sinks any non-TM_BYTESTREAM message rather than dropping it. TYPE is a
* bitmask, so a composite (`TM_BYTESTREAM|TM_NOREPLY`) reads as its flags, not
* as an unrecognized type. A statement that minted no KEY of its own inherits
* the input message's, so a keyed script keeps its key across the split.
*
* The Shell signs what it MINTS — each command it parses — so that command
* crosses the IPC boundary to a worker carrying an HMAC envelope
* (Command_Auth::sign is a no-op on non-command types). A pre-built message is
* forwarded untouched: signing on arrival is the ingress conferring authority,
* and it would overwrite an envelope already bound to another destination under
* a session key (ADR-15). The minter signs.
*
* @param array<int,mixed> $message Message to parse or pass through.
* @throws \RuntimeException When no sink is wired, or TYPE is not an integer.
*/
public function fill( array $message ): void {
$sink = $this->require_sink();
$type = $message[ Message::TYPE ] ?? 0;
$value = $message[ Message::VALUE ] ?? null;
if ( ! \is_integer( $type ) ) {
throw new \RuntimeException( 'Shell::fill requires a valid message' );
}
if ( $type & Message::TM_EOF ) {
// Stdin closed mid-statement: report before draining.
$this->flush_pending();
$message[ Message::FROM ] = $this->reply_from();
$message[ Message::TO ] = $this->path;
$sink->fill( $message );
return;
}
if ( ! ( $type & Message::TM_BYTESTREAM ) || ! \is_string( $value ) ) {
// Not REPL input: nothing to parse, so sink it rather than drop it.
$sink->fill( $message );
return;
}
if ( empty( $this->include_stack ) ) {
// A fresh top-level script (not a recursive include) — new memo.
$this->included = [];
}
foreach ( $this->split_statements( $value ) as $statement ) {
$parsed = $this->parse( $statement );
if ( null !== $parsed ) {
++$this->counter;
if ( '' === $parsed[ Message::KEY ] ) {
$parsed[ Message::KEY ] = $message[ Message::KEY ];
}
Command_Auth::sign( $parsed );
$sink->fill( $parsed );
}
}
}
/**
* Quote-aware statement splitter: comment lines returned whole, others split on unquoted `;`.
*
* @param string $script One or more physical lines.
* @return array<int,string> One entry per statement, in source order.
*/
public function split_statements( string $script ): array {
return \array_column( self::split_statements_indexed( $script ), 'text' );
}
/**
* The one static TSL statement front-end: split → join backslash
* continuations → tokenize → resolve verb aliases + cwd, keeping BOTH token
* forms. A public static sibling of tokenize() built from the pieces the Shell
* already owns, with dispatch removed and no side effects: no interpolation, no
* Core::$var reads, no node construction. `Topology_Analyzer` and the topology
* editor read the list without executing it.
*
* Each statement is `{ verb, values, spans, raw, line }`: `verb` is the
* canonical verb; `values` the quote-stripped tokens (`values[0] === verb`,
* and for `cmd` `values[1]` is the cwd-resolved path); `spans` the same tokens
* with quote chars + escapes verbatim (what a round-trip must emit, so a
* deferred `'<partition>'` never becomes an eager `"<partition>"`); `raw` the
* canonical single-line form (the sharing signature readers normalize); `line`
* the 1-based first physical source line.
*
* @param string $text A whole `.tsl` source, or any run of statements.
* @return list<array{verb:string,values:list<string>,spans:list<string>,raw:string,line:int}>
* @throws \RuntimeException On a quote or a backslash continuation left open at
* end-of-input.
*/
public static function parse_statements( string $text ): array {
$shell = new self();
$statements = [];
foreach ( self::join_statement_continuations( self::split_statements_indexed( $text ) ) as $joined ) {
$statement = self::build_statement( $shell, $joined['text'], $joined['line'] );
if ( null !== $statement ) {
$statements[] = $statement;
}
}
return $statements;
}
/**
* split_statements(), plus the 1-based first physical line of each statement's
* run — the one thing parse_statements() needs and split_statements() does not
* compute.
*
* @param string $script One or more physical lines.
* @return list<array{text:string,line:int}>
*/
private static function split_statements_indexed( string $script ): array {
$statements = [];
$buf = '';
$in_quote = null;
$stmt_line = 0;
$line_no = 0;
foreach ( \explode( "\n", $script ) as $line ) {
++$line_no;
if ( null !== $in_quote ) {
// Mid-quote: the newline is token content, keep accumulating.
$buf .= "\n";
} else {
$leading = \ltrim( $line );
if ( '' === $leading ) {
continue;
}
if ( '#' === $leading[0] ) {
// Whole-line comment — don't scan for `;` inside it.
$statements[] = [
'text' => \trim( $line ),
'line' => $line_no,
];
continue;
}
}
$length = \strlen( $line );
for ( $i = 0; $i < $length; ++$i ) {
$ch = $line[ $i ];
if ( null !== $in_quote ) {
// An escaped quote must not close the run.
if ( '\\' === $ch && $i + 1 < $length ) {
$buf .= $ch . $line[ ++$i ];
continue;
}
$buf .= $ch;
if ( $ch === $in_quote ) {
$in_quote = null;
}
continue;
}
if ( "'" === $ch || '"' === $ch || '`' === $ch ) {
if ( 0 === $stmt_line ) {
$stmt_line = $line_no;
}
$in_quote = $ch;
$buf .= $ch;
continue;
}
if ( '\\' === $ch && $i + 1 < $length ) {
$buf .= $ch . $line[ ++$i ];
continue;
}
// A `;` inside a comment tail must not split the statement.
if ( '#' === $ch ) {
$buf .= \substr( $line, $i );
break;
}
if ( ';' === $ch ) {
$trim = \trim( $buf );
if ( '' !== $trim ) {
$statements[] = [
'text' => $trim,
'line' => $stmt_line,
];
}
$buf = '';
$stmt_line = 0;
continue;
}
if ( 0 === $stmt_line && ' ' !== $ch && "\t" !== $ch ) {
$stmt_line = $line_no;
}
$buf .= $ch;
}
if ( null === $in_quote ) {
$tail = \trim( $buf );
if ( '' !== $tail ) {
$statements[] = [
'text' => $tail,
'line' => $stmt_line,
];
}
$buf = '';
$stmt_line = 0;
}
}
// EOF mid-quote: parse() holds the tail; flush_pending() judges it.
$tail = \trim( $buf );
if ( '' !== $tail ) {
$statements[] = [
'text' => $tail,
'line' => $stmt_line,
];
}
return $statements;
}
/**
* Fold trailing-backslash continuations across the statement stream — the same
* splice parse() performs, applied statelessly. The joined statement keeps the
* FIRST physical line of its run, and a continuation still open at end-of-input
* throws rather than yielding the half of the statement that arrived: the
* runtime path fails loud there too, and a truncated statement describes a
* different graph than the author wrote.
*
* @param list<array{text:string,line:int}> $indexed Statements with source lines.
* @return list<array{text:string,line:int}> One entry per joined statement.
* @throws \RuntimeException On a trailing continuation at end-of-input.
*/
private static function join_statement_continuations( array $indexed ): array {
$out = [];
$acc = '';
$acc_line = 0;
foreach ( $indexed as $statement ) {
if ( 0 === $acc_line ) {
$acc_line = $statement['line'];
}
$text = $statement['text'];
if ( self::is_continuation( $text ) ) {
$acc .= \substr( $text, 0, -1 );
continue;
}
$out[] = [
'text' => $acc . $text,
'line' => $acc_line,
];
$acc = '';
$acc_line = 0;
}
if ( '' !== $acc ) {
// Runtime parity: flush_pending() fails loud here too.
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- parse diagnostic, not HTML.
throw new \RuntimeException( "got EOF while waiting for tokens at line {$acc_line}" );
}
return $out;
}
/**
* Tokenize one joined statement and resolve its verb alias + cwd into the
* canonical `{ verb, values, spans, raw, line }` record. Returns null for a
* comment/blank statement or a `cd`/`chdir` (which only mutates the shared
* throwaway shell's cwd). Reuses the Shell's own cd()/prefix() so the static
* and runtime paths route identically.
*
* The switch mirrors parse() verb for verb, because the record has to MEAN
* what parse() means: replaying `raw` at the root cwd mints the very Message
* parse() minted at the live cwd. Dispatch reads token[0] and nothing else —
* `command_node foo ping` names a verb on foo, not the Shell's `ping`.
*
* @param self $shell Throwaway shell carrying the cwd `cd` statements move.
* @param string $text One statement, continuations already joined.
* @param int $line 1-based first physical line of the statement's run.
* @return array{verb:string,values:list<string>,spans:list<string>,raw:string,line:int}|null
* @throws \RuntimeException On an unterminated quote at end-of-input.
*/
private static function build_statement( self $shell, string $text, int $line ): ?array {
if ( '' === $text || '#' === $text[0] ) {
return null;
}
$open_quote = null;
$scanned = self::scan_tokens( $text, $open_quote );
if ( null !== $open_quote ) {
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- plain-text loader/CLI message; escape at the view, not the runtime.
throw new \RuntimeException( 'got EOF while waiting for tokens: ' . \trim( $text ) );
}
if ( empty( $scanned ) ) {
return null;
}
$token_values = \array_column( $scanned, 'value' );
$token_spans = \array_column( $scanned, 'raw' );
$verb = self::VERB_ALIASES[ $token_values[0] ] ?? $token_values[0];
switch ( $verb ) {
case 'cd':
case 'chdir':
// RESOLVES against the cwd and mutates it; emits nothing.
$shell->path = $shell->cd( $shell->path, $token_values[1] ?? '' );
return null;
case 'include':
case 'var':
case 'print':
case 'clear':
case 'debug_level':
case 'status':
case 'show_parse':
// run_builtin() verbs: shell state, never a message.
$values = [ $verb, ...\array_slice( $token_values, 1 ) ];
$spans = [ $verb, ...\array_slice( $token_spans, 1 ) ];
break;
case 'command_node':
case 'ping':
case 'request':
case 'request_node':
case 'send':
case 'send_node':
case 'send_struct':
case 'send_struct_node':
case 'send_eof':
case 'tell':
case 'tell_node':
// parse() PREFIXES arg[0]; the tail stays opaque.
$path = $shell->prefix( $token_values[1] ?? '' );
$values = [ $verb, $path, ...\array_slice( $token_values, 2 ) ];
// $path is a VALUE; spans are source text, so requote it.
$spans = [ $verb, Node::serialize_arg( $path ), ...\array_slice( $token_spans, 2 ) ];
break;
case 'pwd':
// parse() ignores pwd's tokens; the cwd IS the argument.
$token_values = '' === $shell->path ? [ 'pwd' ] : [ 'pwd', $shell->path ];
$token_spans = '' === $shell->path
? [ 'pwd' ]
: [ 'pwd', Node::serialize_arg( $shell->path ) ];
// Fall through to the cwd routing every bare verb takes.
default:
// parse()'s default: TM_COMMAND at the cwd, named by verb.
$head = '' === $shell->path ? [] : [ 'command_node', $shell->path ];
// The cwd is a VALUE; spans are source text, so requote it.
$head_spans = '' === $shell->path
? []
: [ 'command_node', Node::serialize_arg( $shell->path ) ];
$values = [ ...$head, $verb, ...\array_slice( $token_values, 1 ) ];
$spans = [ ...$head_spans, $verb, ...\array_slice( $token_spans, 1 ) ];
break;
}
return [
'verb' => $values[0],
'values' => $values,
'spans' => $spans,
'raw' => \trim( \implode( ' ', $spans ) ),
'line' => $line,
];
}
/**
* Parse one statement into a Message.
*
* Null covers everything that mints nothing: a blank or comment line, a line
* held as a backslash or open-quote continuation, a builtin that only moved
* shell state, and a verb that answered with a usage or decode error.
*
* @param string $line One statement, already split on unquoted `;`.
* @return array<int,mixed>|null The 7-field positional Message, or null.
*/
public function parse( string $line ): ?array {
// Backslash splice: the \<newline> vanishes (bash: hi\+bye = hibye).
if ( self::is_continuation( $line ) ) {
$this->continuation .= \substr( $line, 0, -1 );
if ( '' === $this->prompt_stash ) {
$this->prompt_stash = $this->prompt;
}
$this->prompt = '> ';
return null;
}
if ( '' !== $this->continuation ) {
$line = $this->continuation . $line;
$this->continuation = '';
}
if ( '' !== $this->quote_continuation ) {
$line = $this->quote_continuation . "\n" . $line;
$this->quote_continuation = '';
}
$raw = $line;
// Settle comments first: interpolating an inert line warns spuriously.
$trimmed_raw = \trim( $line );
if ( '' === $trimmed_raw || '#' === $trimmed_raw[0] ) {
return null;
}
$line = $this->interpolate( $line );
// Trim AFTER interpolation so `<var>` can expand into leading space.
$line = \trim( $line );
if ( '' === $line || '#' === $line[0] ) {
return null;
}
$open_quote = null;
$tokens = \array_column( self::scan_tokens( $line, $open_quote ), 'value' );
if ( null !== $open_quote ) {
// Continue on the next line (raw, so the join interpolates ONCE).
if ( '' === $this->prompt_stash ) {
$this->prompt_stash = $this->prompt;
}
$this->quote_continuation = $raw;
$this->prompt = "{$open_quote}> ";
return null;
}
if ( '' !== $this->prompt_stash ) {
$this->prompt = $this->prompt_stash;
$this->prompt_stash = '';
}
if ( empty( $tokens ) ) {
return null;
}
if ( $this->show_parse ) {
$dump = 'parse> line: ' . $line . "\n"
. 'parse> tokens: ' . (string) \wp_json_encode( $tokens ) . "\n";
$this->stdout( $dump );
}
$verb = \array_shift( $tokens );
$args = $tokens;
// Shell.pm:94 — a builtin runs, anything else becomes a command.
if ( $this->run_builtin( $verb, $args ) ) {
return null;
}
// Shell3:2240-2242 — var scope; overriding FROM re-routes the reply.
$message = Message::new_message();
// A forged TIMESTAMP is a debugging tool; unset keeps the mint clock.
$forged = Core::str( Core::$var['message.timestamp'] ?? '', '' );
if ( '' !== $forged ) {
$message[ Message::TIMESTAMP ] = $forged;
}
$message[ Message::FROM ] = Core::str( Core::$var['message.from'] ?? '', '' )
?: $this->reply_from();
$message[ Message::ID ] = Core::str( Core::$var['message.id'] ?? '', '' );
$message[ Message::KEY ] = Core::str( Core::$var['message.key'] ?? '', '' );
// LOCAL taint: in-proc mint, stripped at wire (packed()); local-only.
$message[ Message::LOCAL ] = true;
switch ( $verb ) {
case 'command':
case 'cmd':
case 'command_node':
$cmd_path = $args[0] ?? '';
$cmd_verb = $args[1] ?? '';
$cmd_args = \array_slice( $args, 2 );
if ( '' === $cmd_path || '' === $cmd_verb ) {
$this->stdout( "usage: cmd <path> <verb> [<args>]\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_COMMAND;
$message[ Message::TO ] = $this->prefix( $cmd_path );
$message[ Message::VALUE ] = [
'name' => $cmd_verb,
'arguments' => $cmd_args,
];
break;
case 'pwd':
$message[ Message::TYPE ] = Message::TM_COMMAND;
$message[ Message::TO ] = $this->path;
$message[ Message::VALUE ] = [
'name' => 'pwd',
'arguments' => '' === $this->path ? [] : [ $this->path ],
];
break;
case 'ping':
// Receiver bounces TO=FROM; VALUE is the send timestamp.
$message[ Message::TYPE ] = Message::TM_PING;
$message[ Message::TO ] = $this->prefix( $args[0] ?? '' );
// %.6F: a (string) cast rounds, and rounding up = negative RTT.
$message[ Message::VALUE ] = \sprintf( '%.6F', Core::$now );
break;
case 'request':
case 'request_node':
if ( '' === ( $args[0] ?? '' ) ) {
$this->stdout( "usage: request <path> <args>\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_REQUEST;
$message[ Message::TO ] = $this->prefix( $args[0] );
$message[ Message::VALUE ] = \implode( ' ', \array_slice( $args, 1 ) );
break;
case 'send':
case 'send_node':
if ( '' === ( $args[0] ?? '' ) ) {
$this->stdout( "usage: send <path> <bytes>\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_BYTESTREAM;
$message[ Message::TO ] = $this->prefix( $args[0] );
$message[ Message::VALUE ] = \implode( ' ', \array_slice( $args, 1 ) ) . "\n";
break;
case 'send_struct':
case 'send_struct_node':
if ( '' === ( $args[0] ?? '' ) ) {
$this->stdout( "usage: send_struct <path> <json>\n" );
return null;
}
// Runs in parse(), before central catch — decode error here.
try {
$decoded = \json_decode( \implode( ' ', \array_slice( $args, 1 ) ), true, 512, \JSON_THROW_ON_ERROR );
} catch ( \JsonException $e ) {
$this->stdout( 'send_struct: ' . $e->getMessage() . "\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_STRUCT;
$message[ Message::TO ] = $this->prefix( $args[0] );
$message[ Message::VALUE ] = $decoded;
break;
case 'send_eof':
if ( '' === ( $args[0] ?? '' ) ) {
$this->stdout( "usage: send_eof <path>\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_EOF;
$message[ Message::TO ] = $this->prefix( $args[0] );
break;
case 'tell':
case 'tell_node':
if ( '' === ( $args[0] ?? '' ) ) {
$this->stdout( "usage: tell <path> <bytes>\n" );
return null;
}
$message[ Message::TYPE ] = Message::TM_INFO;
$message[ Message::TO ] = $this->prefix( $args[0] );
$message[ Message::VALUE ] = \implode( ' ', \array_slice( $args, 1 ) );
break;
default:
// TO=cwd: empty - local interpreter; set - routed via _router.
$message[ Message::TYPE ] = Message::TM_COMMAND;
$message[ Message::TO ] = $this->prefix( '' );
$message[ Message::VALUE ] = [
'name' => $verb,
'arguments' => $args,
];
break;
}
$this->stamp_noreply( $message );
return $message;
}
/**
* The Shell's BUILTINS table (Tachikoma Shell.pm:103+): each verb acts on
* shell or session state and produces no message. Returns whether the verb
* was one — false sends parse() on to mint a command, which is Shell.pm's
* `if ( $BUILTINS{$name} ) ... else send_command(...)` in switch form.
*
* @param string $verb The first token of the statement.
* @param list<string> $args Tokens after the verb.
* @return bool True when the verb was a builtin and no message is minted.
*/
private function run_builtin( string $verb, array $args ): bool {
switch ( $verb ) {
case 'include':
$this->include_file( $args[0] ?? '' );
return true;
case 'cd':
case 'chdir':
$this->path = $this->cd( $this->path, $args[0] ?? '' );
$this->prompt = '/' . $this->path . '> ';
return true;
case 'print':
$this->stdout( \implode( ' ', $args ) );
return true;
case 'clear':
$this->stdout_control( "\033[2J\033[H" );
return true;
case 'debug_level':
$this->debug_level_command( $args[0] ?? '' );
return true;
case 'status':
foreach ( $this->status_lines as $status_line ) {
$this->stdout( $status_line . "\n" );
}
return true;
case 'show_parse':
$this->show_parse = ! $this->show_parse;
$this->stdout( 'show_parse: ' . ( $this->show_parse ? 'on' : 'off' ) . "\n" );
return true;
case 'var':
$this->var_command( \implode( ' ', $args ) );
return true;
default:
return false;
}
}
/**
* This session's reply address — where a worker's answer comes back to.
* Stamped on every message the Shell mints and on the EOF drain marker.
*
* @return string The `_output/<pid>` path Router dispatches a reply by.
*/
private function reply_from(): string {
return Node_Names::OUTPUT . '/' . \getmypid();
}
/**
* `debug_level [ 0 | 1 | 2 ]` — dials the `_output` Dumper's rendering,
* after Shell.pm:154. A bare verb toggles 0↔1.
*
* Refuses anything that is not a level, as Shell.pm's `^\d+$` and the JS
* twin's usage line both do: a cast would read `abc` as 0 and quietly turn
* the dial OFF. A Shell driving a TSL in worker or request scope has no
* Dumper at all, and says so rather than reporting a dial it never moved.
*
* @param string $level Requested level, or '' to toggle.
*/
private function debug_level_command( string $level ): void {
$max = Dumper_Node::MAX_DEBUG_LEVEL;
$usage = \implode( '|', \range( 0, $max ) );
if ( '' !== $level && ( ! \ctype_digit( $level ) || (int) $level > $max ) ) {
$this->stdout( "usage: debug_level [$usage]\n" );
return;
}
$dumper = Core::node( Node_Names::OUTPUT );
if ( ! $dumper instanceof Dumper_Node ) {
$this->stdout( 'debug_level: unknown node: ' . Node_Names::OUTPUT . "\n" );
return;
}
$next = '' === $level
? ( $dumper->debug_level() > 0 ? 0 : 1 )
: (int) $level;
$this->stdout( 'debug_level: ' . $dumper->set_debug_level( $next ) . "\n" );
}
/**
* `var [ <name> [ <op> [ <value> ] ] ]` — follows Shell3's var_assignment.
*
* Bare lists every var as `name=value`; a name alone prints its value and
* autovivifies it to empty (Shell3.pm:2715); `<name> =` with no value
* DELETES it (Shell3.pm:2839); otherwise the operator set applies.
*
* @param string $assignment The tokens after `var`, re-joined with spaces.
*/
private function var_command( string $assignment ): void {
// ltrim only: a trailing whitespace VALUE must reach the grammar.
$assignment = \ltrim( $assignment );
if ( '' === \rtrim( $assignment ) ) {
$out = '';
$all = Core::$var;
\ksort( $all );
foreach ( $all as $name => $value ) {
$out .= $name . '=' . \rtrim( Core::as_string( $value, '' ), "\n" ) . "\n";
}
if ( '' !== $out ) {
$this->stdout( $out );
}
return;
}
if ( ! \preg_match( self::VAR_GRAMMAR, $assignment, $m ) ) {
$this->stdout( "var: expected <name> [ <op> [ <value> ] ]\n" );
return;
}
[ , $name, $op, $raw_value ] = $m + [ 3 => '' ];
// Shell3:2825 — a value TOKEN sets (even if blank); none deletes.
$has_value = '' !== $raw_value;
// ltrim only: tokenize stripped the edges, so the tail is content.
$value = \ltrim( $raw_value );
if ( \str_contains( $name, ':' ) ) {
$this->stdout( "var: invalid name '{$name}' (':' is reserved for namespaces like config:)\n" );
return;
}
if ( '' === $op ) {
// Shell3:630 fatals on trailing junk where an operator belongs.
if ( '' !== \trim( $value ) ) {
$this->stdout( "var: unexpected token in assignment: {$value}\n" );
return;
}
// Reading defines the key — Shell3's `$hash->{$name} //= q()`.
Core::$var[ $name ] ??= '';
$read = Core::as_string( Core::$var[ $name ], '' );
// Printed verbatim: an empty value prints nothing at all.
if ( '' !== $read ) {
$this->stdout( $read );
}
return;
}
$this->operate( $name, $op, $value, $has_value );
}
/**
* Shell3's `operate()` / `operate_with_value()` over one var.
*
* @param string $name Var name, already checked for a namespace colon.
* @param string $op One of `= .= += -= *= /= //= ||= ++ --`.
* @param string $value Right-hand side, left-trimmed.
* @param bool $has_value Whether a value TOKEN followed the operator; false
* is what makes `var x =` a delete rather than a set.
*/
private function operate( string $name, string $op, string $value, bool $has_value ): void {
$current = Core::as_string( Core::$var[ $name ] ?? '', '' );
$exists = \array_key_exists( $name, Core::$var );
if ( ! $has_value ) {
// Valueless: only these three exist; the rest are usage errors.
if ( '=' === $op ) {
unset( Core::$var[ $name ] );
} elseif ( '++' === $op ) {
Core::$var[ $name ] = self::format_number( Core::num_float( $current, 0 ) + 1 );
} elseif ( '--' === $op ) {
Core::$var[ $name ] = self::format_number( Core::num_float( $current, 0 ) - 1 );
} else {
$this->stdout( "var: bad arguments: {$op}\n" );
}
return;
}
switch ( $op ) {
case '=':
Core::$var[ $name ] = $value;
return;
case '.=':
Core::$var[ $name ] = $exists ? $current . ' ' . $value : $value;
return;
case '//=':
if ( ! $exists ) {
Core::$var[ $name ] = $value;
}
return;
case '||=':
if ( '' === $current || '0' === $current ) {
Core::$var[ $name ] = $value;
}
return;
case '/=':
if ( 0.0 === Core::num_float( $value, 0 ) ) {
$this->stdout( "var: division by zero\n" );
return;
}
Core::$var[ $name ] = self::format_number( Core::num_float( $current, 0 ) / Core::num_float( $value, 0 ) );
return;
case '+=':
case '-=':
case '*=':
$left = Core::num_float( $current, 0 );
$right = Core::num_float( $value, 0 );
Core::$var[ $name ] = self::format_number(
'+=' === $op ? $left + $right : ( '-=' === $op ? $left - $right : $left * $right )
);
return;
default:
$this->stdout( "var: invalid operator: {$op}\n" );
}
}
/**
* Render a float as Perl prints one: an integral value loses its fractional
* part, so `var n ++` on an unset var yields `1` rather than `1.0`.
*
* @param float $n Arithmetic result.
* @return string The rendered number.
*/
private static function format_number( float $n ): string {
return (float) (int) $n === $n ? (string) (int) $n : (string) $n;
}
/**
* Quote-aware single-tier interpolation. Outside quotes and inside double
* quotes: `<ns:key>` → that namespace's registered resolver
* (Core::resolve_config_token); bare `<var>` → Core::$var; unknown → ''.
* Inside single quotes or backticks the `<…>` is left LITERAL (standard shell
* semantics) so a token can be deferred to a downstream binder — e.g. a Topic
* line writes `<config:logs_dir>/jobs.p'<partition>'`, expanding the dir now
* and handing the raw `<partition>` to Topic. The quote chars survive here;
* tokenize() strips them afterward.
*
* @param string $line One statement, before tokenizing.
* @return string The line with every eligible `<…>` expanded.
*/
public function interpolate( string $line ): string {
$out = '';
$literal = null; // active quote/backtick span, suppresses expansion.
$length = \strlen( $line );
for ( $i = 0; $i < $length; ) {
$ch = $line[ $i ];
if ( null !== $literal ) {
// `\'` is an escaped quote, not the span's end.
if ( '\\' === $ch && $i + 1 < $length ) {
$out .= $ch . $line[ $i + 1 ];
$i += 2;
continue;
}
$out .= $ch;
if ( $ch === $literal ) {
$literal = null;
}
++$i;
continue;
}
// An escape pair passes through; tokenize() resolves it later.
if ( '\\' === $ch && $i + 1 < $length ) {
$out .= $ch . $line[ $i + 1 ];
$i += 2;
continue;
}
// A comment tail is inert — copy it verbatim, expand nothing.
if ( '#' === $ch ) {
return $out . \substr( $line, $i );
}
if ( "'" === $ch || '`' === $ch ) {
$literal = $ch;
$out .= $ch;
++$i;
continue;
}
if ( '<' === $ch && \preg_match( '/\G<([a-zA-Z_][a-zA-Z0-9_]*(?::[a-zA-Z_][a-zA-Z0-9_]*)?)>/', $line, $m, 0, $i ) ) {
$key = $m[1];
$colon = \strpos( $key, ':' );
if ( false !== $colon ) {
$out .= Core::resolve_config_token( \substr( $key, 0, $colon ), \substr( $key, $colon + 1 ) );
} else {
// get_shared: undefined warns, defined-empty is silent.
if ( ! \array_key_exists( $key, Core::$var ) ) {
// Raw, like Shell3's `print {*STDERR}`: no prefix.
Core::_stderr( "WARNING: use of uninitialized value <{$key}>\n", true );
}
$out .= Core::as_string( Core::$var[ $key ] ?? '', '' );
}
$i += \strlen( $m[0] );
continue;
}
$out .= $ch;
++$i;
}
return $out;
}
/**
* Quote-aware tokenizer ('/"/`): splits on unquoted whitespace, strips the quote chars.
*
* @api The PHP side of the JS `tokenize` parity mirror — three JS docblocks
* name it as the byte-for-byte anchor, and the round-trip tests read a
* serialized line back through it.
*
* @param string $line One statement.
* @return list<string> The tokens, quote chars stripped and escapes resolved.
*/
public function tokenize( string $line ): array {
return \array_column( self::scan_tokens( $line ), 'value' );
}