harn-modules 0.8.26

Cross-file module graph and import resolution utilities 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
//! Interface fingerprints — a stable hash of a module's public surface.
//!
//! The fingerprint covers exactly the parts of a module that downstream
//! importers can observe:
//!
//! * public functions, pipelines, tools, skills (name + signature)
//! * public structs, enums, type aliases, interfaces (full shape)
//! * `pub import` re-exports (target path + selective names)
//!
//! It intentionally excludes anything internal — function bodies,
//! comments, private helpers, local variable bindings — so an edit that
//! changes only the implementation of a public function leaves the
//! fingerprint stable and dependents stay valid.
//!
//! The hash is BLAKE3 over a canonical textual rendering of the surface
//! (alphabetized, single source of truth so trivial reorderings don't
//! flip the fingerprint either).

use std::fmt::Write as _;
use std::path::Path;

use harn_parser::{
    peel_attributes, EnumVariant, InterfaceMethod, Node, Parser, SNode, ShapeField, StructField,
    TypeExpr, TypeParam, TypedParam, Variance, WhereClause,
};

use crate::read_module_source;

/// A 32-byte BLAKE3 digest of a module's public surface.
pub type Fingerprint = [u8; 32];

/// Compute the interface fingerprint for `program` (the parsed top-level
/// statements of a module). Returns the BLAKE3 digest of a canonical
/// textual rendering — see the module docs for what's included.
pub fn fingerprint_program(program: &[SNode]) -> Fingerprint {
    let canonical = canonicalize_program(program);
    blake3::hash(canonical.as_bytes()).into()
}

/// Convenience: parse `path` (real file or `<std>` virtual path) and
/// fingerprint its public surface. Returns `None` when the source can't
/// be read or doesn't lex/parse — callers can treat that as "no
/// fingerprint" rather than erroring.
pub fn fingerprint_file(path: &Path) -> Option<Fingerprint> {
    let source = read_module_source(path)?;
    fingerprint_source(&source)
}

/// Fingerprint an already-loaded source string. Lex + parse failures
/// return `None`.
pub fn fingerprint_source(source: &str) -> Option<Fingerprint> {
    let mut lexer = harn_lexer::Lexer::new(source);
    let tokens = lexer.tokenize().ok()?;
    let program = Parser::new(tokens).parse().ok()?;
    Some(fingerprint_program(&program))
}

/// Hex-encode a fingerprint for human-readable output (NDJSON events,
/// logs, etc.).
pub fn fingerprint_hex(fp: &Fingerprint) -> String {
    let mut out = String::with_capacity(fp.len() * 2);
    for b in fp {
        write!(&mut out, "{b:02x}").expect("write to String is infallible");
    }
    out
}

fn canonicalize_program(program: &[SNode]) -> String {
    let mut lines: Vec<String> = program.iter().filter_map(canonicalize_top_level).collect();
    lines.sort();
    lines.join("\n")
}

fn canonicalize_top_level(snode: &SNode) -> Option<String> {
    let (_attrs, inner) = peel_attributes(snode);
    match &inner.node {
        Node::FnDecl {
            name,
            type_params,
            params,
            return_type,
            where_clauses,
            is_pub,
            is_stream,
            ..
        } => is_pub.then(|| {
            format!(
                "fn{stream}:{name}{generics}({params}){ret}{wheres}",
                stream = if *is_stream { "*" } else { "" },
                generics = format_type_params(type_params),
                params = format_typed_params(params),
                ret = format_return(return_type),
                wheres = format_where_clauses(where_clauses),
            )
        }),
        Node::Pipeline {
            name,
            params,
            return_type,
            is_pub,
            extends,
            ..
        } => is_pub.then(|| {
            format!(
                "pipeline:{name}({params}){ret}{extends}",
                params = params.join(","),
                ret = format_return(return_type),
                extends = extends
                    .as_deref()
                    .map(|e| format!(" extends {e}"))
                    .unwrap_or_default(),
            )
        }),
        Node::ToolDecl {
            name,
            params,
            return_type,
            is_pub,
            ..
        } => is_pub.then(|| {
            format!(
                "tool:{name}({params}){ret}",
                params = format_typed_params(params),
                ret = format_return(return_type),
            )
        }),
        Node::SkillDecl { name, is_pub, .. } => {
            // Skill bodies are configuration that downstream importers
            // observe by reading the resulting registry dict, but a
            // skill is identified by its name from a typing perspective.
            // The conservative thing is to hash the name only and let
            // body edits propagate via runtime registration rather than
            // type-time invalidation.
            is_pub.then(|| format!("skill:{name}"))
        }
        Node::StructDecl {
            name,
            type_params,
            fields,
            is_pub,
        } => is_pub.then(|| {
            format!(
                "struct:{name}{generics}{{{fields}}}",
                generics = format_type_params(type_params),
                fields = format_struct_fields(fields),
            )
        }),
        Node::EnumDecl {
            name,
            type_params,
            variants,
            is_pub,
        } => is_pub.then(|| {
            format!(
                "enum:{name}{generics}{{{variants}}}",
                generics = format_type_params(type_params),
                variants = format_enum_variants(variants),
            )
        }),
        Node::InterfaceDecl {
            name,
            type_params,
            associated_types,
            methods,
        } => Some(format!(
            "interface:{name}{generics}{{assoc=[{assoc}]methods=[{methods}]}}",
            generics = format_type_params(type_params),
            assoc = format_associated_types(associated_types),
            methods = format_interface_methods(methods),
        )),
        Node::TypeDecl {
            name,
            type_params,
            type_expr,
        } => Some(format!(
            "type:{name}{generics}={ty}",
            generics = format_type_params(type_params),
            ty = format_type_expr(type_expr),
        )),
        Node::ImportDecl { path, is_pub } => is_pub.then(|| format!("pub_import_wildcard:{path}")),
        Node::SelectiveImport {
            names,
            path,
            is_pub,
        } => is_pub.then(|| {
            let mut sorted = names.clone();
            sorted.sort();
            format!("pub_import_selective:{path}::{}", sorted.join(","))
        }),
        _ => None,
    }
}

