harn-kernel 0.10.53

Portable compiler, program artifact, and deterministic execution kernel for Harn
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
//! Runtime type-contract matching shared by native and portable execution.
//!
//! The parser owns `TypeExpr`; this module owns how those expressions match
//! runtime values. Runtimes project their value representation through the
//! small `TypeContractValue` interface instead of maintaining another type
//! dispatch table.

use harn_parser::builtin_signatures::{BuiltinSignature, Ty};
use harn_parser::TypeExpr;

use crate::DataValue;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeTypeKind {
    Int,
    Float,
    Decimal,
    String,
    Bytes,
    Bool,
    Nil,
    List,
    Dict,
    Closure,
    Duration,
    Enum,
    Struct,
    TaskHandle,
    Channel,
    Atomic,
    Rng,
    SyncPermit,
    Resource,
    ResourceGuard,
    McpClient,
    VerdictReceipt,
    Set,
    Generator,
    Stream,
    Range,
    Iter,
    Pair,
    Harness,
}

pub trait TypeContractValue: Sized {
    fn runtime_type_kind(&self) -> RuntimeTypeKind;
    fn list_items(&self) -> Option<&[Self]> {
        None
    }
    fn record_field(&self, _name: &str) -> Option<&Self> {
        None
    }
    /// Apply `predicate` to every value in a dictionary-like value.
    ///
    /// Returning `None` distinguishes a value that is not enumerable from an
    /// empty dictionary. This keeps homogeneous `dict<K, V>` checks exact
    /// without forcing either runtime to allocate a projection vector.
    fn record_values_match(&self, _predicate: &mut dyn FnMut(&Self) -> bool) -> Option<bool> {
        None
    }
    fn string_literal(&self) -> Option<&str> {
        None
    }
    fn int_literal(&self) -> Option<i64> {
        None
    }
    fn nominal_type_name(&self) -> Option<&str> {
        None
    }
}

