sim-shape 0.1.2

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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Collection shapes: `TableShape` with its per-field specs and extra-field
//! policy, and `RepeatShape` for matching repeated occurrences of a shape.

use std::sync::Arc;

use sim_kernel::{
    Cx, Diagnostic, Expr, Result, Symbol, Table, Value, force_list_to_vec, shape_is_subshape_of,
};

use crate::{
    algebra::{capture_symbol, number_expr, number_value, symbol_list_expr, symbol_list_value},
    base::{Bindings, MatchScore, Shape, ShapeDoc, ShapeMatch},
    duplicate_keys::reject_duplicate_symbol_keys,
};

/// Shape for table values or map expressions with named field constraints.
///
/// Required fields must be present and accepted by their field shapes. Extra
/// fields are controlled by [`TableExtraPolicy`].
///
/// ```rust
/// # use std::sync::Arc;
/// # use sim_kernel::{Cx, DefaultFactory, Expr, NoopEvalPolicy, Symbol};
/// # use sim_shape::{ExprKind, ExprKindShape, Shape, TableShape};
/// # let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
/// let shape = TableShape::single(
///     Symbol::new("ok"),
///     Arc::new(ExprKindShape::new(ExprKind::Bool)),
/// );
/// let expr = Expr::Map(vec![(Expr::Symbol(Symbol::new("ok")), Expr::Bool(true))]);
///
/// assert!(shape.check_expr(&mut cx, &expr).unwrap().accepted);
/// ```
#[derive(Clone)]
pub struct TableShape {
    fields: Vec<TableFieldSpec>,
    extra: TableExtraPolicy,
}

/// One field constraint inside a [`TableShape`].
#[derive(Clone)]
pub struct TableFieldSpec {
    /// Symbol key to look up in the table or map expression.
    pub key: Symbol,
    /// Shape that must accept the field value or expression.
    pub shape: Arc<dyn Shape>,
    /// Whether the field must be present.
    pub required: bool,
}

/// Policy for keys not listed in a [`TableShape`].
#[derive(Clone)]
pub enum TableExtraPolicy {
    /// Accept extra keys without checking their values.
    Allow,
    /// Reject any extra key.
    Reject,
    /// Check each extra value with the supplied shape.
    Shape(Arc<dyn Shape>),
}

impl TableShape {
    /// Build a table shape requiring a single named field, allowing extras.
    pub fn single(key: Symbol, shape: Arc<dyn Shape>) -> Self {
        Self::new(
            vec![TableFieldSpec {
                key,
                shape,
                required: true,
            }],
            TableExtraPolicy::Allow,
        )
    }

    /// Build a table shape from explicit field specs and an extra-key policy.
    pub fn new(fields: Vec<TableFieldSpec>, extra: TableExtraPolicy) -> Self {
        Self { fields, extra }
    }

    /// Return the field constraints in declaration order.
    pub fn fields(&self) -> &[TableFieldSpec] {
        &self.fields
    }

    /// Return the policy applied to keys not listed in the field specs.
    pub fn extra(&self) -> &TableExtraPolicy {
        &self.extra
    }
}

impl Shape for TableShape {
    fn is_total(&self) -> bool {
        self.fields.is_empty() && matches!(self.extra, TableExtraPolicy::Allow)
    }

    fn is_effectful(&self) -> bool {
        self.fields.iter().any(|field| field.shape.is_effectful())
            || matches!(&self.extra, TableExtraPolicy::Shape(shape) if shape.is_effectful())
    }

    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);
        };

        for parent_field in parent.fields() {
            if !parent_field_compatible(cx, self, parent_field)? {
                return Ok(None);
            }
        }

        for child_field in self.fields() {
            if parent
                .fields()
                .iter()
                .any(|parent_field| parent_field.key == child_field.key)
            {
                continue;
            }
            if !field_accepted_by_parent(cx, child_field, parent)? {
                return Ok(None);
            }
        }

        if extra_policy_at_least_as_strict(cx, &self.extra, &parent.extra)? {
            Ok(Some(true))
        } else {
            Ok(None)
        }
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        if let Some(table) = value.object().as_table_impl() {
            return self.check_table_value(cx, table);
        }

        let table_value = value.object().as_table(cx)?;
        let Some(table) = table_value.object().as_table_impl() else {
            return Ok(ShapeMatch::reject("shape-table: expected table"));
        };
        self.check_table_value(cx, table)
    }

    fn check_expr(&self, cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        let Expr::Map(entries) = expr else {
            return Ok(ShapeMatch::reject("shape-table: expected map expression"));
        };

        let mut parsed = Vec::with_capacity(entries.len());
        for (key, value) in entries {
            let Expr::Symbol(key) = key else {
                return Ok(ShapeMatch::reject("shape-table: map key must be symbol"));
            };
            parsed.push((key.clone(), value.clone()));
        }
        self.check_map_expr(cx, &parsed)
    }

    fn describe(&self, cx: &mut Cx) -> Result<ShapeDoc> {
        let mut doc = ShapeDoc::new("table shape");
        for field in &self.fields {
            doc = doc.with_detail(format!("{}: {}", field.key, field.shape.describe(cx)?.name));
        }
        Ok(doc)
    }
}

