Skip to main content

harn_modules/
type_dependencies.rs

1//! Type declarations required by imported callable signatures.
2//!
3//! A callable keeps the type environment of its defining module even when a
4//! facade re-exports it. The caller therefore needs the callable's named type
5//! dependencies, not every private type reachable from the facade.
6
7use std::collections::{BTreeMap, HashSet};
8use std::path::{Path, PathBuf};
9
10use harn_parser::{Node, SNode, TypeExpr};
11
12use super::{normalize_path, type_decl_name, LocatedTypeDeclaration, ModuleGraph};
13
14impl ModuleGraph {
15    pub(super) fn extend_callable_type_dependencies(
16        &self,
17        origin: &Path,
18        callable: &SNode,
19        declarations: &mut Vec<LocatedTypeDeclaration>,
20        seen: &mut HashSet<(PathBuf, String)>,
21    ) {
22        let mut names = HashSet::new();
23        collect_callable_type_names(callable, &mut names);
24        let mut names: Vec<String> = names.into_iter().collect();
25        names.sort();
26        for name in names {
27            self.extend_named_type_dependency(origin, &name, declarations, seen);
28        }
29    }
30
31    pub(super) fn extend_type_dependency(
32        &self,
33        origin: &Path,
34        declaration: &SNode,
35        declarations: &mut Vec<LocatedTypeDeclaration>,
36        seen: &mut HashSet<(PathBuf, String)>,
37    ) {
38        let Some(name) = type_decl_name(declaration) else {
39            return;
40        };
41        let origin = normalize_path(origin);
42        if !seen.insert((origin.clone(), name.to_string())) {
43            return;
44        }
45        declarations.push(LocatedTypeDeclaration {
46            file: origin.clone(),
47            declaration: declaration.clone(),
48        });
49
50        let mut names = HashSet::new();
51        collect_declaration_type_names(declaration, &mut names);
52        let mut names: Vec<String> = names.into_iter().collect();
53        names.sort();
54        for dependency in names {
55            self.extend_named_type_dependency(&origin, &dependency, declarations, seen);
56        }
57    }
58
59    fn extend_named_type_dependency(
60        &self,
61        visible_from: &Path,
62        name: &str,
63        declarations: &mut Vec<LocatedTypeDeclaration>,
64        seen: &mut HashSet<(PathBuf, String)>,
65    ) {
66        let mut visited = HashSet::new();
67        let Some((declaration, origin)) =
68            self.find_visible_type_declaration(visible_from, name, &mut visited)
69        else {
70            return;
71        };
72        self.extend_type_dependency(&origin, &declaration, declarations, seen);
73    }
74
75    /// Resolve a type name in its declaring module's typing context. This
76    /// includes private signature dependencies and does not grant import access.
77    pub fn type_declaration_visible_from(
78        &self,
79        file: &Path,
80        name: &str,
81    ) -> Option<LocatedTypeDeclaration> {
82        let (declaration, file) =
83            self.find_visible_type_declaration(file, name, &mut HashSet::new())?;
84        Some(LocatedTypeDeclaration { file, declaration })
85    }
86
87    /// Bind referenced type names to defining modules without flattening the
88    /// declaration's private scope into its importing module.
89    pub fn type_declaration_bindings(
90        &self,
91        site: &LocatedTypeDeclaration,
92    ) -> BTreeMap<String, PathBuf> {
93        let mut names = HashSet::new();
94        collect_declaration_type_names(&site.declaration, &mut names);
95        let declaration = match &site.declaration.node {
96            Node::AttributedDecl { inner, .. } => inner.as_ref(),
97            _ => &site.declaration,
98        };
99        let parameters = match &declaration.node {
100            Node::TypeDecl { type_params, .. }
101            | Node::StructDecl { type_params, .. }
102            | Node::EnumDecl { type_params, .. }
103            | Node::InterfaceDecl { type_params, .. } => type_params.as_slice(),
104            _ => &[],
105        };
106        for parameter in parameters {
107            names.remove(&parameter.name);
108        }
109        names
110            .into_iter()
111            .filter_map(|name| {
112                self.type_declaration_visible_from(&site.file, &name)
113                    .map(|target| (name, target.file))
114            })
115            .collect()
116    }
117
118    fn find_visible_type_declaration(
119        &self,
120        path: &Path,
121        name: &str,
122        visited: &mut HashSet<PathBuf>,
123    ) -> Option<(SNode, PathBuf)> {
124        let path = normalize_path(path);
125        if !visited.insert(path.clone()) {
126            return None;
127        }
128        let module = self.modules.get(&path)?;
129        if let Some(declaration) = module
130            .type_declarations
131            .iter()
132            .find(|declaration| type_decl_name(declaration) == Some(name))
133        {
134            return Some((declaration.clone(), path));
135        }
136
137        for import in &module.imports {
138            if import.namespace_alias.is_some()
139                || import
140                    .selective_names
141                    .as_ref()
142                    .is_some_and(|names| !names.contains(name))
143            {
144                continue;
145            }
146            let Some(import_path) = import.path.as_ref() else {
147                continue;
148            };
149            if let Some(found) = self.find_visible_type_declaration(import_path, name, visited) {
150                return Some(found);
151            }
152        }
153        None
154    }
155}
156
157fn collect_callable_type_names(callable: &SNode, names: &mut HashSet<String>) {
158    let callable = match &callable.node {
159        Node::AttributedDecl { inner, .. } => inner.as_ref(),
160        _ => callable,
161    };
162    match &callable.node {
163        Node::FnDecl {
164            params,
165            return_type,
166            type_predicate,
167            throws,
168            where_clauses,
169            ..
170        } => {
171            collect_parameter_type_names(params, names);
172            collect_optional_type_name(return_type, names);
173            if let Some(predicate) = type_predicate {
174                collect_type_names(&predicate.type_expr, names);
175            }
176            collect_optional_type_name(throws, names);
177            for clause in where_clauses {
178                collect_type_names(&clause.bound, names);
179            }
180        }
181        Node::Pipeline {
182            params,
183            return_type,
184            throws,
185            ..
186        }
187        | Node::ToolDecl {
188            params,
189            return_type,
190            throws,
191            ..
192        } => {
193            collect_parameter_type_names(params, names);
194            collect_optional_type_name(return_type, names);
195            collect_optional_type_name(throws, names);
196        }
197        _ => {}
198    }
199}
200
201fn collect_declaration_type_names(declaration: &SNode, names: &mut HashSet<String>) {
202    let declaration = match &declaration.node {
203        Node::AttributedDecl { inner, .. } => inner.as_ref(),
204        _ => declaration,
205    };
206    match &declaration.node {
207        Node::TypeDecl { type_expr, .. } => collect_type_names(type_expr, names),
208        Node::StructDecl { fields, .. } => {
209            for field in fields {
210                collect_optional_type_name(&field.type_expr, names);
211            }
212        }
213        Node::EnumDecl { variants, .. } => {
214            for variant in variants {
215                collect_parameter_type_names(&variant.fields, names);
216            }
217        }
218        Node::InterfaceDecl {
219            associated_types,
220            methods,
221            ..
222        } => {
223            for associated in associated_types {
224                collect_optional_type_name(&associated.default, names);
225            }
226            for method in methods {
227                collect_parameter_type_names(&method.params, names);
228                collect_optional_type_name(&method.return_type, names);
229            }
230        }
231        _ => {}
232    }
233}
234
235fn collect_parameter_type_names(params: &[harn_parser::TypedParam], names: &mut HashSet<String>) {
236    for param in params {
237        collect_optional_type_name(&param.type_expr, names);
238    }
239}
240
241fn collect_optional_type_name(type_expr: &Option<TypeExpr>, names: &mut HashSet<String>) {
242    if let Some(type_expr) = type_expr {
243        collect_type_names(type_expr, names);
244    }
245}
246
247fn collect_type_names(type_expr: &TypeExpr, names: &mut HashSet<String>) {
248    match type_expr {
249        TypeExpr::Named(name) => {
250            names.insert(name.clone());
251        }
252        TypeExpr::Applied { name, args } => {
253            names.insert(name.clone());
254            for arg in args {
255                collect_type_names(arg, names);
256            }
257        }
258        TypeExpr::Union(members) | TypeExpr::Intersection(members) | TypeExpr::Tuple(members) => {
259            for member in members {
260                collect_type_names(member, names);
261            }
262        }
263        TypeExpr::Shape(fields) => {
264            for field in fields {
265                collect_type_names(&field.type_expr, names);
266            }
267        }
268        TypeExpr::OpenShape { fields, rests } => {
269            for field in fields {
270                collect_type_names(&field.type_expr, names);
271            }
272            for rest in rests {
273                collect_type_names(rest, names);
274            }
275        }
276        TypeExpr::List(inner)
277        | TypeExpr::Iter(inner)
278        | TypeExpr::Generator(inner)
279        | TypeExpr::Stream(inner)
280        | TypeExpr::Owned(inner) => collect_type_names(inner, names),
281        TypeExpr::DictType(key, value) => {
282            collect_type_names(key, names);
283            collect_type_names(value, names);
284        }
285        TypeExpr::FnType {
286            params,
287            return_type,
288        } => {
289            for param in params {
290                collect_type_names(param, names);
291            }
292            collect_type_names(return_type, names);
293        }
294        TypeExpr::Never | TypeExpr::LitString(_) | TypeExpr::LitInt(_) => {}
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    fn write_file(root: &Path, name: &str, source: &str) -> PathBuf {
303        let path = root.join(name);
304        std::fs::write(&path, source).unwrap();
305        path
306    }
307
308    #[test]
309    fn located_types_retain_recursive_origins_through_callable_facades() {
310        let temp = tempfile::tempdir().unwrap();
311        let root = temp.path();
312        let contracts = write_file(root, "contracts.harn",
313            "type Recursive = {next?: Recursive, label: string}\npub type Request = {payload: Recursive}\n");
314        write_file(root, "api.harn",
315            "import { Request } from \"./contracts\"\npub fn run(request: Request) -> Request { request }\n");
316        let facade = write_file(root, "facade.harn", "pub import { run } from \"./api\"\n");
317        let entry = write_file(root, "entry.harn", "import { run } from \"./facade\"\n");
318        let graph = crate::build(std::slice::from_ref(&entry));
319        let sites = graph
320            .imported_type_declaration_sites_for_file(&entry)
321            .unwrap();
322        assert_eq!(sites.len(), 2);
323        assert!(sites
324            .iter()
325            .all(|site| site.file == normalize_path(&contracts)));
326        let names: HashSet<_> = sites
327            .iter()
328            .filter_map(|site| type_decl_name(&site.declaration))
329            .collect();
330        assert_eq!(names, HashSet::from(["Recursive", "Request"]));
331        let recursive = sites
332            .iter()
333            .find(|site| type_decl_name(&site.declaration) == Some("Recursive"))
334            .unwrap();
335        assert_eq!(
336            graph.type_declaration_bindings(recursive),
337            BTreeMap::from([("Recursive".to_string(), normalize_path(&contracts)),])
338        );
339        let request = sites
340            .iter()
341            .find(|site| type_decl_name(&site.declaration) == Some("Request"))
342            .unwrap();
343        assert_eq!(
344            request.declaration.span,
345            graph
346                .export_definition_of(&contracts, "Request")
347                .unwrap()
348                .span
349        );
350        assert_eq!(
351            graph.imported_type_declarations_for_file(&entry).unwrap(),
352            sites
353                .into_iter()
354                .map(|site| site.declaration)
355                .collect::<Vec<_>>()
356        );
357        assert!(graph.export_definition_of(&facade, "Recursive").is_none());
358    }
359
360    #[test]
361    fn private_same_named_types_bind_in_each_declaration_scope() {
362        let temp = tempfile::tempdir().unwrap();
363        let root = temp.path();
364        let left = write_file(
365            root,
366            "left.harn",
367            "type Details = {left_only: int}\npub type Left = {details: Details}\n",
368        );
369        let right = write_file(
370            root,
371            "right.harn",
372            "type Details = {right_only: string}\npub type Right = {details: Details}\n",
373        );
374        let entry = write_file(
375            root,
376            "entry.harn",
377            "import { Left } from \"./left\"\nimport { Right } from \"./right\"\n",
378        );
379        let graph = crate::build(std::slice::from_ref(&entry));
380        let sites = graph
381            .imported_type_declaration_sites_for_file(&entry)
382            .unwrap();
383        assert_eq!(
384            sites
385                .iter()
386                .filter(|site| type_decl_name(&site.declaration) == Some("Details"))
387                .count(),
388            2
389        );
390        for (name, origin) in [("Left", &left), ("Right", &right)] {
391            let site = sites
392                .iter()
393                .find(|site| type_decl_name(&site.declaration) == Some(name))
394                .unwrap();
395            assert_eq!(
396                graph.type_declaration_bindings(site),
397                BTreeMap::from([("Details".to_string(), normalize_path(origin)),])
398            );
399        }
400        let left_details = graph
401            .type_declaration_visible_from(&left, "Details")
402            .unwrap();
403        let right_details = graph
404            .type_declaration_visible_from(&right, "Details")
405            .unwrap();
406        assert_ne!(left_details.file, right_details.file);
407        assert_ne!(
408            left_details.declaration.node,
409            right_details.declaration.node
410        );
411        assert!(graph
412            .type_declaration_visible_from(&entry, "Details")
413            .is_none());
414    }
415
416    #[test]
417    fn declaration_bindings_omit_generic_parameters_even_when_a_private_type_shadows_them() {
418        let temp = tempfile::tempdir().unwrap();
419        let root = temp.path();
420        let models = write_file(root, "models.harn",
421            "type T = {unrelated: bool}\ntype Marker = {present: string}\npub struct Box<T> { value: T, count: int, marker: Marker }\n");
422        let entry = write_file(root, "entry.harn", "import { Box } from \"./models\"\n");
423        let graph = crate::build(std::slice::from_ref(&entry));
424        let site = graph.type_declaration_visible_from(&models, "Box").unwrap();
425        assert!(graph.type_declaration_visible_from(&models, "T").is_some());
426        assert!(graph
427            .type_declaration_visible_from(&models, "int")
428            .is_none());
429        assert_eq!(
430            graph.type_declaration_bindings(&site),
431            BTreeMap::from([("Marker".to_string(), normalize_path(&models)),])
432        );
433    }
434
435    #[test]
436    fn unresolved_import_cannot_become_an_empty_located_type_census() {
437        let temp = tempfile::tempdir().unwrap();
438        let root = temp.path();
439        let good = write_file(root, "good.harn", "pub type Known = {value: string}\n");
440        let entry = write_file(
441            root,
442            "entry.harn",
443            "import { Known } from \"./good\"\nimport \"./missing\"\n",
444        );
445        let graph = crate::build(std::slice::from_ref(&entry));
446        assert!(graph
447            .type_declaration_visible_from(&good, "Known")
448            .is_some());
449        assert!(graph
450            .imported_type_declaration_sites_for_file(&entry)
451            .is_none());
452        assert!(graph.imported_type_declarations_for_file(&entry).is_none());
453    }
454}