pub fn matches_type<V: TypeContractValue>(
    value: &V,
    expected: &TypeExpr,
    type_params: &[String],
    nominal_type_names: &[String],
) -> bool {
    use RuntimeTypeKind as Kind;
    match expected {
        TypeExpr::Named(name) => match name.as_str() {
            _ if type_params.iter().any(|param| param == name) => true,
            "any" | "unknown" => true,
            "int" => value.runtime_type_kind() == Kind::Int,
            "float" | "number" => matches!(value.runtime_type_kind(), Kind::Float | Kind::Int),
            "decimal" => value.runtime_type_kind() == Kind::Decimal,
            "string" => value.runtime_type_kind() == Kind::String,
            "bool" => value.runtime_type_kind() == Kind::Bool,
            "nil" => value.runtime_type_kind() == Kind::Nil,
            "list" => value.runtime_type_kind() == Kind::List,
            "dict" | "record" => value.runtime_type_kind() == Kind::Dict,
            "bytes" => value.runtime_type_kind() == Kind::Bytes,
            "duration" => value.runtime_type_kind() == Kind::Duration,
            "set" => value.runtime_type_kind() == Kind::Set,
            "range" => value.runtime_type_kind() == Kind::Range,
            "iter" => value.runtime_type_kind() == Kind::Iter,
            "generator" | "Generator" => value.runtime_type_kind() == Kind::Generator,
            "stream" | "Stream" => value.runtime_type_kind() == Kind::Stream,
            "channel" => value.runtime_type_kind() == Kind::Channel,
            "task_handle" => value.runtime_type_kind() == Kind::TaskHandle,
            "atomic" => value.runtime_type_kind() == Kind::Atomic,
            "rng" => value.runtime_type_kind() == Kind::Rng,
            "sync_permit" => value.runtime_type_kind() == Kind::SyncPermit,
            "resource" => value.runtime_type_kind() == Kind::Resource,
            "resource_guard" => value.runtime_type_kind() == Kind::ResourceGuard,
            "mcp_client" => value.runtime_type_kind() == Kind::McpClient,
            "verdict_receipt" => value.runtime_type_kind() == Kind::VerdictReceipt,
            "pair" => value.runtime_type_kind() == Kind::Pair,
            "enum" => value.runtime_type_kind() == Kind::Enum,
            "struct" => value.runtime_type_kind() == Kind::Struct,
            "closure" => value.runtime_type_kind() == Kind::Closure,
            _ if !nominal_type_names.iter().any(|ty| ty == name) => true,
            _ => value
                .nominal_type_name()
                .is_some_and(|actual| actual == name),
        },
        TypeExpr::Union(members) => members
            .iter()
            .any(|member| matches_type(value, member, type_params, nominal_type_names)),
        TypeExpr::Intersection(members) => members
            .iter()
            .all(|member| matches_type(value, member, type_params, nominal_type_names)),
        TypeExpr::List(inner) => value.list_items().is_some_and(|items| {
            items
                .iter()
                .all(|item| matches_type(item, inner, type_params, nominal_type_names))
        }),
        TypeExpr::Tuple(elements) => value.list_items().is_some_and(|items| {
            items.len() == elements.len()
                && items.iter().zip(elements).all(|(item, element)| {
                    matches_type(item, element, type_params, nominal_type_names)
                })
        }),
        TypeExpr::DictType(_, value_type) => {
            value.runtime_type_kind() == Kind::Dict
                && record_values_match(value, value_type, type_params, nominal_type_names)
        }
        TypeExpr::Iter(_) | TypeExpr::Generator(_) | TypeExpr::Stream(_) => matches!(
            value.runtime_type_kind(),
            Kind::List | Kind::Generator | Kind::Stream
        ),
        TypeExpr::Shape(fields) | TypeExpr::OpenShape { fields, .. } => {
            matches!(value.runtime_type_kind(), Kind::Dict | Kind::Struct)
                && fields
                    .iter()
                    .all(|field| match value.record_field(&field.name) {
                        Some(field_value)
                            if field.optional && field_value.runtime_type_kind() == Kind::Nil =>
                        {
                            true
                        }
                        Some(field_value) => matches_type(
                            field_value,
                            &field.type_expr,
                            type_params,
                            nominal_type_names,
                        ),
                        None => field.optional,
                    })
        }
        TypeExpr::Applied { name, args } => match (name.as_str(), args.as_slice()) {
            ("list" | "List", [inner]) => value.list_items().is_some_and(|items| {
                items
                    .iter()
                    .all(|item| matches_type(item, inner, type_params, nominal_type_names))
            }),
            ("dict" | "Dict", [_, value_type]) => {
                value.runtime_type_kind() == Kind::Dict
                    && record_values_match(value, value_type, type_params, nominal_type_names)
            }
            ("Option", [inner]) => {
                value.runtime_type_kind() == Kind::Nil
                    || matches_type(value, inner, type_params, nominal_type_names)
            }
            _ => true,
        },
        TypeExpr::FnType { .. } => value.runtime_type_kind() == Kind::Closure,
        TypeExpr::Never => false,
        TypeExpr::LitString(expected) => value.string_literal() == Some(expected),
        TypeExpr::LitInt(expected) => value.int_literal() == Some(*expected),
        TypeExpr::Owned(inner) => matches_type(value, inner, type_params, nominal_type_names),
    }
}

/// Match a value against the canonical const-friendly type used by builtin
/// and capability manifests.
///
/// Conversion is owned by `harn-parser`; runtimes therefore do not maintain a
/// second interpretation of `Ty` alongside the source-language `TypeExpr`.
pub fn matches_manifest_type<V: TypeContractValue>(value: &V, expected: &Ty) -> bool {
    let expected = harn_parser::builtin_signatures::ty_to_type_expr(expected);
    matches_type(value, &expected, &[], &[])
}

/// Match a runtime value against the closed schema subset emitted by the
/// canonical compiler for typed default parameters.
///
/// This is intentionally narrower than Harn's user-facing schema language:
/// it owns only the compiler-generated `type`, `properties`, `required`,
/// `items`, `additional_properties`, `union`, `all_of`, `enum`, and `const`
/// vocabulary. Both native and portable runtimes can project values through
/// [`TypeContractValue`] without growing a second source-type dispatcher.
pub fn matches_compiler_schema<V: TypeContractValue>(value: &V, schema: &DataValue) -> bool {
    matches_compiler_schema_inner(value, schema, 0)
}

