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
//! Match-hook protocol and built-ins: the `MatchHook` trait, its context and
//! decision types, the hook object wrapper, and the standard hook
//! implementations (trace, score floor, accept/discard on diagnostics).

use std::sync::Arc;

use sim_citizen_derive::non_citizen;
use sim_kernel::{
    ClassRef, Cx, DefaultFactory, Error, Expr, Factory, NumberLiteral, Object, ObjectEncode,
    ObjectEncoding, Result, Symbol, Value,
};

use crate::{MatchScore, ShapeMatch};

/// Capability class for a match hook decision.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchHookKind {
    /// Observe and emit diagnostics without changing acceptance.
    Mark,
    /// Optionally turn a rejected match into an accepted one.
    Accept,
    /// Optionally turn an accepted match into a rejected one.
    Discard,
    /// Add annotations such as score deltas and diagnostics.
    Annotate,
}

/// Match target observed by a hook.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchHookTargetKind {
    /// Runtime value check.
    Value,
    /// Expression check.
    Expr,
}

/// Point in the wrapper algorithm where a hook runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchHookPhase {
    /// Before the inner shape is checked.
    BeforeInner,
    /// After the inner shape has produced a match.
    AfterInner,
}

/// Context supplied to every hook invocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MatchHookContext {
    /// Position of the hook in the wrapper registration order.
    pub hook_index: usize,
    /// Current execution phase.
    pub phase: MatchHookPhase,
    /// Whether the check is for a value or expression.
    pub target_kind: MatchHookTargetKind,
    /// Description name for the wrapped shape.
    pub shape_label: String,
}

/// Hook result interpreted by [`HookedShape`](crate::HookedShape).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MatchHookDecision {
    /// Do nothing.
    Pass,
    /// Emit a mark diagnostic.
    Mark {
        /// Mark text recorded as an info diagnostic.
        message: String,
    },
    /// Accept a currently rejected match.
    Accept {
        /// Explanation recorded for the repair.
        reason: String,
        /// Score assigned when the inner match left a reject score.
        score: MatchScore,
    },
    /// Reject a currently accepted match.
    Discard {
        /// Explanation recorded for the veto.
        reason: String,
    },
    /// Add a diagnostic and score delta.
    Annotate {
        /// Annotation text recorded as an info diagnostic.
        message: String,
        /// Amount added to the match score.
        score_delta: i32,
    },
}

/// Runtime hook contract for neutral shape match membranes.
pub trait MatchHook: Send + Sync {
    /// Stable symbol naming the hook.
    fn symbol(&self) -> Symbol;
    /// Decision class this hook may produce.
    fn kind(&self) -> MatchHookKind;
    /// Constructor encoding for pure, descriptor-backed built-in hooks.
    fn object_encoding(&self) -> Option<ObjectEncoding> {
        None
    }
    /// Run the hook for the supplied context and current match state.
    fn apply(
        &self,
        cx: &mut Cx,
        ctx: &MatchHookContext,
        current: Option<&ShapeMatch>,
    ) -> Result<MatchHookDecision>;
}

/// Opaque runtime object that carries a shape hook.
#[non_citizen(
    reason = "may wrap custom live hook code; built-in pure hook descriptors use shape/*Hook citizens",
    kind = "function"
)]
#[derive(Clone)]
pub struct MatchHookObject {
    hook: Arc<dyn MatchHook>,
}

impl MatchHookObject {
    /// Wrap a hook as an opaque runtime object.
    pub fn new(hook: Arc<dyn MatchHook>) -> Self {
        Self { hook }
    }

    /// Clone out the wrapped hook handle.
    pub fn hook(&self) -> Arc<dyn MatchHook> {
        self.hook.clone()
    }
}

impl Object for MatchHookObject {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok(format!(
            "#<shape-hook {} {}>",
            self.hook.symbol(),
            hook_kind_name(self.hook.kind())
        ))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl sim_kernel::ObjectCompat for MatchHookObject {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        if let Some(ObjectEncoding::Constructor { class, .. }) = self.hook.object_encoding()
            && let Some(value) = cx.registry().class_by_symbol(&class)
        {
            return Ok(value.clone());
        }
        cx.factory().nil()
    }

