sim-shape 0.1.0

Shape algebra, comparison, and match-hook helpers.
Documentation
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
//! Atomic shapes: the leaf matchers `AnyShape`, `ExprKindShape`,
//! `NumberValueShape`, `ClassShape`, and `ExactExprShape`.

use crate::base::{ExprKind, MatchScore, Shape, ShapeDoc, ShapeMatch};
use crate::diagnostics::{expected_shape_diagnostic, expr_actual_label};
use crate::functions::shape_value;
use crate::primitives::object::ObjectExpr;
use crate::recursion::{DepthGuard, class_is_subclass_of_guarded, is_cyclic_parent_edge};
use sim_kernel::{Cx, Expr, Result, ShapeRef, Symbol, Value};

/// The total shape that accepts every value and expression.
///
/// This is the `core/Any` atomic shape: it matches anything with an exact
/// score and reports `is_total() == true`.
///
/// # Examples
///
/// ```rust
/// # use std::sync::Arc;
/// use sim_kernel::{Cx, DefaultFactory, Expr, NoopEvalPolicy};
/// use sim_shape::{AnyShape, Shape};
///
/// let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
/// let matched = AnyShape.check_expr(&mut cx, &Expr::Bool(true)).unwrap();
/// assert!(matched.accepted);
/// assert!(AnyShape.is_total());
/// ```
pub struct AnyShape;

impl Shape for AnyShape {
    fn symbol(&self) -> Option<Symbol> {
        Some(Symbol::qualified("core", "Any"))
    }

    fn is_total(&self) -> bool {
        true
    }

    fn check_value(&self, _cx: &mut Cx, _value: Value) -> Result<ShapeMatch> {
        Ok(ShapeMatch::accept(MatchScore::exact(0)))
    }

    fn check_expr(&self, _cx: &mut Cx, _expr: &Expr) -> Result<ShapeMatch> {
        Ok(ShapeMatch::accept(MatchScore::exact(0)))
    }

    fn describe(&self, _cx: &mut Cx) -> Result<ShapeDoc> {
        Ok(ShapeDoc::new("Any"))
    }
}

/// A shape that matches expressions of a single [`ExprKind`].
///
/// Accepts any expression whose syntactic kind equals the configured kind (for
/// example, every `String` expression); a subshape of the `core/Expr` shape.
pub struct ExprKindShape {
    kind: ExprKind,
}

impl ExprKindShape {
    /// Build a shape that matches expressions of the given kind.
    pub fn new(kind: ExprKind) -> Self {
        Self { kind }
    }

    /// The expression kind this shape matches.
    pub fn kind(&self) -> &ExprKind {
        &self.kind
    }
}

impl Shape for ExprKindShape {
    fn parents(&self, cx: &mut Cx) -> Result<Vec<ShapeRef>> {
        Ok(cx
            .registry()
            .shape_by_symbol(&Symbol::qualified("core", "Expr"))
            .cloned()
            .into_iter()
            .collect())
    }

    fn is_subshape_of(&self, _cx: &mut Cx, parent: &dyn Shape) -> Result<Option<bool>> {
        if let Some(parent) = parent.as_any().downcast_ref::<Self>() {
            return Ok(Some(self.kind == parent.kind));
        }
        if parent.as_any().is::<ExactExprShape>()
            || matches!(
                parent.symbol(),
                Some(symbol) if symbol == Symbol::qualified("core", "ExactExprShape")
            )
        {
            return Ok(Some(false));
        }
        Ok(matches!(
            parent.symbol(),
            Some(symbol) if symbol == Symbol::qualified("core", "Expr")
        )
        .then_some(true))
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        let expr = value.object().as_expr(cx)?;
        self.check_expr(cx, &expr)
    }

    fn check_expr(&self, _cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        if self.kind.matches(expr) {
            Ok(ShapeMatch::accept(MatchScore::exact(10)))
        } else {
            Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic(
                    format!("{} expression", self.kind.name()),
                    expr_actual_label(expr),
                ),
            ))
        }
    }

    fn describe(&self, _cx: &mut Cx) -> Result<ShapeDoc> {
        Ok(ShapeDoc::new(format!("expr-kind {}", self.kind.name())))
    }
}

/// A shape that matches number-domain values and number expressions.
///
/// On values it accepts anything the active number backend recognizes as a
/// number; on expressions it accepts literal `Number` forms. Named
/// `core/Number`.
pub struct NumberValueShape;

impl Shape for NumberValueShape {
    fn symbol(&self) -> Option<Symbol> {
        Some(Symbol::qualified("core", "Number"))
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        if cx.number_value_ref(value)?.is_some() {
            Ok(ShapeMatch::accept(MatchScore::exact(20)))
        } else {
            Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic("number value", "non-number value"),
            ))
        }
    }

    fn check_expr(&self, _cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        if matches!(expr, Expr::Number(_)) {
            Ok(ShapeMatch::accept(MatchScore::exact(10)))
        } else {
            Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic("number expression", expr_actual_label(expr)),
            ))
        }
    }

    fn describe(&self, _cx: &mut Cx) -> Result<ShapeDoc> {
        Ok(ShapeDoc::new("number value"))
    }
}