fn matches_compiler_schema_inner<V: TypeContractValue>(
    value: &V,
    schema: &DataValue,
    depth: usize,
) -> bool {
    const MAX_SCHEMA_DEPTH: usize = 256;
    if depth >= MAX_SCHEMA_DEPTH {
        return false;
    }
    let DataValue::Record(fields) = schema else {
        return false;
    };

    if let Some(DataValue::List(branches)) = fields.get("union") {
        return branches
            .iter()
            .any(|branch| matches_compiler_schema_inner(value, branch, depth + 1));
    }
    if let Some(DataValue::List(branches)) = fields.get("all_of") {
        return branches
            .iter()
            .all(|branch| matches_compiler_schema_inner(value, branch, depth + 1));
    }
    if let Some(DataValue::String(expected)) = fields.get("type") {
        use RuntimeTypeKind as Kind;
        let matches = match expected.as_str() {
            "int" => value.runtime_type_kind() == Kind::Int,
            "float" => matches!(value.runtime_type_kind(), Kind::Int | Kind::Float),
            "string" => value.runtime_type_kind() == Kind::String,
            "bool" => value.runtime_type_kind() == Kind::Bool,
            "nil" => value.runtime_type_kind() == Kind::Nil,
            "list" => value.runtime_type_kind() == Kind::List,
            "dict" => value.runtime_type_kind() == Kind::Dict,
            "bytes" => value.runtime_type_kind() == Kind::Bytes,
            "closure" => value.runtime_type_kind() == Kind::Closure,
            // Sets cannot cross the portable data boundary.
            "set" => value.runtime_type_kind() == Kind::Set,
            _ => false,
        };
        if !matches {
            return false;
        }
    }
    if let Some(DataValue::List(allowed)) = fields.get("enum") {
        if !allowed
            .iter()
            .any(|candidate| literal_matches(value, candidate))
        {
            return false;
        }
    }
    if let Some(expected) = fields.get("const") {
        if !literal_matches(value, expected) {
            return false;
        }
    }
    if let Some(DataValue::List(required)) = fields.get("required") {
        if !required.iter().all(|name| match name {
            DataValue::String(name) => value.record_field(name).is_some(),
            _ => false,
        }) {
            return false;
        }
    }
    if let Some(DataValue::Record(properties)) = fields.get("properties") {
        for (name, child_schema) in properties {
            if let Some(child) = value.record_field(name) {
                if !matches_compiler_schema_inner(child, child_schema, depth + 1) {
                    return false;
                }
            }
        }
    }
    if let Some(additional) = fields.get("additional_properties") {
        if value.record_values_match(&mut |child| {
            matches_compiler_schema_inner(child, additional, depth + 1)
        }) != Some(true)
        {
            return false;
        }
    }
    true
}

fn literal_matches<V: TypeContractValue>(value: &V, expected: &DataValue) -> bool {
    match expected {
        DataValue::String(expected) => value.string_literal() == Some(expected),
        DataValue::Int(expected) => value.int_literal() == Some(*expected),
        DataValue::Nil => value.runtime_type_kind() == RuntimeTypeKind::Nil,
        _ => false,
    }
}

/// Return whether a canonical manifest type can cross the portable
/// [`DataValue`] boundary without losing information or type precision.
///
/// The capability registry describes both JSON-shaped host calls and native
/// runtime objects such as channels, streams, closures, schemas, and generic
/// results. Portable execution must reject the latter structurally instead of
/// collapsing them to `any` and pretending the contract is enforceable.
pub fn manifest_type_is_portable(expected: &Ty) -> bool {
    match expected {
        Ty::Any | Ty::LitInt(_) | Ty::LitString(_) => true,
        Ty::Named(name) => matches!(
            *name,
            "any"
                | "unknown"
                | "nil"
                | "bool"
                | "int"
                | "float"
                | "number"
                | "string"
                | "bytes"
                | "list"
                | "dict"
                | "record"
        ),
        Ty::Optional(inner) => manifest_type_is_portable(inner),
        Ty::Apply("list" | "List", [inner]) | Ty::Apply("Option", [inner]) => {
            manifest_type_is_portable(inner)
        }
        Ty::Apply("dict" | "Dict", [key, value]) => {
            manifest_dict_key_is_portable(key) && manifest_type_is_portable(value)
        }
        Ty::Union(members) => !members.is_empty() && members.iter().all(manifest_type_is_portable),
        Ty::Shape(fields) => fields
            .iter()
            .all(|field| manifest_type_is_portable(&field.ty)),
        Ty::Generic(_) | Ty::Apply(_, _) | Ty::Fn(_, _) | Ty::SchemaOf(_) | Ty::Never => false,
    }
}