    fn as_expr(&self, _cx: &mut Cx) -> Result<Expr> {
        match self.object_encoding(_cx)? {
            ObjectEncoding::Constructor { class, args } => Ok(Expr::Call {
                operator: Box::new(Expr::Symbol(class)),
                args,
            }),
            _ => Err(Error::Eval(format!(
                "shape hook {} produced a non-constructor object encoding; only \
                 constructor encodings can render as an expression",
                self.hook.symbol()
            ))),
        }
    }

    fn as_object_encoder(&self) -> Option<&dyn ObjectEncode> {
        self.hook.object_encoding().is_some().then_some(self)
    }
}

impl ObjectEncode for MatchHookObject {
    fn object_encoding(&self, _cx: &mut Cx) -> Result<ObjectEncoding> {
        self.hook.object_encoding().ok_or_else(|| {
            Error::Eval(format!(
                "shape hook {} is not a pure descriptor citizen",
                self.hook.symbol()
            ))
        })
    }
}

/// Wrap a hook as an opaque runtime value.
pub fn hook_value(hook: Arc<dyn MatchHook>) -> Value {
    DefaultFactory
        .opaque(Arc::new(MatchHookObject::new(hook)))
        .expect("hook object should always be boxable")
}

/// Extract a hook from a runtime value produced by [`hook_value`].
pub fn hook_ref_arc(value: &Value) -> Result<Arc<dyn MatchHook>> {
    value
        .object()
        .downcast_ref::<MatchHookObject>()
        .map(MatchHookObject::hook)
        .ok_or(Error::TypeMismatch {
            expected: "shape-hook",
            found: "non-shape-hook",
        })
}

/// Mark hook that emits the wrapped shape label before and after matching.
#[derive(Clone, Default)]
pub struct TraceMarkHook;

impl MatchHook for TraceMarkHook {
    fn symbol(&self) -> Symbol {
        Symbol::qualified("shape", "trace-mark")
    }

    fn kind(&self) -> MatchHookKind {
        MatchHookKind::Mark
    }

    fn object_encoding(&self) -> Option<ObjectEncoding> {
        Some(hook_encoding(trace_mark_hook_class_symbol(), Vec::new()))
    }

    fn apply(
        &self,
        _cx: &mut Cx,
        ctx: &MatchHookContext,
        _current: Option<&ShapeMatch>,
    ) -> Result<MatchHookDecision> {
        Ok(MatchHookDecision::Mark {
            message: ctx.shape_label.clone(),
        })
    }
}

/// Annotate hook that raises accepted match scores to a minimum floor.
#[derive(Clone)]
pub struct ScoreFloorHook {
    floor: i32,
}

impl ScoreFloorHook {
    /// Build a score-floor hook that lifts accepted scores to `floor`.
    pub fn new(floor: i32) -> Self {
        Self { floor }
    }

    /// The minimum score this hook enforces.
    pub fn floor(&self) -> i32 {
        self.floor
    }
}

impl MatchHook for ScoreFloorHook {
    fn symbol(&self) -> Symbol {
        Symbol::qualified("shape", "score-floor")
    }

    fn kind(&self) -> MatchHookKind {
        MatchHookKind::Annotate
    }

    fn object_encoding(&self) -> Option<ObjectEncoding> {
        Some(hook_encoding(
            score_floor_hook_class_symbol(),
            vec![int_expr(self.floor)],
        ))
    }

    fn apply(
        &self,
        _cx: &mut Cx,
        _ctx: &MatchHookContext,
        current: Option<&ShapeMatch>,
    ) -> Result<MatchHookDecision> {
        let Some(current) = current else {
            return Ok(MatchHookDecision::Pass);
        };
        if current.accepted && current.score.value() < self.floor {
            return Ok(MatchHookDecision::Annotate {
                message: format!("score floor {}", self.floor),
                score_delta: self.floor - current.score.value(),
            });
        }
        Ok(MatchHookDecision::Pass)
    }
}

/// Accept hook that repairs quiet rejections with score 1.
#[derive(Clone, Default)]
pub struct AcceptOnNoDiagnosticsHook;

impl MatchHook for AcceptOnNoDiagnosticsHook {
    fn symbol(&self) -> Symbol {
        Symbol::qualified("shape", "accept-on-no-diagnostics")
    }

    fn kind(&self) -> MatchHookKind {
        MatchHookKind::Accept
    }

