Skip to main content

harn_builtin_meta/
lib.rs

1//! Const-constructible type definitions for Harn builtin signatures.
2//!
3//! Both `harn-parser` (for typechecking) and `harn-vm` (for runtime metadata)
4//! consume these shapes. Living in a dep-free crate lets the parser see the
5//! types without depending on the VM, and lets the `#[harn_builtin]` proc-macro
6//! emit `const` literals that link into either side.
7//!
8//! `Ty::to_type_expr` and friends, which convert into the parser's runtime
9//! `TypeExpr`, live in `harn-parser` since they depend on parser-internal AST.
10//!
11//! The [`shapes`] submodule holds the named structural-record consts
12//! (`LLM_CALL_OPTIONS`, `LLM_CALL_RESULT`, `TRANSCRIPT`, …) shared by the
13//! parser's static typechecking tables and the `#[harn_builtin]` macro's
14//! `@NAME` signature injection.
15
16pub mod contracts;
17pub mod host_capabilities;
18pub mod llm_options;
19pub mod runtime_type_tags;
20pub mod shapes;
21pub mod signatures;
22
23pub use contracts::{
24    wire_identifier_key, BuiltinContract, BuiltinExposure, CapabilityId, EffectAccess, EffectKind,
25    EffectSpec, ResourceSelector,
26};
27
28/// A complete, static description of one builtin: identifier, arity range,
29/// per-parameter types, generic type parameters, return type, and any
30/// where-clause bounds the type checker should enforce on call.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct BuiltinSignature {
33    /// Builtin name as registered in the VM and referenced from Harn source.
34    pub name: &'static str,
35    /// Positional parameters in declaration order. Trailing entries with
36    /// `optional: true` define the lower bound of the arity range; the
37    /// remaining entries plus `has_rest` define the upper bound.
38    pub params: &'static [Param],
39    /// Statically-known return type. Use [`Ty::Any`] when the return is
40    /// genuinely dynamic (e.g. `json_parse`).
41    pub returns: Ty,
42    /// Generic type parameter names declared on this builtin (e.g. `["T"]`
43    /// for `schema_parse<T>`).
44    pub type_params: &'static [&'static str],
45    /// True when the final parameter is variadic (rest). When set, the
46    /// effective arity upper bound is unbounded and the runtime will treat
47    /// trailing args as the rest-list.
48    pub has_rest: bool,
49    /// `where T: Foo` constraints. Each entry binds a generic type
50    /// parameter name to the name of an interface it must implement.
51    pub where_clauses: &'static [(&'static str, &'static str)],
52}
53
54impl BuiltinSignature {
55    /// Reuse a canonical signature shape under a projected source name.
56    pub const fn with_name(self, name: &'static str) -> Self {
57        Self { name, ..self }
58    }
59}
60
61/// One parameter slot inside a [`BuiltinSignature`].
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Param {
64    pub name: &'static str,
65    pub ty: Ty,
66    /// True when this parameter has a default at the call site (so it may
67    /// be omitted). All optional params must be trailing.
68    pub optional: bool,
69}
70
71impl Param {
72    pub const fn new(name: &'static str, ty: Ty) -> Self {
73        Self {
74            name,
75            ty,
76            optional: false,
77        }
78    }
79
80    pub const fn optional(name: &'static str, ty: Ty) -> Self {
81        Self {
82            name,
83            ty,
84            optional: true,
85        }
86    }
87}
88
89/// `const`-friendly type IR used in builtin descriptors. Mirrors the runtime
90/// `TypeExpr` from `harn-parser` but is constructable in `const` position with
91/// no allocation. Convert to `TypeExpr` at the boundary via the parser-side
92/// `Ty::to_type_expr` helper.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum Ty {
95    /// A primitive or user-defined named type: `int`, `string`, `bool`,
96    /// `float`, `nil`, `bytes`, `dict`, `list`, `closure`, `duration`,
97    /// `any`, etc.
98    Named(&'static str),
99    /// Reference to a generic type parameter declared on the enclosing
100    /// signature (e.g. `Generic("T")`).
101    Generic(&'static str),
102    /// Untyped/dynamic. Skips type validation at runtime; the static
103    /// checker treats it as compatible with everything.
104    Any,
105    /// Optional sugar for `T | nil`.
106    Optional(&'static Ty),
107    /// Generic application: `List<T>` is `Apply("list", &[T])`,
108    /// `Result<T, E>` is `Apply("Result", &[T, E])`, `Schema<T>` is
109    /// [`Ty::SchemaOf`].
110    Apply(&'static str, &'static [Ty]),
111    /// Union of N alternatives. Empty unions are rejected by the
112    /// parser-side converter.
113    Union(&'static [Ty]),
114    /// Function type. Stores params and return as references so the literal
115    /// stays `Copy`.
116    Fn(&'static [Ty], &'static Ty),
117    /// Record/shape type with named fields. Closed: an argument carrying a
118    /// field that is not listed here is rejected.
119    Shape(&'static [ShapeFieldDescriptor]),
120    /// Open record: named fields plus one or more row tails, mirroring the
121    /// language's `{name: string, ...dict}`.
122    ///
123    /// Use this for a builtin that takes an extensible options/config dict.
124    /// A closed [`Ty::Shape`] would reject every key the signature does not
125    /// name, so such a parameter would otherwise have to fall back to a bare
126    /// `dict` and lose all field checking — including the declared type of a
127    /// `handler` slot.
128    OpenShape(&'static [ShapeFieldDescriptor], &'static [Ty]),
129    /// `Schema<T>` marker — semantically `Apply("Schema", &[Generic(T)])`
130    /// but distinguished so the type checker can pull the bound `T` from
131    /// the *value* of the schema arg (not its declared type).
132    SchemaOf(&'static str),
133    /// Bottom type (no return).
134    Never,
135    /// Integer literal type: `0`, `1`. Assignable to `int`.
136    LitInt(i64),
137    /// String literal type: `"pass"`. Assignable to `string`.
138    LitString(&'static str),
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub struct ShapeFieldDescriptor {
143    pub name: &'static str,
144    pub ty: Ty,
145    pub optional: bool,
146}
147
148impl ShapeFieldDescriptor {
149    pub const fn new(name: &'static str, ty: Ty) -> Self {
150        Self {
151            name,
152            ty,
153            optional: false,
154        }
155    }
156
157    pub const fn optional(name: &'static str, ty: Ty) -> Self {
158        Self {
159            name,
160            ty,
161            optional: true,
162        }
163    }
164}
165
166impl Ty {
167    /// True when this type carries no constraints (validation is a no-op).
168    pub const fn is_any(&self) -> bool {
169        matches!(self, Ty::Any)
170    }
171}
172
173/// Render shape fields and row tails in the `#[harn_builtin]` sig grammar.
174///
175/// An optional field is written `name?: ty`, not `name: ty?`. The trailing
176/// form does not round-trip: the sig parser folds a trailing `?` into the
177/// type as `ty | nil` and leaves the field required.
178fn write_shape_members(
179    f: &mut core::fmt::Formatter<'_>,
180    fields: &[ShapeFieldDescriptor],
181    rests: &[Ty],
182) -> core::fmt::Result {
183    for (i, fld) in fields.iter().enumerate() {
184        if i > 0 {
185            f.write_str(", ")?;
186        }
187        let name = fld.name;
188        let ty = &fld.ty;
189        let optional = if fld.optional { "?" } else { "" };
190        write!(f, "{name}{optional}: {ty}")?;
191    }
192    for (i, rest) in rests.iter().enumerate() {
193        if i > 0 || !fields.is_empty() {
194            f.write_str(", ")?;
195        }
196        write!(f, "...{rest}")?;
197    }
198    Ok(())
199}
200
201impl core::fmt::Display for Ty {
202    /// Render a parsed [`Ty`] back into the `#[harn_builtin]` sig grammar.
203    /// Round-trip target: parsing the output through the proc-macro's
204    /// sig parser yields a structurally-equal [`Ty`] (modulo whitespace and
205    /// canonical operator spacing). See the drift test in
206    /// `crates/harn-vm/tests/harn_vm/builtin_signature_text_drift.rs`.
207    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
208        match self {
209            Ty::Named(s) | Ty::Generic(s) => f.write_str(s),
210            Ty::Any => f.write_str("any"),
211            Ty::Never => f.write_str("never"),
212            Ty::Optional(inner) => write!(f, "{inner}?"),
213            Ty::Apply(name, args) => {
214                f.write_str(name)?;
215                f.write_str("<")?;
216                for (i, a) in args.iter().enumerate() {
217                    if i > 0 {
218                        f.write_str(", ")?;
219                    }
220                    write!(f, "{a}")?;
221                }
222                f.write_str(">")
223            }
224            Ty::Union(parts) => {
225                // Recover sig-grammar sugar so output round-trips through
226                // the proc-macro sig parser (which desugars `T?` and
227                // `number` into unions).
228                if let [inner, Ty::Named("nil")] = parts {
229                    if !matches!(inner, Ty::Named("nil")) {
230                        return write!(f, "{inner}?");
231                    }
232                }
233                if let [Ty::Named("int"), Ty::Named("float")] = parts {
234                    return f.write_str("number");
235                }
236                for (i, p) in parts.iter().enumerate() {
237                    if i > 0 {
238                        f.write_str(" | ")?;
239                    }
240                    write!(f, "{p}")?;
241                }
242                Ok(())
243            }
244            Ty::Fn(params, ret) => {
245                f.write_str("(")?;
246                for (i, p) in params.iter().enumerate() {
247                    if i > 0 {
248                        f.write_str(", ")?;
249                    }
250                    write!(f, "{p}")?;
251                }
252                write!(f, ") -> {ret}")
253            }
254            Ty::Shape(fields) => {
255                f.write_str("{")?;
256                write_shape_members(f, fields, &[])?;
257                f.write_str("}")
258            }
259            Ty::OpenShape(fields, rests) => {
260                f.write_str("{")?;
261                write_shape_members(f, fields, rests)?;
262                f.write_str("}")
263            }
264            Ty::SchemaOf(t) => write!(f, "Schema<{t}>"),
265            Ty::LitInt(n) => write!(f, "{n}"),
266            Ty::LitString(s) => write!(f, "\"{s}\""),
267        }
268    }
269}
270
271impl BuiltinSignature {
272    /// Non-generic, fixed-arity builtin: no type parameters, no rest, no
273    /// where-clause bounds. Covers ~70% of the registry; lets each call
274    /// site stay on a single logical line.
275    pub const fn simple(name: &'static str, params: &'static [Param], returns: Ty) -> Self {
276        Self {
277            name,
278            params,
279            returns,
280            type_params: &[],
281            has_rest: false,
282            where_clauses: &[],
283        }
284    }
285
286    /// Non-generic builtin whose final parameter is variadic (rest).
287    /// Equivalent to [`Self::simple`] with `has_rest: true`.
288    pub const fn variadic(name: &'static str, params: &'static [Param], returns: Ty) -> Self {
289        Self {
290            name,
291            params,
292            returns,
293            type_params: &[],
294            has_rest: true,
295            where_clauses: &[],
296        }
297    }
298
299    /// Generic, fixed-arity builtin: declares type parameters, no rest,
300    /// no where-clause bounds. Use the struct literal directly when both
301    /// generics and where-clauses or rest are needed.
302    pub const fn generic(
303        name: &'static str,
304        type_params: &'static [&'static str],
305        params: &'static [Param],
306        returns: Ty,
307    ) -> Self {
308        Self {
309            name,
310            params,
311            returns,
312            type_params,
313            has_rest: false,
314            where_clauses: &[],
315        }
316    }
317
318    /// Number of required parameters (those without defaults).
319    pub fn required_params(&self) -> usize {
320        self.params.iter().filter(|p| !p.optional).count()
321    }
322
323    /// True when this builtin recognises `name` as one of its declared
324    /// generic type parameters.
325    pub fn is_type_param(&self, name: &str) -> bool {
326        self.type_params.contains(&name)
327    }
328
329    /// True when this builtin declares any generic type parameters.
330    pub fn is_generic(&self) -> bool {
331        !self.type_params.is_empty()
332    }
333
334    /// Materialize the type parameter names as owned strings (for use in
335    /// the type checker's existing scope/binding APIs which key off
336    /// `Vec<String>`).
337    pub fn type_param_names(&self) -> Vec<String> {
338        self.type_params.iter().map(|s| (*s).to_string()).collect()
339    }
340
341    /// Where-clause constraints as `(type_param, interface)` strings.
342    pub fn where_clause_strings(&self) -> Vec<(String, String)> {
343        self.where_clauses
344            .iter()
345            .map(|(tp, iface)| ((*tp).to_string(), (*iface).to_string()))
346            .collect()
347    }
348}
349
350impl core::fmt::Display for BuiltinSignature {
351    /// Render a parsed [`BuiltinSignature`] back into the `#[harn_builtin]`
352    /// `sig = "..."` grammar. Used by the drift test and by tooling that
353    /// wants a canonical string form of the signature regardless of how it
354    /// was originally typed.
355    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356        if !self.type_params.is_empty() {
357            f.write_str("<")?;
358            for (i, tp) in self.type_params.iter().enumerate() {
359                if i > 0 {
360                    f.write_str(", ")?;
361                }
362                f.write_str(tp)?;
363            }
364            if !self.where_clauses.is_empty() {
365                f.write_str(" where ")?;
366                for (i, (tp, iface)) in self.where_clauses.iter().enumerate() {
367                    if i > 0 {
368                        f.write_str(", ")?;
369                    }
370                    write!(f, "{tp}: {iface}")?;
371                }
372            }
373            f.write_str("> ")?;
374        }
375        f.write_str(self.name)?;
376        f.write_str("(")?;
377        let last_idx = self.params.len().saturating_sub(1);
378        for (i, p) in self.params.iter().enumerate() {
379            if i > 0 {
380                f.write_str(", ")?;
381            }
382            if self.has_rest && i == last_idx {
383                f.write_str("...")?;
384            }
385            f.write_str(p.name)?;
386            if p.optional {
387                f.write_str("?")?;
388            }
389            let ty = &p.ty;
390            write!(f, ": {ty}")?;
391        }
392        let ret = &self.returns;
393        write!(f, ") -> {ret}")
394    }
395}
396
397/// Public view of one builtin used by `harn-lint` and other crates that need
398/// just identifier + return-type hints (no parameter types).
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub struct BuiltinMetadata {
401    pub name: &'static str,
402    pub return_types: &'static [&'static str],
403}
404
405// ---- Convenience constants ----
406//
407// Used pervasively in builtin signature literals to keep individual entries
408// terse. Add new constants here when a type appears repeatedly enough to
409// warrant a shorthand (avoid one-off shorthands).
410
411pub const TY_ANY: Ty = Ty::Any;
412pub const TY_BOOL: Ty = Ty::Named("bool");
413pub const TY_BYTES: Ty = Ty::Named("bytes");
414pub const TY_CLOSURE: Ty = Ty::Named("closure");
415pub const TY_DECIMAL: Ty = Ty::Named("decimal");
416pub const TY_DICT: Ty = Ty::Named("dict");
417pub const TY_DURATION: Ty = Ty::Named("duration");
418pub const TY_FLOAT: Ty = Ty::Named("float");
419pub const TY_INT: Ty = Ty::Named("int");
420pub const TY_LIST: Ty = Ty::Named("list");
421pub const TY_NEVER: Ty = Ty::Never;
422pub const TY_NIL: Ty = Ty::Named("nil");
423pub const TY_RESOURCE: Ty = Ty::Named("resource");
424pub const TY_STRING: Ty = Ty::Named("string");
425
426/// `string | nil`.
427pub const TY_STRING_OR_NIL: Ty = Ty::Union(&[TY_STRING, TY_NIL]);
428/// `int | nil`.
429pub const TY_INT_OR_NIL: Ty = Ty::Union(&[TY_INT, TY_NIL]);
430/// `dict | nil`.
431pub const TY_DICT_OR_NIL: Ty = Ty::Union(&[TY_DICT, TY_NIL]);
432/// `bytes | nil`.
433pub const TY_BYTES_OR_NIL: Ty = Ty::Union(&[TY_BYTES, TY_NIL]);
434/// `int | float`.
435pub const TY_NUMBER: Ty = Ty::Union(&[TY_INT, TY_FLOAT]);
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    const APPLY_ARGS: &[Ty] = &[TY_DICT];
442    const FN_PARAMS: &[Ty] = &[TY_INT, TY_STRING];
443    const SHAPE_FIELDS: &[ShapeFieldDescriptor] = &[
444        ShapeFieldDescriptor::new("name", TY_STRING),
445        ShapeFieldDescriptor::optional("age", TY_INT),
446    ];
447
448    const OPEN_SHAPE_RESTS: &[Ty] = &[TY_DICT];
449
450    #[test]
451    fn wire_identifier_keys_stay_unique_across_capabilities() {
452        // `from_host_namespace` resolves by normalized spelling, so two
453        // capabilities whose field names differ only by `_` or case would make
454        // every host-wire lookup ambiguous. Guard the vocabulary, not the
455        // lookup: the ambiguity would be introduced by adding a capability.
456        let mut seen = std::collections::HashMap::new();
457        for capability in CapabilityId::ALL {
458            let key = wire_identifier_key(capability.field_name());
459            if let Some(other) = seen.insert(key.clone(), capability.field_name()) {
460                panic!(
461                    "`{other}` and `{}` both normalize to `{key}`",
462                    capability.field_name()
463                );
464            }
465        }
466    }
467
468    #[test]
469    fn host_namespace_resolves_the_separatorless_spelling() {
470        assert_eq!(
471            CapabilityId::from_host_namespace("prmonitor"),
472            Some(CapabilityId::PrMonitor)
473        );
474        assert_eq!(
475            CapabilityId::from_host_namespace("PrMonitor"),
476            Some(CapabilityId::PrMonitor)
477        );
478        assert_eq!(
479            CapabilityId::from_host_namespace("pr_monitor"),
480            Some(CapabilityId::PrMonitor)
481        );
482        assert_eq!(CapabilityId::from_host_namespace("not_a_capability"), None);
483        // The exact parser stays exact: it reads the closed source vocabulary,
484        // where a spelling either is or is not the declared field name.
485        assert_eq!(CapabilityId::from_field_name("prmonitor"), None);
486    }
487
488    #[test]
489    fn ty_display_atomic_and_compound() {
490        assert_eq!(format!("{TY_INT}"), "int");
491        assert_eq!(format!("{TY_ANY}"), "any");
492        assert_eq!(format!("{TY_NEVER}"), "never");
493        // `T | nil` round-trips as `T?` (the sig grammar's optional sugar
494        // is desugared into a 2-element union, not `Ty::Optional`).
495        assert_eq!(format!("{TY_STRING_OR_NIL}"), "string?");
496        let opt_int = Ty::Optional(&TY_INT);
497        assert_eq!(format!("{opt_int}"), "int?");
498        // `int | float` round-trips as `number` (the predeclared shorthand).
499        assert_eq!(format!("{TY_NUMBER}"), "number");
500        let list_dict = Ty::Apply("list", APPLY_ARGS);
501        assert_eq!(format!("{list_dict}"), "list<dict>");
502        let lit_int = Ty::LitInt(42);
503        assert_eq!(format!("{lit_int}"), "42");
504        let lit_str = Ty::LitString("pass");
505        assert_eq!(format!("{lit_str}"), "\"pass\"");
506        let schema_t = Ty::SchemaOf("T");
507        assert_eq!(format!("{schema_t}"), "Schema<T>");
508        let fn_ty = Ty::Fn(FN_PARAMS, &TY_BOOL);
509        assert_eq!(format!("{fn_ty}"), "(int, string) -> bool");
510        let shape = Ty::Shape(SHAPE_FIELDS);
511        // An optional field renders as `age?: int`, not `age: int?`. The
512        // trailing form does not round-trip: the sig parser folds a trailing
513        // `?` into the type as `int | nil`, which leaves the field *required*
514        // and silently changes the contract.
515        assert_eq!(format!("{shape}"), "{name: string, age?: int}");
516        let open = Ty::OpenShape(SHAPE_FIELDS, OPEN_SHAPE_RESTS);
517        assert_eq!(format!("{open}"), "{name: string, age?: int, ...dict}");
518        let tail_only = Ty::OpenShape(&[], OPEN_SHAPE_RESTS);
519        assert_eq!(format!("{tail_only}"), "{...dict}");
520    }
521
522    const BASIC_PARAMS: &[Param] = &[Param::new("a", TY_DICT), Param::new("b", TY_DICT)];
523    const REST_PARAMS: &[Param] = &[Param::new("prefix", TY_STRING), Param::new("args", TY_ANY)];
524    const OPT_PARAMS: &[Param] = &[
525        Param::new("receipt", TY_DICT),
526        Param::optional("candidate", TY_ANY),
527    ];
528    const GENERIC_PARAMS: &[Param] = &[Param::new("schema", Ty::SchemaOf("T"))];
529
530    #[test]
531    fn signature_display_basic() {
532        let sig = BuiltinSignature::simple("deep_merge", BASIC_PARAMS, TY_DICT);
533        assert_eq!(format!("{sig}"), "deep_merge(a: dict, b: dict) -> dict");
534    }
535
536    #[test]
537    fn signature_display_with_optional_and_rest() {
538        let sig = BuiltinSignature {
539            name: "io_println",
540            params: REST_PARAMS,
541            returns: TY_NIL,
542            type_params: &[],
543            has_rest: true,
544            where_clauses: &[],
545        };
546        assert_eq!(
547            format!("{sig}"),
548            "io_println(prefix: string, ...args: any) -> nil"
549        );
550
551        let opt_sig =
552            BuiltinSignature::simple("lifecycle_replay_resume_input", OPT_PARAMS, TY_DICT);
553        assert_eq!(
554            format!("{opt_sig}"),
555            "lifecycle_replay_resume_input(receipt: dict, candidate?: any) -> dict"
556        );
557    }
558
559    #[test]
560    fn signature_display_with_generics_and_where() {
561        let sig = BuiltinSignature {
562            name: "schema_parse",
563            params: GENERIC_PARAMS,
564            returns: Ty::Generic("T"),
565            type_params: &["T"],
566            has_rest: false,
567            where_clauses: &[("T", "Decode")],
568        };
569        assert_eq!(
570            format!("{sig}"),
571            "<T where T: Decode> schema_parse(schema: Schema<T>) -> T"
572        );
573    }
574}