fn manifest_dict_key_is_portable(expected: &Ty) -> bool {
    match expected {
        Ty::Any | Ty::Named("any" | "unknown" | "string") | Ty::LitString(_) => true,
        Ty::Union(members) => {
            !members.is_empty() && members.iter().all(manifest_dict_key_is_portable)
        }
        _ => false,
    }
}

/// Return whether every parameter and successful return value in a canonical
/// capability signature is representable by the portable value contract.
pub fn manifest_signature_is_portable(signature: &BuiltinSignature) -> bool {
    signature
        .params
        .iter()
        .all(|parameter| manifest_type_is_portable(&parameter.ty))
        && manifest_type_is_portable(&signature.returns)
}

fn record_values_match<V: TypeContractValue>(
    value: &V,
    value_type: &TypeExpr,
    type_params: &[String],
    nominal_type_names: &[String],
) -> bool {
    value
        .record_values_match(&mut |field| {
            matches_type(field, value_type, type_params, nominal_type_names)
        })
        .unwrap_or(false)
}

impl TypeContractValue for DataValue {
    fn runtime_type_kind(&self) -> RuntimeTypeKind {
        match self {
            Self::Nil => RuntimeTypeKind::Nil,
            Self::Bool(_) => RuntimeTypeKind::Bool,
            Self::Int(_) => RuntimeTypeKind::Int,
            Self::Float(_) => RuntimeTypeKind::Float,
            Self::String(_) => RuntimeTypeKind::String,
            Self::Bytes(_) => RuntimeTypeKind::Bytes,
            Self::List(_) => RuntimeTypeKind::List,
            Self::Record(_) => RuntimeTypeKind::Dict,
        }
    }

    fn list_items(&self) -> Option<&[Self]> {
        match self {
            Self::List(items) => Some(items),
            _ => None,
        }
    }

    fn record_field(&self, name: &str) -> Option<&Self> {
        match self {
            Self::Record(fields) => fields.get(name),
            _ => None,
        }
    }

    fn record_values_match(&self, predicate: &mut dyn FnMut(&Self) -> bool) -> Option<bool> {
        match self {
            Self::Record(fields) => Some(fields.values().all(predicate)),
            _ => None,
        }
    }

    fn string_literal(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    fn int_literal(&self) -> Option<i64> {
        match self {
            Self::Int(value) => Some(*value),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use harn_parser::builtin_signatures::{ShapeFieldDescriptor, Ty};

    use super::*;

    const STRING: Ty = Ty::Named("string");
    const STRING_LIST_ARGS: &[Ty] = &[STRING];
    const RESULT_ARGS: &[Ty] = &[STRING, Ty::Named("dict")];
    const INT_KEYED_DICT_ARGS: &[Ty] = &[Ty::Named("int"), STRING];
    const RECORD_FIELDS: &[ShapeFieldDescriptor] = &[
        ShapeFieldDescriptor::new("name", STRING),
        ShapeFieldDescriptor::optional("note", STRING),
    ];

    #[test]
    fn manifest_types_use_the_source_type_contract() {
        let strings = DataValue::List(vec![DataValue::String("kernel".into())]);
        assert!(matches_manifest_type(
            &strings,
            &Ty::Apply("list", STRING_LIST_ARGS)
        ));
        assert!(!matches_manifest_type(
            &DataValue::List(vec![DataValue::Int(1)]),
            &Ty::Apply("list", STRING_LIST_ARGS)
        ));

        let record = DataValue::Record(std::collections::BTreeMap::from([(
            "name".to_string(),
            DataValue::String("portable".into()),
        )]));
        assert!(matches_manifest_type(&record, &Ty::Shape(RECORD_FIELDS)));
    }

    #[test]
    fn portable_manifest_types_are_exactly_data_value_types() {
        assert!(manifest_type_is_portable(&Ty::Apply(
            "list",
            STRING_LIST_ARGS
        )));
        assert!(manifest_type_is_portable(&Ty::Shape(RECORD_FIELDS)));
        assert!(!manifest_type_is_portable(&Ty::Apply(
            "Result",
            RESULT_ARGS
        )));
        assert!(!manifest_type_is_portable(&Ty::Named("channel")));
        assert!(!manifest_type_is_portable(&Ty::Fn(&[], &STRING)));
        assert!(!manifest_type_is_portable(&Ty::Generic("T")));
        assert!(!manifest_type_is_portable(&Ty::Apply(
            "dict",
            INT_KEYED_DICT_ARGS
        )));
    }
}