oxdock_core/exec/state.rs
1use std::collections::HashMap;
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64};
4use std::sync::{Arc, Condvar, Mutex};
5
6use anyhow::Result;
7use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs};
8use oxdock_parser::{Field, Step, TypeDescriptor, TypeTag, Value};
9use oxdock_process::{BackgroundHandle, CommandContext, ProcessManager};
10
11use super::io::{ExactCapture, ExecIo, SlidingWindow};
12use super::native::FunctionRegistry;
13use oxdock_pipe::KeeperGuard;
14
15/// Maximum nested function-call depth. Guards the host thread stack against
16/// runaway recursion; the error names the function that overflowed.
17pub(super) const MAX_CALL_DEPTH: usize = 64;
18
19/// Execution state for one script run. Public so hosts can register
20/// functions and introspect listings; all fields stay crate-private so the
21/// scope, recursion-budget, and task invariants cannot be broken from outside.
22pub struct ExecState<P: ProcessManager> {
23 pub(super) fs: Box<dyn WorkspaceFs>,
24 /// Pre-reserved guarded scratch name for `CARGO_TARGET_DIR` (issue #131).
25 /// Opaque [`CargoScratch`]: renderable for the child environment but not
26 /// nameable as a `&GuardedPath`, so host code cannot `ensure()` or
27 /// `create_dir_all` it. The child `cargo` creates it on demand.
28 pub(super) cargo_scratch: CargoScratch,
29 /// Pure session seed from [`oxdock_process::seed_defaults`], stored at
30 /// init alongside the layered `envs`. `ISOLATED` resets clone this
31 /// (not the layered map), and transport sanitize diffs against it.
32 /// Built once: re-seeding would re-read host fallbacks and break
33 /// state stability.
34 pub(super) seed: Arc<HashMap<String, String>>,
35 pub(super) cwd: GuardedPath,
36 pub(super) envs: Arc<HashMap<String, String>>,
37 /// Outer-scope env snapshots for `ISOLATED` blocks, innermost last.
38 /// Each entry is the script env as it stood at that block's entry, so
39 /// the block allowlist resolves against the enclosing scope even as
40 /// the live envs are scrubbed underneath. Nesting snapshots the
41 /// already-scrubbed parent, so narrowing is monotonic by
42 /// construction. Cloned (not reset) by `fork()` so tasks spawned
43 /// inside a block inherit its scrub.
44 pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
45 pub(super) bg_children: Vec<Box<dyn BackgroundHandle>>,
46 pub(super) scope_stack: Vec<ScopeSnapshot>,
47 pub(super) io: ExecIo,
48 /// Pre-registered SlidingWindow observers for stream assertion steps.
49 /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
50 pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
51 /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
52 pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
53 /// Exact-match stdout accumulators for `ASSERT_EQ stdout`, keyed by
54 /// generation and fed by the same tee. Entries allocated during
55 /// pre-registration observe bytes from scope entry; the common
56 /// top-level case therefore sees trial-cumulative output.
57 pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
58 /// Variable scopes for $variable bindings (FOR loops, LET assignments).
59 /// Innermost scope is last. Variables are looked up from innermost to outermost.
60 /// Each entry carries its declared type name alongside the value.
61 pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
62 /// Name directory for type resolution: startup descriptors plus the
63 /// run's host descriptors. Words carry their own vtables, so this map
64 /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
65 pub(super) types: HashMap<String, &'static TypeDescriptor>,
66 /// Named record schemas for shaped MAP bindings: schema name to its
67 /// field table. Populated from host modules alongside descriptors, so
68 /// `LET $s: SSH_SESSION_INFO` resolves exactly when the owning module
69 /// is registered. Impossible to reference an unregistered schema.
70 pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
71 /// Module-shared state stashed at registration, keyed by owning
72 /// module name plus value type. Bodies fetch it through
73 /// `StepCtx::module_state` instead of hand-built closures, so
74 /// every entry can stay `#[oxdock_func]`.
75 pub(super) module_states:
76 HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
77 /// Script-level type aliases for this run: alias name to canonical
78 /// target spelling (`PERSON` to `MAP<name:STRING>`). Populated once
79 /// from top-level `TYPE` steps before the static pass, so forward
80 /// references resolve run-wide at first coercion.
81 pub(super) type_aliases: HashMap<String, String>,
82 /// Cancellation token for background thread teardown.
83 #[allow(dead_code)]
84 pub(super) cancel_token: Arc<AtomicBool>,
85 /// Handle to the currently executing foreground OS process, so
86 /// ThreadJoinHandle::kill() can interrupt a blocking wait().
87 #[allow(dead_code)]
88 pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
89 /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
90 /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
91 /// the handle lives inside the entry so `CANCEL` can synchronously tear
92 /// down a task even while a concurrent `AWAIT` is waiting on it.
93 /// Entries are retained as `Cancelled`/`Completed` tombstones so later
94 /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
95 #[allow(dead_code)]
96 pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
97 /// Counter for generating unique task IDs. Shared across subscopes via Arc.
98 #[allow(dead_code)]
99 pub(super) next_task_id: Arc<AtomicU64>,
100 /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
101 /// spawns in background mode so the handle can be registered for cancellation.
102 pub(super) inside_async: bool,
103 /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
104 /// pipe the worker produces to, bridging the spawn-to-first-attach
105 /// window and every transient gap between producer steps. Guards keyed
106 /// to step `k` drop when the worker completes its top-level step `k`
107 /// (matched by slice identity, so nested bodies never discharge them);
108 /// leftovers drop with the worker thread. Always `None` outside
109 /// workers; `fork` never inherits it.
110 pub(super) keeper_expiry: Option<KeeperExpiry>,
111 /// Whether `handlers::run()` must spawn in background mode so the handle
112 /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
113 /// body executes on the current thread so the deadline watcher can kill
114 /// a blocking foreground process. Unlike `inside_async`, this does not
115 /// affect end-of-pipeline named-task reaping.
116 pub(super) cancellable: bool,
117 /// The single function registry: DSL `FUNC` definitions, builtins, and
118 /// host extensions. Script entries scope lexically through the
119 /// registry's own frames (managed by `push_scope`/`pop_scope`);
120 /// native entries persist. Shared across `fork()` via clone.
121 pub(super) functions: FunctionRegistry<P>,
122 /// Current nested function-call depth on this thread. Enforced against
123 /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
124 /// inherit the caller's depth budget.
125 pub(super) call_depth: usize,
126 /// Identity of the task this state executes (`0` = root flow).
127 /// Stamped onto pipe handles minted here and compared by the promotion
128 /// check: only the declaring task may promote its own pipes.
129 pub(super) task_id: u64,
130 /// Declared `--to-host` transfers recorded strictly at execution time:
131 /// each executed flagged `COPY` appends its evaluated
132 /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
133 /// these entries, so dead branches contribute nothing and dynamic
134 /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
135 /// in [`ExecIo`] when staged.
136 pub(super) push_manifest: Vec<(String, String)>,
137 pub(super) _marker: PhantomData<P>,
138}
139
140pub(super) struct ScopeSnapshot {
141 pub(super) cwd: GuardedPath,
142 pub(super) root: GuardedPath,
143 pub(super) envs: Arc<HashMap<String, String>>,
144}
145
146/// Lifecycle phase of a named background task (`LET $var: HANDLE = ASYNC ...`).
147/// `Running` and `Awaiting` both hold the live handle inside the entry;
148/// `Cancelled` and `Completed` are terminal tombstones with no handle.
149pub(super) enum TaskPhase {
150 Running,
151 Awaiting,
152 Cancelled,
153 Completed,
154}
155
156pub(super) struct TaskEntryState {
157 pub(super) phase: TaskPhase,
158 pub(super) handle: Option<Box<dyn BackgroundHandle>>,
159 /// True once the handle has been consumed and its thread joined
160 /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
161 /// Threads observing `Cancelled` must wait on `done` until `reaped`
162 /// before resuming, so no caller outruns OS process teardown.
163 pub(super) reaped: bool,
164 /// Explicit result of a background task, published by `RETURN` (block
165 /// bodies) or the function call itself (single-`CALL` bodies). Set
166 /// under the entry lock before `done.notify_all()`; read by
167 /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that returned nothing
168 /// or have not finished. Task stdout is never captured: it streams
169 /// live to the shared parent writer.
170 pub(super) return_value: Option<Value>,
171 /// Whether this task's body can publish a value: single-`CALL` bodies
172 /// always can; block bodies can iff they contain a `RETURN` in their
173 /// own scope. A task that can return but falls off the end fails its
174 /// capture loudly; a task that cannot return yields `INT` 0.
175 pub(super) returns_value: bool,
176}
177
178/// Synchronized named-task entry shared by every scope that can observe the
179/// task (`AWAIT`, `CANCEL`, end-poll reaping). Exactly one thread ever takes
180/// the handle and performs teardown; all other observers rendezvous on
181/// `done`/`reaped`.
182pub(super) struct TaskEntry {
183 pub(super) state: Mutex<TaskEntryState>,
184 pub(super) done: Condvar,
185}
186
187impl TaskEntry {
188 pub(super) fn new(handle: Box<dyn BackgroundHandle>, returns_value: bool) -> Self {
189 Self {
190 state: Mutex::new(TaskEntryState {
191 phase: TaskPhase::Running,
192 handle: Some(handle),
193 reaped: false,
194 return_value: None,
195 returns_value,
196 }),
197 done: Condvar::new(),
198 }
199 }
200
201 /// Block until the teardown owner has consumed the handle and joined
202 /// the task thread. Lock-free for callers except the wait itself.
203 pub(super) fn wait_reaped(&self) {
204 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
205 while !guard.reaped {
206 guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
207 }
208 }
209
210 /// Mark teardown complete and wake every rendezvous waiter.
211 pub(super) fn finish_teardown(&self) {
212 {
213 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
214 guard.handle = None;
215 guard.reaped = true;
216 }
217 self.done.notify_all();
218 }
219}
220
221/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
222/// keyed by the top-level body index of the final producer step for each
223/// pipe: dropping the guards for step `k` once it completes keeps the
224/// pipe open across every transient gap between producers, then releases
225/// it so later consumer steps in the same task observe EOF.
226///
227/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
228/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
229/// code with different slices and must never consume the worker's
230/// top-level map.
231pub(super) struct KeeperExpiry {
232 body_addr: usize,
233 body_len: usize,
234 map: HashMap<usize, Vec<KeeperGuard>>,
235}
236
237impl KeeperExpiry {
238 pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
239 Self {
240 body_addr: steps.as_ptr() as usize,
241 body_len: steps.len(),
242 map,
243 }
244 }
245
246 pub(super) fn matches(&self, steps: &[Step]) -> bool {
247 self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
248 }
249
250 /// Drop the guards expiring at top-level step `idx`. Returns true when
251 /// the map is drained and the expiry itself can be cleared.
252 pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
253 if self.matches(steps) {
254 drop(self.map.remove(&idx));
255 }
256 self.map.is_empty()
257 }
258}
259
260impl<P: ProcessManager> ExecState<P> {
261 /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
262 /// `Expr::Env`, expansions): exact hit first, case-insensitive
263 /// fallback on Windows so `{{ env:Path }}` resolves the seeded
264 /// `PATH`. The map is seeded at init, so no fallback layer exists.
265 pub(super) fn get_env(&self, key: &str) -> Option<&str> {
266 if let Some(v) = self.envs.get(key) {
267 return Some(v.as_str());
268 }
269 #[allow(clippy::disallowed_macros)]
270 if cfg!(windows) {
271 return self
272 .envs
273 .iter()
274 .find(|(k, _)| oxdock_process::names_eq(k, key))
275 .map(|(_, v)| v.as_str());
276 }
277 None
278 }
279
280 pub(super) fn command_ctx(&self) -> Result<CommandContext> {
281 // Resolve the working directory through the snapshot choke point: a
282 // snapshot-rooted cwd materializes here (so `RUN` executes against a
283 // real directory) while a local cwd resolves purely lexically with
284 // zero I/O. The seeded scratch materializes alongside: `HOME` and
285 // `TMPDIR` point at it, so children writing temp or profile data
286 // must observe real directories, never lexical candidates.
287 let cwd = self.fs.resolve_write(&self.cwd, ".")?;
288 self.cargo_scratch.ensure_materialized()?;
289 Ok(CommandContext::new(
290 &cwd.into(),
291 Arc::clone(&self.envs),
292 &self.cargo_scratch,
293 self.fs.root(),
294 self.fs.build_context(),
295 ))
296 }
297
298 /// Fork the execution state for a child thread. The child gets:
299 /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
300 /// - Cloned envs, cwd, cargo scratch name, var_scopes
301 /// - Fresh bg_children, scope_stack (empty -- child manages its own)
302 /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
303 /// - Cloned io configuration
304 /// - Independent cancel_token, active_process (child manages its own)
305 /// - Shared named_tasks and next_task_id (via Arc clone)
306 #[allow(dead_code)]
307 pub(super) fn fork(&self) -> Self {
308 Self {
309 fs: self.fs.clone_box(),
310 cargo_scratch: self.cargo_scratch.clone(),
311 seed: Arc::clone(&self.seed),
312 cwd: self.cwd.clone(),
313 envs: Arc::clone(&self.envs),
314 bg_children: Vec::new(),
315 scope_stack: Vec::new(),
316 isolated_stack: self.isolated_stack.clone(),
317 io: self.io.clone(),
318 assert_windows: Arc::clone(&self.assert_windows),
319 assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
320 exact_stdout: Arc::clone(&self.exact_stdout),
321 var_scopes: self.var_scopes.clone(),
322 cancel_token: Arc::new(AtomicBool::new(false)),
323 active_process: Arc::new(Mutex::new(None)),
324 named_tasks: Arc::clone(&self.named_tasks),
325 next_task_id: Arc::clone(&self.next_task_id),
326 inside_async: true,
327 keeper_expiry: None,
328 cancellable: self.cancellable,
329 functions: self.functions.clone(),
330 types: self.types.clone(),
331 record_schemas: self.record_schemas.clone(),
332 module_states: self.module_states.clone(),
333 type_aliases: self.type_aliases.clone(),
334 call_depth: self.call_depth,
335 task_id: self.task_id,
336 // Forks start with an empty manifest: async children record
337 // their own executions; the guest packs the root manifest.
338 push_manifest: Vec::new(),
339 _marker: PhantomData,
340 }
341 }
342
343 /// Whether `pipe` may promote to an OS kernel pair on behalf of
344 /// `task_id`: only when it was declared by that same task and no
345 /// spawned child can observe it. Anything else stays script-backed, so
346 /// concurrent tasks can never disagree about EOF propagation.
347 /// Spawning tasks pass their worker id (not the spawner's): promotion
348 /// is judged from the worker's perspective, since it is the worker's
349 /// bindings that will hold raw descriptors.
350 pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
351 pipe.declaring_task() == task_id && !pipe.has_escaped()
352 }
353
354 /// Whether `pipe` may promote on the current thread (main flow and
355 /// inline resolves).
356 pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
357 Self::can_promote_in_task(pipe, self.task_id)
358 }
359
360 /// Mark every pipe visible in scope as shared-with-a-child. Called
361 /// synchronously on the spawner before a worker thread starts: forking
362 /// copies the whole environment, so every visible pipe is capturable
363 /// whether or not the child body names it. Over-marking only costs
364 /// zero-copy opportunities, never correctness.
365 pub(super) fn mark_captured_pipes_escaped(&self) {
366 for scope in self.var_scopes.iter() {
367 for (_, value) in scope.values() {
368 mark_value_pipes_escaped(value);
369 }
370 }
371 }
372
373 pub(super) fn push_var_scope(&mut self) {
374 self.var_scopes.push(HashMap::new());
375 }
376
377 pub(super) fn pop_var_scope(&mut self) {
378 self.var_scopes.pop();
379 }
380
381 /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
382 /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
383 /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
384 /// Function definitions scope through the registry's own frames.
385 pub(super) fn push_scope(&mut self) {
386 self.scope_stack.push(ScopeSnapshot {
387 cwd: self.cwd.clone(),
388 root: self.fs.root().clone(),
389 envs: Arc::clone(&self.envs),
390 });
391 self.functions.push_scope();
392 self.push_var_scope();
393 }
394
395 /// Exit a lexical scope, restoring everything `push_scope` saved.
396 pub(super) fn pop_scope(&mut self) -> Result<()> {
397 let snapshot = self
398 .scope_stack
399 .pop()
400 .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
401 self.fs.set_root(&snapshot.root);
402 self.cwd = snapshot.cwd;
403 self.envs = snapshot.envs;
404 self.functions.pop_scope();
405 self.pop_var_scope();
406 Ok(())
407 }
408 pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
409 if self
410 .var_scopes
411 .last()
412 .map(|s| s.contains_key(&key))
413 .unwrap_or(false)
414 {
415 anyhow::bail!(
416 "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
417 key,
418 key
419 );
420 }
421 let coerced = super::args::coerce_value(value, &kind)?;
422 let scope = self
423 .var_scopes
424 .last_mut()
425 .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
426 scope.insert(key, (kind, coerced));
427 Ok(())
428 }
429
430 pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
431 let kind = self
432 .var_scopes
433 .iter()
434 .rev()
435 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
436 .ok_or_else(|| {
437 anyhow::anyhow!(
438 "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
439 )
440 })?;
441 let coerced = super::args::coerce_value(value, &kind)?;
442 for scope in self.var_scopes.iter_mut().rev() {
443 if let Some(slot) = scope.get_mut(key) {
444 slot.1 = coerced;
445 return Ok(());
446 }
447 }
448 anyhow::bail!("undeclared variable ${key}");
449 }
450
451 /// Append `item` to the LIST binding `key` in place. Copy-on-write:
452 /// the buffer detaches only when shared, so aliases keep their
453 /// contents; the sole owner mutates with no copy. Bails for
454 /// undeclared names and non-list bindings. Shaped lists validate
455 /// the item against the element tag, so a push can never silently
456 /// corrupt the shape the declaration promises.
457 pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
458 let kind = self
459 .var_scopes
460 .iter()
461 .rev()
462 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
463 .ok_or_else(|| {
464 anyhow::anyhow!(
465 "undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
466 )
467 })?;
468 let element = match kind {
469 TypeTag::List => None,
470 TypeTag::ListOf(element) => Some(element.as_ref().clone()),
471 _ => {
472 anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
473 }
474 };
475 for scope in self.var_scopes.iter_mut().rev() {
476 if let Some(slot) = scope.get_mut(key) {
477 let list = slot.1.as_list_mut().ok_or_else(|| {
478 anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
479 })?;
480 if let Some(expected) = element {
481 oxdock_parser::check_value_at(
482 &expected,
483 &item,
484 &format!("${key}[{}]", list.len()),
485 )?;
486 }
487 list.push(item);
488 return Ok(());
489 }
490 }
491 anyhow::bail!("undeclared variable ${key}");
492 }
493
494 pub(super) fn get_var(&self, key: &str) -> Option<Value> {
495 // Walk scopes from innermost to outermost
496 for scope in self.var_scopes.iter().rev() {
497 if let Some((_, value)) = scope.get(key) {
498 return Some(value.clone());
499 }
500 }
501 None
502 }
503
504 pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
505 for scope in self.var_scopes.iter().rev() {
506 if let Some(entry) = scope.get(key) {
507 return Some(entry.clone());
508 }
509 }
510 None
511 }
512
513 /// Get a flattened view of all variables across all scopes.
514 /// Inner scopes take precedence over outer scopes.
515 pub(super) fn all_vars(&self) -> HashMap<String, Value> {
516 let mut result = HashMap::new();
517 for scope in self.var_scopes.iter().rev() {
518 for (k, (_, v)) in scope {
519 result.entry(k.clone()).or_insert_with(|| v.clone());
520 }
521 }
522 result
523 }
524}
525
526/// Mark every pipe handle reachable from `value` as shared-with-a-child.
527/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
528/// shallow top-level check would miss them and let a later promotion
529/// corrupt the shared EOF contract. Values form a tree, so recursion
530/// terminates; host-opaque payloads cannot carry handles.
531fn mark_value_pipes_escaped(value: &Value) {
532 if let Some(handle) = value.as_pipe_handle() {
533 handle.mark_escaped();
534 return;
535 }
536 if let Some(items) = value.as_list() {
537 for item in items {
538 mark_value_pipes_escaped(item);
539 }
540 }
541 if let Some(entries) = value.as_map() {
542 for item in entries.values() {
543 mark_value_pipes_escaped(item);
544 }
545 }
546}