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
use super::{pipe, util};
use crate::engine::ecs;
use slotmap::KeyData;
use std::collections::HashSet;
use std::io::Write;
/// Runs REPL commands against engine state.
///
/// This is intended to be called from the main thread (e.g. inside `Universe::update()`),
/// after commands are received from the stdin thread.
pub struct ReplBackend {
cwd: Option<ecs::ComponentId>,
}
impl ReplBackend {
pub fn new() -> Self {
Self { cwd: None }
}
pub(crate) fn cwd(&self) -> Option<ecs::ComponentId> {
self.cwd
}
fn format_component_id_short(id: ecs::ComponentId) -> String {
let s = format!("{:?}", id);
if let (Some(l), Some(r)) = (s.find('('), s.rfind(')')) {
if r > l + 1 {
return s[l + 1..r].to_string();
}
}
s
}
fn parse_component_id_short(s: &str) -> Option<ecs::ComponentId> {
// slotmap::KeyData debug format is "<idx>v<version>".
let (idx_str, ver_str) = s.split_once('v')?;
let idx: u32 = idx_str.parse().ok()?;
let version: u32 = ver_str.parse().ok()?;
let ffi = (u64::from(version) << 32) | u64::from(idx);
Some(KeyData::from_ffi(ffi).into())
}
pub(crate) fn current_listing(&self, world: &ecs::World) -> Vec<ecs::ComponentId> {
self.listing_for(world, self.cwd)
}
fn listing_for(
&self,
world: &ecs::World,
cwd: Option<ecs::ComponentId>,
) -> Vec<ecs::ComponentId> {
match cwd {
None => world
.all_components()
.filter(|&cid| world.parent_of(cid).is_none())
.collect(),
Some(cwd) => world.children_of(cwd).to_vec(),
}
}
fn resolve_in_listing(
&self,
world: &ecs::World,
listing: &[ecs::ComponentId],
segment: &str,
) -> Result<ecs::ComponentId, String> {
let (key_part, name_part) = segment.split_once(':').unwrap_or((segment, ""));
// 1) Numeric index into listing.
if let Ok(idx) = key_part.parse::<usize>() {
let cid = listing
.get(idx)
.copied()
.ok_or_else(|| format!("index out of range: {}", idx))?;
if !name_part.is_empty() {
let actual_name = world
.get_component_node(cid)
.map(|n| n.name.as_str())
.unwrap_or("<deleted>");
if actual_name != name_part {
return Err(format!(
"index {} resolved, but name mismatch: expected '{}' got '{}'",
idx, name_part, actual_name
));
}
}
return Ok(cid);
}
// 2) GUID.
if let Ok(guid) = key_part.parse::<uuid::Uuid>() {
for cid in listing.iter().copied() {
if let Some(node) = world.get_component_node(cid) {
if node.guid == guid {
if !name_part.is_empty() && node.name != name_part {
return Err(format!(
"guid {} resolved, but name mismatch: expected '{}' got '{}'",
guid, name_part, node.name
));
}
return Ok(cid);
}
}
}
return Err(format!("guid not found: {}", guid));
}
// 3) Short ComponentId token (e.g. 7v1).
if let Some(cid) = Self::parse_component_id_short(key_part) {
if listing.iter().any(|&c| c == cid) {
if !name_part.is_empty() {
let actual_name = world
.get_component_node(cid)
.map(|n| n.name.as_str())
.unwrap_or("<deleted>");
if actual_name != name_part {
return Err(format!(
"id {} resolved, but name mismatch: expected '{}' got '{}'",
key_part, name_part, actual_name
));
}
}
return Ok(cid);
}
return Err(format!("id not in current listing: {}", key_part));
}
// 4) Name.
let mut matches: Vec<ecs::ComponentId> = Vec::new();
for cid in listing.iter().copied() {
if let Some(node) = world.get_component_node(cid) {
if node.name == key_part {
matches.push(cid);
}
}
}
match matches.len() {
0 => Err(format!("not found: {}", key_part)),
1 => Ok(matches[0]),
_ => Err(format!(
"ambiguous name: {} (use 'ls' + index, guid, or id token)",
key_part
)),
}
}
fn cd_path(&self, world: &ecs::World, path: &str) -> Result<Option<ecs::ComponentId>, String> {
let is_abs = path.starts_with('/');
let mut cur: Option<ecs::ComponentId> = if is_abs { None } else { self.cwd };
let segments = path.split('/').filter(|s| !s.is_empty());
for seg in segments {
match seg {
"." => {}
".." => {
cur = cur.and_then(|cwd| world.parent_of(cwd));
}
_ => {
let listing = self.listing_for(world, cur);
let next = self.resolve_in_listing(world, &listing, seg)?;
cur = Some(next);
}
}
}
Ok(cur)
}
pub(crate) fn resolve_path_or_item(
&self,
world: &ecs::World,
arg: &str,
) -> Result<Option<ecs::ComponentId>, String> {
match arg {
"/" => Ok(None),
"." => Ok(self.cwd),
".." => Ok(self.cwd.and_then(|cwd| world.parent_of(cwd))),
_ if arg.contains('/') => self.cd_path(world, arg),
_ if arg.parse::<uuid::Uuid>().is_ok() => {
// For single-item GUID lookups (not path segments), allow global resolution.
// This keeps `cd /a/b/c` semantics local, but makes `cat <guid>` usable anywhere.
let guid = arg
.parse::<uuid::Uuid>()
.map_err(|e| format!("invalid guid: {}", e))?;
world
.component_id_by_guid(guid)
.map(Some)
.ok_or_else(|| format!("guid not found: {}", guid))
}
_ => {
let listing = self.current_listing(world);
Ok(Some(self.resolve_in_listing(world, &listing, arg)?))
}
}
}
/// Execute a single REPL command.
///
/// This currently only reads from `world` and updates internal REPL state (cwd).
pub fn exec(&mut self, world: &ecs::World, cmd: &str) {
let cmd = cmd.trim();
if cmd.is_empty() {
return;
}
// Pipe system (component-object pipes).
if cmd.contains('|') {
match pipe::try_exec_piped(self, world, cmd) {
Ok(true) => return,
Ok(false) => {}
Err(e) => {
println!("🐈 pipe: {}", e);
return;
}
}
}
// If the cwd component was deleted, reset to root.
if let Some(cwd) = self.cwd {
if world.get_component_node(cwd).is_none() {
self.cwd = None;
}
}
let mut it = cmd.split_whitespace();
let Some(verb) = it.next() else {
return;
};
match verb {
"help" => {
println!("🐈 Commands:");
println!("🐈 ls");
println!("🐈 tree [max_depth]");
println!("🐈 cd <name>");
println!("🐈 cd <index>");
println!("🐈 cd <guid>");
println!("🐈 cd <path>");
println!("🐈 cd ..");
println!("🐈 cd /");
println!("🐈 pwd");
println!("🐈 type [path]");
println!("🐈 cat <path>");
println!("🐈 ls | grep <pattern>");
println!("🐈 cat <path> | grep <pattern>");
println!("🐈 <cmd> | (trailing pipe prints summary)");
println!("🐈 clear");
}
"clear" | "cls" => {
// Clear screen + move cursor to home. (Many terminals also treat 3J as clear scrollback.)
print!("\x1b[2J\x1b[H\x1b[3J");
let _ = std::io::stdout().flush();
}
"pwd" => match self.cwd {
None => println!("🐈 /"),
Some(mut cur) => {
let mut parts: Vec<String> = Vec::new();
loop {
let Some(node) = world.get_component_node(cur) else {
break;
};
parts.push(format!(
"{}:{}",
Self::format_component_id_short(cur),
node.name
));
match world.parent_of(cur) {
Some(p) => cur = p,
None => break,
}
}
parts.reverse();
println!("🐈 /{}", parts.join("/"));
}
},
"type" | "kind" => {
// If no arg is provided, default to the current working directory.
// At root (cwd=None), print a sentinel.
let target = match it.next() {
None => self.cwd,
Some(arg) => match self.resolve_path_or_item(world, arg) {
Ok(t) => t,
Err(e) => {
println!("🐈 type: {}", e);
return;
}
},
};
match target {
None => println!("🐈 type: <root>"),
Some(cid) => {
let Some(node) = world.get_component_node(cid) else {
println!("🐈 type: not found");
return;
};
let kind = node.component.name();
println!(
"🐈 type: {} (name='{}' id={} guid={})",
kind,
node.name,
Self::format_component_id_short(cid),
node.guid
);
}
}
}
"ls" => {
let ids: Vec<ecs::ComponentId> = self.current_listing(world);
if ids.is_empty() {
println!("🐈 (empty)");
return;
}
for (i, cid) in ids.into_iter().enumerate() {
if let Some(line) = util::format_ls_line(world, i, cid) {
println!("{}", line);
}
}
}
"tree" => {
let arg = it.next();
if it.next().is_some() {
println!("🐈 tree: usage: tree [max_depth]");
return;
}
let max_depth: Option<usize> = match arg {
None => None,
Some(s) => match s.parse::<usize>() {
Ok(v) => Some(v),
Err(_) => {
println!("🐈 tree: invalid max_depth: {}", s);
return;
}
},
};
self.print_tree(world, max_depth);
}
"cat" => {
// If no arg is provided, default to the current working directory.
// - At root (cwd=None): dump the whole scene (all roots)
// - Otherwise: dump the cwd subtree
let target = match it.next() {
None => self.cwd,
Some(arg) => match self.resolve_path_or_item(world, arg) {
Ok(t) => t,
Err(e) => {
println!("🐈 cat: {}", e);
return;
}
},
};
use crate::scripting::component_registry::subtree_to_ce_ast;
use crate::scripting::unparser::unparse_component;
match target {
Some(root) => match subtree_to_ce_ast(world, root) {
Ok(ce) => println!("{}", unparse_component(&ce)),
Err(e) => println!("🐈 cat: {}", e),
},
None => {
let root_ids: Vec<ecs::ComponentId> = world
.all_components()
.filter(|&cid| world.parent_of(cid).is_none())
.collect();
for (i, cid) in root_ids.iter().enumerate() {
if i > 0 {
println!();
}
match subtree_to_ce_ast(world, *cid) {
Ok(ce) => println!("{}", unparse_component(&ce)),
Err(e) => println!("🐈 cat: {}", e),
}
}
}
}
}
"cd" => {
let Some(arg) = it.next() else {
println!(
"🐈 usage: cd <name> | cd <index> | cd <guid> | cd <path> | cd .. | cd /"
);
return;
};
match arg {
"/" => {
self.cwd = None;
}
".." => {
self.cwd = self.cwd.and_then(|cwd| world.parent_of(cwd));
}
name => {
// Path form (supports absolute/relative):
// cd /7v1:root/8v1:child
// cd 7v1:child/grandchild
if name.contains('/') {
match self.cd_path(world, name) {
Ok(new_cwd) => self.cwd = new_cwd,
Err(e) => println!("🐈 cd: {}", e),
}
return;
}
let candidates: Vec<ecs::ComponentId> = self.current_listing(world);
// 1) If it's a numeric index, treat it as an index into the last listing.
if let Ok(idx) = name.parse::<usize>() {
if let Some(cid) = candidates.get(idx).copied() {
self.cwd = Some(cid);
} else {
println!("🐈 cd: index out of range: {}", idx);
}
return;
}
// 2) If it parses as a UUID, match on GUID.
if let Ok(guid) = name.parse::<uuid::Uuid>() {
let mut found: Option<ecs::ComponentId> = None;
for cid in candidates.iter().copied() {
if let Some(node) = world.get_component_node(cid) {
if node.guid == guid {
found = Some(cid);
break;
}
}
}
// If not found in the current listing, allow a global jump-by-guid.
if found.is_none() {
found = world.component_id_by_guid(guid);
}
match found {
Some(cid) => self.cwd = Some(cid),
None => println!("🐈 cd: guid not found: {}", guid),
}
return;
}
// 3) Otherwise, treat it as a name.
let mut matches: Vec<ecs::ComponentId> = Vec::new();
for cid in candidates.iter().copied() {
if let Some(node) = world.get_component_node(cid) {
if node.name == name {
matches.push(cid);
}
}
}
match matches.len() {
0 => println!("🐈 cd: not found: {}", name),
1 => self.cwd = Some(matches[0]),
_ => {
println!("🐈 cd: ambiguous name: {}", name);
println!("🐈 hint: use 'ls' then 'cd <index>' or 'cd <guid>'");
}
}
}
}
}
_ => println!("🐈 unknown command: {}", verb),
}
}
fn print_tree(&self, world: &ecs::World, max_depth: Option<usize>) {
let mut visited: HashSet<ecs::ComponentId> = HashSet::new();
match self.cwd {
None => {
println!("🐈 /");
let roots: Vec<ecs::ComponentId> = world
.all_components()
.filter(|&cid| world.parent_of(cid).is_none())
.collect();
for (i, cid) in roots.into_iter().enumerate() {
self.print_tree_node(world, cid, 0, i, &mut visited, max_depth);
}
}
Some(cwd) => {
// Print the current component first.
if let Some(line) = util::format_ls_line(world, 0, cwd) {
println!("{}", line);
} else {
println!("🐈 tree: cwd deleted");
return;
}
let children: Vec<ecs::ComponentId> = world.children_of(cwd).to_vec();
for (i, cid) in children.into_iter().enumerate() {
self.print_tree_node(world, cid, 1, i, &mut visited, max_depth);
}
}
}
}
fn print_tree_node(
&self,
world: &ecs::World,
cid: ecs::ComponentId,
depth: usize,
index_in_parent: usize,
visited: &mut HashSet<ecs::ComponentId>,
max_depth: Option<usize>,
) {
if let Some(limit) = max_depth {
if depth > limit {
return;
}
}
let indent = " ".repeat(depth);
if !visited.insert(cid) {
// Defensive: should be a tree, but avoid infinite loops.
if let Some(line) = util::format_ls_line(world, index_in_parent, cid) {
println!("{}{} 🌀(cycle)", indent, line);
}
return;
}
if let Some(line) = util::format_ls_line(world, index_in_parent, cid) {
println!("{}{}", indent, line);
} else {
return;
}
let children: Vec<ecs::ComponentId> = world.children_of(cid).to_vec();
for (i, ch) in children.into_iter().enumerate() {
self.print_tree_node(world, ch, depth + 1, i, visited, max_depth);
}
}
/// Execute all queued commands.
pub fn exec_all<I>(&mut self, world: &ecs::World, commands: I)
where
I: IntoIterator<Item = String>,
{
for cmd in commands {
self.exec(world, &cmd);
}
}
}