nu_protocol/engine/
closure.rs

1use std::borrow::Cow;
2
3use crate::{BlockId, ShellError, Span, Value, VarId, engine::EngineState};
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct Closure {
9    pub block_id: BlockId,
10    pub captures: Vec<(VarId, Value)>,
11}
12
13impl Closure {
14    pub fn coerce_into_string<'a>(
15        &self,
16        engine_state: &'a EngineState,
17        span: Span,
18    ) -> Result<Cow<'a, str>, ShellError> {
19        let block = engine_state.get_block(self.block_id);
20        if let Some(span) = block.span {
21            let contents_bytes = engine_state.get_span_contents(span);
22            Ok(String::from_utf8_lossy(contents_bytes))
23        } else {
24            Err(ShellError::CantConvert {
25                to_type: "string".into(),
26                from_type: "closure".into(),
27                span,
28                help: Some(format!(
29                    "unable to retrieve block contents for closure with id {}",
30                    self.block_id.get()
31                )),
32            })
33        }
34    }
35}