fn format_type_params(params: &[TypeParam]) -> String {
    if params.is_empty() {
        return String::new();
    }
    let parts: Vec<String> = params
        .iter()
        .map(|p| {
            let var = match p.variance {
                Variance::Invariant => "",
                Variance::Covariant => "out ",
                Variance::Contravariant => "in ",
            };
            format!("{var}{}", p.name)
        })
        .collect();
    format!("<{}>", parts.join(","))
}

fn format_typed_params(params: &[TypedParam]) -> String {
    params
        .iter()
        .map(|p| {
            let mut s = String::new();
            if p.rest {
                s.push_str("...");
            }
            s.push_str(&p.name);
            if let Some(ty) = &p.type_expr {
                s.push(':');
                s.push_str(&format_type_expr(ty));
            }
            // Default values reference expressions whose shape we don't
            // walk into; presence-only is enough — adding a default to
            // a public parameter changes the callable contract.
            if p.default_value.is_some() {
                s.push_str("=?");
            }
            s
        })
        .collect::<Vec<_>>()
        .join(",")
}

fn format_return(ret: &Option<TypeExpr>) -> String {
    match ret {
        Some(ty) => format!("->{}", format_type_expr(ty)),
        None => String::new(),
    }
}

fn format_where_clauses(clauses: &[WhereClause]) -> String {
    if clauses.is_empty() {
        return String::new();
    }
    let mut parts: Vec<String> = clauses
        .iter()
        .map(|w| format!("{}:{}", w.type_name, w.bound))
        .collect();
    parts.sort();
    format!(" where {}", parts.join(","))
}

fn format_struct_fields(fields: &[StructField]) -> String {
    let mut rendered: Vec<String> = fields
        .iter()
        .map(|f| {
            let opt = if f.optional { "?" } else { "" };
            let ty = f
                .type_expr
                .as_ref()
                .map(format_type_expr)
                .unwrap_or_default();
            format!("{}{opt}:{ty}", f.name)
        })
        .collect();
    rendered.sort();
    rendered.join(",")
}

fn format_enum_variants(variants: &[EnumVariant]) -> String {
    let mut rendered: Vec<String> = variants
        .iter()
        .map(|v| format!("{}({})", v.name, format_typed_params(&v.fields)))
        .collect();
    rendered.sort();
    rendered.join(",")
}

fn format_associated_types(items: &[(String, Option<TypeExpr>)]) -> String {
    let mut rendered: Vec<String> = items
        .iter()
        .map(|(name, bound)| match bound {
            Some(ty) => format!("{name}:{}", format_type_expr(ty)),
            None => name.clone(),
        })
        .collect();
    rendered.sort();
    rendered.join(",")
}

fn format_interface_methods(methods: &[InterfaceMethod]) -> String {
    let mut rendered: Vec<String> = methods
        .iter()
        .map(|m| {
            format!(
                "{}{}({}){}",
                m.name,
                format_type_params(&m.type_params),
                format_typed_params(&m.params),
                format_return(&m.return_type),
            )
        })
        .collect();
    rendered.sort();
    rendered.join(",")
}

