Skip to main content

nu_protocol/engine/
closure.rs

1use crate::{BlockId, HASH_ITEM_LIMIT, ShellError, Span, Value, VarId, engine::EngineState};
2use serde::{Deserialize, Serialize};
3use std::{
4    borrow::Cow,
5    fmt::{self, Debug},
6    hash::{Hash, Hasher},
7};
8
9#[derive(Clone, Serialize, Deserialize)]
10pub struct Closure {
11    pub block_id: BlockId,
12    pub captures: Vec<(VarId, Value)>,
13}
14
15impl Debug for Closure {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        f.debug_struct("Closure")
18            .field("block_id", &self.block_id)
19            .field(
20                "captures",
21                &fmt::from_fn(|f| {
22                    f.debug_map()
23                        .entries(self.captures.iter().map(|(k, v)| (k, v)))
24                        .finish()
25                }),
26            )
27            .finish()
28    }
29}
30
31impl Hash for Closure {
32    /// Hashes `block_id`, the number of captures, and the first [`HASH_ITEM_LIMIT`] captures in
33    /// order, which agrees with [`Value::strict_eq`]'s positional compare of captures. Closures
34    /// built from one literal with different captures then land in different buckets.
35    fn hash<H: Hasher>(&self, state: &mut H) {
36        self.block_id.hash(state);
37        self.captures.len().hash(state);
38        for capture in self.captures.iter().take(HASH_ITEM_LIMIT) {
39            capture.hash(state);
40        }
41    }
42}
43
44/// Help text shared by every error reporting a closure whose block is not
45/// available in the engine state, most commonly because the closure was
46/// parsed after the running job was spawned.
47pub const MISSING_CLOSURE_BLOCK_HELP: &str = "the closure was likely parsed after this job was spawned; define it before `job spawn`, or pass plain data instead of a closure";
48
49impl Closure {
50    pub fn coerce_into_string<'a>(
51        &self,
52        engine_state: &'a EngineState,
53        span: Span,
54    ) -> Result<Cow<'a, str>, ShellError> {
55        let block = engine_state.try_get_block(self.block_id);
56        if let Some(span) = block.and_then(|block| block.span) {
57            let contents_bytes = engine_state.get_span_contents(span);
58            Ok(String::from_utf8_lossy(contents_bytes))
59        } else {
60            Err(ShellError::CantConvert {
61                to_type: "string".into(),
62                from_type: "closure".into(),
63                span,
64                help: Some(format!(
65                    "unable to retrieve block contents for closure with id {}",
66                    self.block_id.get()
67                )),
68            })
69        }
70    }
71
72    /// Returns an estimate of the memory size used by this Closure in bytes
73    pub fn memory_size(&self) -> usize {
74        std::mem::size_of::<Self>()
75            + self
76                .captures
77                .iter()
78                .map(|(_, v)| v.memory_size())
79                .sum::<usize>()
80    }
81
82    pub(crate) fn compact_debug(&self) -> impl Debug {
83        fmt::from_fn(|f| {
84            write!(f, "{:?}: ", self.block_id)?;
85            f.debug_map()
86                .entries(self.captures.iter().map(|(k, v)| (k, v)))
87                .finish()
88        })
89    }
90}