/// Shape for homogeneous list-like values and collection expressions.
///
/// `RepeatShape` checks every item with the body shape and can enforce minimum
/// and maximum item counts.
///
/// ```rust
/// # use std::sync::Arc;
/// # use sim_kernel::{Cx, DefaultFactory, Expr, NoopEvalPolicy};
/// # use sim_shape::{ExprKind, ExprKindShape, RepeatShape, Shape};
/// # let mut cx = Cx::new(Arc::new(NoopEvalPolicy), Arc::new(DefaultFactory));
/// let shape = RepeatShape::with_bounds(
///     Arc::new(ExprKindShape::new(ExprKind::Bool)),
///     1,
///     Some(2),
/// );
///
/// assert!(shape
///     .check_expr(&mut cx, &Expr::Vector(vec![Expr::Bool(true)]))
///     .unwrap()
///     .accepted);
/// ```
pub struct RepeatShape {
    body: Arc<dyn Shape>,
    min: usize,
    max: Option<usize>,
}

impl RepeatShape {
    /// Build an unbounded repeat over the given body shape.
    pub fn new(body: Arc<dyn Shape>) -> Self {
        Self::with_bounds(body, 0, None)
    }

    /// Build a repeat with a minimum and optional maximum item count.
    pub fn with_bounds(body: Arc<dyn Shape>, min: usize, max: Option<usize>) -> Self {
        Self { body, min, max }
    }

    /// Return the shape applied to each item.
    pub fn body(&self) -> &Arc<dyn Shape> {
        &self.body
    }

    /// Return the minimum required item count.
    pub fn min(&self) -> usize {
        self.min
    }

    /// Return the maximum allowed item count, if bounded.
    pub fn max(&self) -> Option<usize> {
        self.max
    }
}

impl Shape for RepeatShape {
    fn is_effectful(&self) -> bool {
        self.body.is_effectful()
    }

    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.min < parent.min {
            return Ok(None);
        }
        if !max_at_most(self.max, parent.max) {
            return Ok(None);
        }
        shape_is_subshape_of(cx, self.body.as_ref(), parent.body.as_ref()).map(Some)
    }

    fn check_value(&self, cx: &mut Cx, value: Value) -> Result<ShapeMatch> {
        let Some(list) = value.object().as_list() else {
            let expr = value.object().as_expr(cx)?;
            return self.check_expr(cx, &expr);
        };
        let items = force_list_to_vec(cx, list, "shape-repeat")?;
        self.check_values(cx, &items)
    }

    fn check_expr(&self, cx: &mut Cx, expr: &Expr) -> Result<ShapeMatch> {
        let items = match expr {
            Expr::List(items) | Expr::Vector(items) | Expr::Set(items) => items,
            _ => return Ok(ShapeMatch::reject("shape-repeat: expected list expression")),
        };
        let mut out = ShapeMatch::accept(MatchScore::exact(20));
        for item in items {
            let mut matched = self.body.check_expr(cx, item)?;
            if !matched.accepted {
                matched
                    .diagnostics
                    .insert(0, Diagnostic::error("shape-repeat: item rejected"));
                return Ok(matched);
            }
            out.captures.extend(matched.captures);
            out.score += matched.score;
        }
        self.finish_expr(out, items.len())
    }

    fn describe(&self, cx: &mut Cx) -> Result<ShapeDoc> {
        let max = self
            .max
            .map(|max| max.to_string())
            .unwrap_or_else(|| "unbounded".to_owned());
        Ok(ShapeDoc::new("repeat shape")
            .with_detail(self.body.describe(cx)?.name)
            .with_detail(format!("min {}", self.min))
            .with_detail(format!("max {max}")))
    }
}

impl TableShape {
    fn check_table_value(&self, cx: &mut Cx, table: &dyn Table) -> Result<ShapeMatch> {
        let entries = table.entries(cx)?;
        self.check_value_entries(cx, &entries)
    }