    fn object_encoding(&self) -> Option<ObjectEncoding> {
        Some(hook_encoding(
            accept_on_no_diagnostics_hook_class_symbol(),
            Vec::new(),
        ))
    }

    fn apply(
        &self,
        _cx: &mut Cx,
        _ctx: &MatchHookContext,
        current: Option<&ShapeMatch>,
    ) -> Result<MatchHookDecision> {
        let Some(current) = current else {
            return Ok(MatchHookDecision::Pass);
        };
        if !current.accepted && current.diagnostics.is_empty() {
            return Ok(MatchHookDecision::Accept {
                reason: "no diagnostics".to_owned(),
                score: MatchScore::exact(1),
            });
        }
        Ok(MatchHookDecision::Pass)
    }
}

/// Discard hook that rejects accepted matches containing a diagnostic prefix.
#[derive(Clone)]
pub struct DiscardOnDiagnosticPrefixHook {
    prefix: String,
}

impl DiscardOnDiagnosticPrefixHook {
    /// Build a discard hook that vetoes matches carrying `prefix` diagnostics.
    pub fn new(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
        }
    }

    /// The diagnostic-message prefix this hook watches for.
    pub fn prefix(&self) -> &str {
        &self.prefix
    }
}

impl MatchHook for DiscardOnDiagnosticPrefixHook {
    fn symbol(&self) -> Symbol {
        Symbol::qualified("shape", "discard-on-diagnostic-prefix")
    }

    fn kind(&self) -> MatchHookKind {
        MatchHookKind::Discard
    }

    fn object_encoding(&self) -> Option<ObjectEncoding> {
        Some(hook_encoding(
            discard_on_diagnostic_prefix_hook_class_symbol(),
            vec![Expr::String(self.prefix.clone())],
        ))
    }

    fn apply(
        &self,
        _cx: &mut Cx,
        _ctx: &MatchHookContext,
        current: Option<&ShapeMatch>,
    ) -> Result<MatchHookDecision> {
        let Some(current) = current else {
            return Ok(MatchHookDecision::Pass);
        };
        if current.accepted
            && current
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.message.starts_with(&self.prefix))
        {
            return Ok(MatchHookDecision::Discard {
                reason: self.prefix.clone(),
            });
        }
        Ok(MatchHookDecision::Pass)
    }
}

pub(crate) fn hook_kind_name(kind: MatchHookKind) -> &'static str {
    match kind {
        MatchHookKind::Mark => "mark",
        MatchHookKind::Accept => "accept",
        MatchHookKind::Discard => "discard",
        MatchHookKind::Annotate => "annotate",
    }
}

/// Class symbol for the [`TraceMarkHook`] citizen (`shape/TraceMarkHook`).
pub fn trace_mark_hook_class_symbol() -> Symbol {
    Symbol::qualified("shape", "TraceMarkHook")
}

/// Class symbol for the [`ScoreFloorHook`] citizen (`shape/ScoreFloorHook`).
pub fn score_floor_hook_class_symbol() -> Symbol {
    Symbol::qualified("shape", "ScoreFloorHook")
}

/// Class symbol for the [`AcceptOnNoDiagnosticsHook`] citizen
/// (`shape/AcceptOnNoDiagnosticsHook`).
pub fn accept_on_no_diagnostics_hook_class_symbol() -> Symbol {
    Symbol::qualified("shape", "AcceptOnNoDiagnosticsHook")
}

/// Class symbol for the [`DiscardOnDiagnosticPrefixHook`] citizen
/// (`shape/DiscardOnDiagnosticPrefixHook`).
pub fn discard_on_diagnostic_prefix_hook_class_symbol() -> Symbol {
    Symbol::qualified("shape", "DiscardOnDiagnosticPrefixHook")
}

fn hook_encoding(class: Symbol, fields: Vec<Expr>) -> ObjectEncoding {
    let mut args = Vec::with_capacity(fields.len() + 1);
    args.push(Expr::Symbol(Symbol::new("v1")));
    args.extend(fields);
    ObjectEncoding::Constructor { class, args }
}

fn int_expr(value: i32) -> Expr {
    Expr::Number(NumberLiteral {
        domain: Symbol::qualified("citizen", "int"),
        canonical: value.to_string(),
    })
}