/// A shape that matches values and expressions of a named class.
///
/// Accepts a value whose class is, or is a subclass of, the named class, and
/// accepts class-symbol or object expressions for that class. Subshape
/// relationships follow the class hierarchy in the registry.
pub struct ClassShape {
    symbol: Symbol,
}

impl ClassShape {
    /// Build a shape that matches the class named by `symbol`.
    pub fn new(symbol: Symbol) -> Self {
        Self { symbol }
    }

    /// The class symbol this shape matches against.
    pub fn symbol(&self) -> &Symbol {
        &self.symbol
    }
}

impl Shape for ClassShape {
    fn parents(&self, cx: &mut Cx) -> Result<Vec<ShapeRef>> {
        let Some(class_value) = cx.registry().class_by_symbol(&self.symbol).cloned() else {
            return Ok(Vec::new());
        };
        let Some(class) = class_value.object().as_class() else {
            return Ok(Vec::new());
        };
        let child_id = class.id();
        let parent_classes = class.parents(cx)?;
        let mut out = Vec::new();
        for parent in parent_classes {
            let Some(parent_class) = parent.object().as_class() else {
                continue;
            };
            // Prune cyclic back-edges so the kernel subshape walk over the
            // reported parents terminates on an adversarial hierarchy.
            if is_cyclic_parent_edge(cx, child_id, parent_class)? {
                continue;
            }
            out.push(shape_value(
                Symbol::qualified("shape-class-parent", parent_class.symbol().to_string()),
                std::sync::Arc::new(ClassShape::new(parent_class.symbol())),
            ));
        }
        Ok(out)
    }

    fn is_subshape_of(&self, cx: &mut Cx, parent: &dyn Shape) -> Result<Option<bool>> {
        let Some(parent) = parent.as_any().downcast_ref::<Self>() else {
            return Ok(None);
        };
        if self.symbol == parent.symbol {
            return Ok(Some(true));
        }
        let Some(child_class) = cx.registry().class_by_symbol(&self.symbol).cloned() else {
            return Ok(Some(false));
        };
        let Some(child_class) = child_class.object().as_class() else {
            return Ok(Some(false));
        };
        let Some(parent_class) = cx.registry().class_by_symbol(&parent.symbol).cloned() else {
            return Ok(Some(false));
        };
        class_is_subclass_of_guarded(cx, child_class, parent_class).map(Some)
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        if let Some(class) = value.object().as_class()
            && class_matches(cx, class, &self.symbol)?
        {
            return Ok(ShapeMatch::accept(MatchScore::exact(30)));
        }

        let class = value.object().class(cx)?;
        let Some(class) = class.object().as_class() else {
            return Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic("class-backed value", "value without class metadata"),
            ));
        };
        if class_matches(cx, class, &self.symbol)? {
            Ok(ShapeMatch::accept(MatchScore::exact(30)))
        } else {
            Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic(
                    format!("class {}", self.symbol),
                    format!("class {}", class.symbol()),
                ),
            ))
        }
    }

    fn check_expr(&self, cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        match expr {
            Expr::Symbol(symbol) if class_symbol_matches(cx, symbol, &self.symbol)? => {
                Ok(ShapeMatch::accept(MatchScore::exact(20)))
            }
            _ => {
                let object = match ObjectExpr::parse(expr) {
                    Some(object) => object,
                    None => {
                        return Ok(ShapeMatch::reject_with_diagnostic(
                            expected_shape_diagnostic(
                                format!("class {}", self.symbol),
                                expr_actual_label(expr),
                            ),
                        ));
                    }
                };
                if !class_symbol_matches(cx, &object.class, &self.symbol)? {
                    return Ok(ShapeMatch::reject_with_diagnostic(
                        expected_shape_diagnostic(
                            format!("class {}", self.symbol),
                            format!("class {}", object.class),
                        ),
                    ));
                }
                if let Some(class_value) = cx.registry().class_by_symbol(&self.symbol).cloned()
                    && let Some(class) = class_value.object().as_class()
                {
                    let shape = class.instance_shape(cx)?;
                    if let Some(shape) = shape.object().as_shape() {
                        // The instance shape can resolve back to this class
                        // (self-referential metadata); bound the re-entry so a
                        // cycle rejects rather than overflowing the stack.
                        let Some(_guard) = DepthGuard::enter() else {
                            return Ok(ShapeMatch::reject_with_diagnostic(
                                expected_shape_diagnostic(
                                    format!("class {} within shape recursion budget", self.symbol),
                                    "shape recursion budget exceeded",
                                ),
                            ));
                        };
                        let matched = shape.check_expr(cx, expr)?;
                        if matched.accepted {
                            return Ok(ShapeMatch::accept(MatchScore::exact(30)));
                        }
                        return Ok(matched);
                    }
                }
                Ok(ShapeMatch::accept(MatchScore::exact(25)))
            }
        }
    }

    fn describe(&self, _cx: &mut Cx) -> Result<ShapeDoc> {
        Ok(ShapeDoc::new(format!("class {}", self.symbol)))
    }
}