    fn check_value_entries(&self, cx: &mut Cx, entries: &[(Symbol, Value)]) -> Result<ShapeMatch> {
        match reject_duplicate_symbol_keys(entries, "shape-table") {
            Ok(()) => {}
            Err(sim_kernel::Error::Eval(message)) => return Ok(ShapeMatch::reject(message)),
            Err(err) => return Err(err),
        }

        let mut out = ShapeMatch::accept(MatchScore::exact(20));
        let mut matched_keys = Vec::new();
        let mut missing_keys = Vec::new();

        for field in &self.fields {
            let Some((_, value)) = entries.iter().find(|(key, _)| *key == field.key) else {
                if field.required {
                    missing_keys.push(field.key.clone());
                }
                continue;
            };
            let mut matched = field.shape.check_value(cx, value.clone())?;
            if !matched.accepted {
                matched
                    .diagnostics
                    .insert(0, Diagnostic::error("shape-table: field rejected"));
                return Ok(matched);
            }
            out.captures.extend(matched.captures);
            out.score += matched.score;
            matched_keys.push(field.key.clone());
        }

        if !missing_keys.is_empty() {
            let mut captures = Bindings::new();
            captures.bind_value(
                capture_symbol("missing-keys"),
                symbol_list_value(cx, &missing_keys)?,
            );
            return Ok(ShapeMatch {
                accepted: false,
                captures,
                score: MatchScore::reject(),
                diagnostics: vec![Diagnostic::error("shape-table: missing keys")],
            });
        }

        let field_keys = self
            .fields
            .iter()
            .map(|field| field.key.clone())
            .collect::<Vec<_>>();
        for (key, value) in entries {
            if field_keys.contains(key) {
                continue;
            }
            match &self.extra {
                TableExtraPolicy::Allow => {}
                TableExtraPolicy::Reject => {
                    return Ok(ShapeMatch::reject(format!("shape-table: extra key {key}")));
                }
                TableExtraPolicy::Shape(shape) => {
                    let mut matched = shape.check_value(cx, value.clone())?;
                    if !matched.accepted {
                        matched
                            .diagnostics
                            .insert(0, Diagnostic::error("shape-table: extra value rejected"));
                        return Ok(matched);
                    }
                    out.captures.extend(matched.captures);
                    out.score += matched.score;
                }
            }
        }

        out.captures.bind_value(
            capture_symbol("matched-keys"),
            symbol_list_value(cx, &matched_keys)?,
        );
        Ok(out)
    }

    fn check_map_expr(&self, cx: &mut Cx, entries: &[(Symbol, Expr)]) -> Result<ShapeMatch> {
        match reject_duplicate_symbol_keys(entries, "shape-table") {
            Ok(()) => {}
            Err(sim_kernel::Error::Eval(message)) => return Ok(ShapeMatch::reject(message)),
            Err(err) => return Err(err),
        }

        let mut out = ShapeMatch::accept(MatchScore::exact(20));
        let mut matched_keys = Vec::new();
        let mut missing_keys = Vec::new();

        for field in &self.fields {
            let Some((_, value)) = entries.iter().find(|(key, _)| *key == field.key) else {
                if field.required {
                    missing_keys.push(field.key.clone());
                }
                continue;
            };
            let mut matched = field.shape.check_expr(cx, value)?;
            if !matched.accepted {
                matched
                    .diagnostics
                    .insert(0, Diagnostic::error("shape-table: field rejected"));
                return Ok(matched);
            }
            out.captures.extend(matched.captures);
            out.score += matched.score;
            matched_keys.push(field.key.clone());
        }

        if !missing_keys.is_empty() {
            let mut captures = Bindings::new();
            captures.bind_expr(
                capture_symbol("missing-keys"),
                symbol_list_expr(&missing_keys),
            );
            return Ok(ShapeMatch {
                accepted: false,
                captures,
                score: MatchScore::reject(),
                diagnostics: vec![Diagnostic::error("shape-table: missing keys")],
            });
        }

        let field_keys = self
            .fields
            .iter()
            .map(|field| field.key.clone())
            .collect::<Vec<_>>();
        for (key, value) in entries {
            if field_keys.contains(key) {
                continue;
            }
            match &self.extra {
                TableExtraPolicy::Allow => {}
                TableExtraPolicy::Reject => {
                    return Ok(ShapeMatch::reject(format!("shape-table: extra key {key}")));
                }
                TableExtraPolicy::Shape(shape) => {
                    let mut matched = shape.check_expr(cx, value)?;
                    if !matched.accepted {
                        matched
                            .diagnostics
                            .insert(0, Diagnostic::error("shape-table: extra value rejected"));
                        return Ok(matched);
                    }
                    out.captures.extend(matched.captures);
                    out.score += matched.score;
                }
            }
        }

        out.captures.bind_expr(
            capture_symbol("matched-keys"),
            symbol_list_expr(&matched_keys),
        );
        Ok(out)
    }
}

