//! The std modules a program reaches (ADR 0074): only they are resolved, //! type checked and lowered. They are found from the parse trees, before //! resolution, so a module that is not reached costs nothing past its //! (shared) parse. use std::collections::HashMap; use louise_syntax::ast::{self, AstNode}; use louise_syntax::{Parse, SyntaxKind}; use crate::{Module, PRELUDE}; /// Which of `modules` to analyse, by index: every module outside std, /// the prelude, and what they reach, transitively, through their imports /// (`@test import`s only with `tests`) and the syntax that names a std /// module itself ([`language_modules`]). pub(crate) fn reached(modules: &[Module], tests: bool) -> Vec { let index: HashMap<&str, usize> = (modules.iter().enumerate()) .map(|(i, m)| (m.path.as_str(), i)) .collect(); let mut reached = vec![false; modules.len()]; let mut work: Vec = (0..modules.len()) .filter(|&i| !modules[i].path.starts_with("std/")) .collect(); work.extend(index.get(PRELUDE)); while let Some(i) = work.pop() { if std::mem::replace(&mut reached[i], true) { continue; } let m = &modules[i]; for import in louise_hir::imports(&m.parse.tree(), tests) { let target = louise_hir::import_target(&m.path, &import.path, |p| index.contains_key(p)); work.extend(target.and_then(|t| index.get(t.as_str()))); } work.extend(language_modules(&m.parse).filter_map(|p| index.get(p))); } reached } /// The std modules the language names itself, for syntax that needs one /// without an import (`louise_types`' `WellKnown`): /// - an HTML literal is an `Element` of `std/html`; /// - a template literal is a `Template` of `std/template`; /// - `region` handles `std/ref`'s `st` and `alloc`; /// - a reference to a `@remote` function is a `Remote` of /// `std/dist/remote`. /// /// Every other well-known std type or effect is named in the program /// only through an import of its module, or in a value that a reached /// module made. fn language_modules(parse: &Parse) -> impl Iterator { const MODULES: [&str; 4] = ["std/html", "std/template", "std/ref", "std/dist/remote"]; let mut found = [false; 4]; for node in parse.syntax().descendants() { let which = match node.kind() { SyntaxKind::HTML_ELEMENT => 0, SyntaxKind::TEMPLATE_EXPR => 1, SyntaxKind::REGION_EXPR => 2, SyntaxKind::ATTR if ast::Attr::cast(node) .and_then(|a| a.name()) .is_some_and(|n| n.text() == "remote") => { 3 } _ => continue, }; found[which] = true; } MODULES .into_iter() .zip(found) .filter_map(|(m, f)| f.then_some(m)) }