fn format_type_expr(ty: &TypeExpr) -> String {
    match ty {
        TypeExpr::Named(name) => name.clone(),
        TypeExpr::Union(parts) => {
            let mut rendered: Vec<String> = parts.iter().map(format_type_expr).collect();
            rendered.sort();
            format!("({})", rendered.join("|"))
        }
        TypeExpr::Intersection(parts) => {
            let mut rendered: Vec<String> = parts.iter().map(format_type_expr).collect();
            rendered.sort();
            format!("({})", rendered.join("&"))
        }
        TypeExpr::Shape(fields) => format!("{{{}}}", format_shape_fields(fields)),
        TypeExpr::List(inner) => format!("list<{}>", format_type_expr(inner)),
        TypeExpr::DictType(k, v) => {
            format!("dict<{},{}>", format_type_expr(k), format_type_expr(v))
        }
        TypeExpr::Iter(inner) => format!("iter<{}>", format_type_expr(inner)),
        TypeExpr::Generator(inner) => format!("Generator<{}>", format_type_expr(inner)),
        TypeExpr::Stream(inner) => format!("Stream<{}>", format_type_expr(inner)),
        TypeExpr::Applied { name, args } => {
            let rendered: Vec<String> = args.iter().map(format_type_expr).collect();
            format!("{name}<{}>", rendered.join(","))
        }
        TypeExpr::FnType {
            params,
            return_type,
        } => {
            let rendered: Vec<String> = params.iter().map(format_type_expr).collect();
            format!(
                "fn({})->{}",
                rendered.join(","),
                format_type_expr(return_type)
            )
        }
        TypeExpr::Never => "Never".to_string(),
        TypeExpr::LitString(s) => format!("\"{s}\""),
        TypeExpr::LitInt(n) => n.to_string(),
        TypeExpr::Owned(inner) => format!("owned<{}>", format_type_expr(inner)),
    }
}

fn format_shape_fields(fields: &[ShapeField]) -> String {
    let mut rendered: Vec<String> = fields
        .iter()
        .map(|f| {
            let opt = if f.optional { "?" } else { "" };
            format!("{}{opt}:{}", f.name, format_type_expr(&f.type_expr))
        })
        .collect();
    rendered.sort();
    rendered.join(",")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fp(source: &str) -> Fingerprint {
        fingerprint_source(source).expect("source parses")
    }

    #[test]
    fn private_body_change_does_not_flip_fingerprint() {
        let before = fp("pub fn add(a: int, b: int) -> int { a + b }\n");
        let after = fp("pub fn add(a: int, b: int) -> int { let s = a + b; s }\n");
        assert_eq!(before, after);
    }

    #[test]
    fn private_helper_does_not_flip_fingerprint() {
        let before = fp("pub fn entry() { internal() }\nfn internal() { 1 }\n");
        let after = fp("pub fn entry() { internal() }\nfn internal() { 2 }\nfn extra() { 3 }\n");
        assert_eq!(before, after);
    }

    #[test]
    fn reordering_public_decls_does_not_flip_fingerprint() {
        let a = fp("pub fn alpha() {}\npub fn beta() {}\n");
        let b = fp("pub fn beta() {}\npub fn alpha() {}\n");
        assert_eq!(a, b);
    }

    #[test]
    fn changing_public_signature_flips_fingerprint() {
        let before = fp("pub fn add(a: int, b: int) -> int { a + b }\n");
        let after = fp("pub fn add(a: int, b: int, c: int) -> int { a + b + c }\n");
        assert_ne!(before, after);
    }

    #[test]
    fn changing_public_return_type_flips_fingerprint() {
        let before = fp("pub fn make() -> string { \"x\" }\n");
        let after = fp("pub fn make() -> int { 1 }\n");
        assert_ne!(before, after);
    }

    #[test]
    fn adding_pub_struct_field_flips_fingerprint() {
        let before = fp("pub struct Point { x: int, y: int }\n");
        let after = fp("pub struct Point { x: int, y: int, z: int }\n");
        assert_ne!(before, after);
    }

    #[test]
    fn pub_re_export_change_flips_fingerprint() {
        let before = fp("pub import { foo } from \"./a\"\n");
        let after = fp("pub import { foo, bar } from \"./a\"\n");
        assert_ne!(before, after);
    }

    #[test]
    fn adding_pub_decl_flips_fingerprint() {
        let before = fp("pub fn alpha() {}\n");
        let after = fp("pub fn alpha() {}\npub fn beta() {}\n");
        assert_ne!(before, after);
    }

    #[test]
    fn changing_only_non_pub_imports_does_not_flip_fingerprint() {
        let before = fp("import \"./a\"\npub fn entry() {}\n");
        let after = fp("import \"./b\"\npub fn entry() {}\n");
        // Private imports affect what _this_ module sees but not what
        // downstreams see, so they're outside the public surface.
        assert_eq!(before, after);
    }

    #[test]
    fn hex_is_64_chars() {
        let h = fingerprint_hex(&fp("pub fn x() {}\n"));
        assert_eq!(h.len(), 64);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
    }
}