impl RepeatShape {
    fn check_values(&self, cx: &mut Cx, items: &[Value]) -> Result<ShapeMatch> {
        let mut out = ShapeMatch::accept(MatchScore::exact(20));
        for item in items {
            let mut matched = self.body.check_value(cx, item.clone())?;
            if !matched.accepted {
                matched
                    .diagnostics
                    .insert(0, Diagnostic::error("shape-repeat: item rejected"));
                return Ok(matched);
            }
            out.captures.extend(matched.captures);
            out.score += matched.score;
        }
        self.finish_value(cx, out, items.len())
    }

    fn finish_value(&self, cx: &mut Cx, mut out: ShapeMatch, count: usize) -> Result<ShapeMatch> {
        if count < self.min {
            return Ok(ShapeMatch::reject("shape-repeat: too few items"));
        }
        if matches!(self.max, Some(max) if count > max) {
            return Ok(ShapeMatch::reject("shape-repeat: too many items"));
        }
        out.captures
            .bind_value(capture_symbol("repeat-count"), number_value(cx, count)?);
        Ok(out)
    }

    fn finish_expr(&self, mut out: ShapeMatch, count: usize) -> Result<ShapeMatch> {
        if count < self.min {
            return Ok(ShapeMatch::reject("shape-repeat: too few items"));
        }
        if matches!(self.max, Some(max) if count > max) {
            return Ok(ShapeMatch::reject("shape-repeat: too many items"));
        }
        out.captures
            .bind_expr(capture_symbol("repeat-count"), number_expr(count));
        Ok(out)
    }
}

fn extra_policy_at_least_as_strict(
    cx: &mut Cx,
    child: &TableExtraPolicy,
    parent: &TableExtraPolicy,
) -> Result<bool> {
    Ok(match (child, parent) {
        (_, TableExtraPolicy::Allow) => true,
        (TableExtraPolicy::Reject, TableExtraPolicy::Reject | TableExtraPolicy::Shape(_)) => true,
        (TableExtraPolicy::Shape(child), TableExtraPolicy::Shape(parent)) => {
            shape_is_subshape_of(cx, child.as_ref(), parent.as_ref())?
        }
        (TableExtraPolicy::Allow, TableExtraPolicy::Reject | TableExtraPolicy::Shape(_)) => false,
        (TableExtraPolicy::Shape(_), TableExtraPolicy::Reject) => false,
    })
}

fn parent_field_compatible(
    cx: &mut Cx,
    child: &TableShape,
    parent_field: &TableFieldSpec,
) -> Result<bool> {
    if let Some(child_field) = child
        .fields()
        .iter()
        .find(|candidate| candidate.key == parent_field.key)
    {
        if parent_field.required && !child_field.required {
            return Ok(false);
        }
        return shape_is_subshape_of(cx, child_field.shape.as_ref(), parent_field.shape.as_ref());
    }

    if parent_field.required {
        return Ok(false);
    }

    match child.extra() {
        TableExtraPolicy::Reject => Ok(true),
        // Unchecked extras can hit this optional key with values the parent field rejects.
        TableExtraPolicy::Allow => Ok(false),
        TableExtraPolicy::Shape(shape) => {
            shape_is_subshape_of(cx, shape.as_ref(), parent_field.shape.as_ref())
        }
    }
}

fn field_accepted_by_parent(
    cx: &mut Cx,
    child_field: &TableFieldSpec,
    parent: &TableShape,
) -> Result<bool> {
    if let Some(parent_field) = parent
        .fields()
        .iter()
        .find(|candidate| candidate.key == child_field.key)
    {
        return shape_is_subshape_of(cx, child_field.shape.as_ref(), parent_field.shape.as_ref());
    }

    match parent.extra() {
        TableExtraPolicy::Allow => Ok(true),
        TableExtraPolicy::Reject => Ok(false),
        TableExtraPolicy::Shape(extra) => {
            shape_is_subshape_of(cx, child_field.shape.as_ref(), extra.as_ref())
        }
    }
}

fn max_at_most(child: Option<usize>, parent: Option<usize>) -> bool {
    match (child, parent) {
        (_, None) => true,
        (Some(child), Some(parent)) => child <= parent,
        (None, Some(_)) => false,
    }
}