/// A shape that matches one exact expression form.
///
/// Accepts only expressions canonically equal to the stored form; a subshape of
/// the [`ExprKindShape`] for that form's kind.
///
/// # Examples
///
/// ```rust
/// # use std::sync::Arc;
/// use sim_kernel::{Cx, DefaultFactory, Expr, NoopEvalPolicy};
/// use sim_shape::{ExactExprShape, Shape};
///
/// let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
/// let shape = ExactExprShape::new(Expr::Bool(true));
/// assert!(shape.check_expr(&mut cx, &Expr::Bool(true)).unwrap().accepted);
/// assert!(!shape.check_expr(&mut cx, &Expr::Bool(false)).unwrap().accepted);
/// ```
pub struct ExactExprShape {
    expected: Expr,
}

impl ExactExprShape {
    /// Build a shape that matches only the given exact expression.
    pub fn new(expected: Expr) -> Self {
        Self { expected }
    }

    /// The exact expression this shape matches.
    pub fn expected(&self) -> &Expr {
        &self.expected
    }
}

impl Shape for ExactExprShape {
    fn parents(&self, _cx: &mut Cx) -> Result<Vec<ShapeRef>> {
        Ok(vec![shape_value(
            Symbol::qualified("shape-exact-parent", expr_kind_of(&self.expected).name()),
            std::sync::Arc::new(ExprKindShape::new(expr_kind_of(&self.expected))),
        )])
    }

    fn is_subshape_of(&self, _cx: &mut Cx, parent: &dyn Shape) -> Result<Option<bool>> {
        if let Some(parent) = parent.as_any().downcast_ref::<Self>() {
            return Ok(Some(self.expected.canonical_eq(parent.expected())));
        }
        if let Some(parent) = parent.as_any().downcast_ref::<ExprKindShape>() {
            return Ok(Some(parent.kind().matches(&self.expected)));
        }
        Ok(None)
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        let expr = value.object().as_expr(cx)?;
        self.check_expr(cx, &expr)
    }

    fn check_expr(&self, _cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        if self.expected.canonical_eq(expr) {
            Ok(ShapeMatch::accept(MatchScore::exact(20)))
        } else {
            Ok(ShapeMatch::reject_with_diagnostic(
                expected_shape_diagnostic("exact expression form", expr_actual_label(expr)),
            ))
        }
    }

    fn describe(&self, _cx: &mut Cx) -> Result<ShapeDoc> {
        Ok(ShapeDoc::new("exact expr").with_detail(format!("{:?}", self.expected)))
    }
}

fn class_matches(cx: &mut Cx, class: &dyn sim_kernel::Class, expected: &Symbol) -> Result<bool> {
    if class.symbol() == *expected {
        return Ok(true);
    }
    let Some(expected) = cx.registry().class_by_symbol(expected).cloned() else {
        return Ok(false);
    };
    class_is_subclass_of_guarded(cx, class, expected)
}

fn class_symbol_matches(cx: &mut Cx, actual: &Symbol, expected: &Symbol) -> Result<bool> {
    if actual == expected {
        return Ok(true);
    }
    let Some(actual) = cx.registry().class_by_symbol(actual).cloned() else {
        return Ok(false);
    };
    let Some(actual) = actual.object().as_class() else {
        return Ok(false);
    };
    class_matches(cx, actual, expected)
}

fn expr_kind_of(expr: &Expr) -> ExprKind {
    match expr {
        Expr::Nil => ExprKind::Nil,
        Expr::Bool(_) => ExprKind::Bool,
        Expr::Number(_) => ExprKind::Number,
        Expr::Symbol(_) => ExprKind::Symbol,
        Expr::Local(_) => ExprKind::Symbol,
        Expr::String(_) => ExprKind::String,
        Expr::Bytes(_) => ExprKind::Bytes,
        Expr::List(_) => ExprKind::List,
        Expr::Vector(_) => ExprKind::Vector,
        Expr::Map(_) => ExprKind::Map,
        Expr::Set(_) => ExprKind::Set,
        Expr::Call { .. } => ExprKind::Call,
        Expr::Infix { .. } => ExprKind::Infix,
        Expr::Prefix { .. } => ExprKind::Prefix,
        Expr::Postfix { .. } => ExprKind::Postfix,
        Expr::Block(_) => ExprKind::Block,
        Expr::Quote { .. } => ExprKind::Quote,
        Expr::Annotated { .. } => ExprKind::Annotated,
        Expr::Extension { .. } => ExprKind::Extension,
    }
}