sealmap_rust/lib.rs
1//! # sealmap-rust
2//!
3//! A pure-Rust frontend that turns Rust source into a
4//! [`sealmap_model::Codebase`]: modules, types, traits, functions and
5//! methods, the relations between them, and an ordered call [`Flow`] for every
6//! function body (the input for sequence diagrams).
7//!
8//! It parses with [`syn`] and never runs `rustc`, `cargo` or anything else, so
9//! it works on any checkout, including code that does not compile, and needs
10//! no toolchain at runtime.
11//!
12//! [`Flow`]: sealmap_model::Flow
13//!
14//! ## How it works
15//!
16//! 1. **Layout.** `Cargo.toml` files in the [`SourceSet`] define packages;
17//! each `.rs` file is mapped to a crate and module path by Cargo's
18//! conventions (`src/lib.rs`, `src/a/mod.rs`, `src/bin/x.rs`, ...). Without
19//! any manifest, the whole set is one crate named after
20//! [`RustOptions::name`].
21//! 2. **Collect (per file, parallel).** Each file is parsed and reduced to
22//! plain data: items, `use` tables, impl blocks and unresolved call flows.
23//! 3. **Resolve (whole workspace, sequential).** Paths are resolved through
24//! local items, `use` imports (including renames, globs and `pub use`
25//! re-exports), `crate`/`self`/`super`/`Self`, and sibling workspace crates.
26//! Method calls are resolved from the receiver's declared or constructed
27//! type (`self`, `self.field`, typed params, `let x = Foo::new()`).
28//!
29//! ## What "resolved" means here
30//!
31//! There is no type checker. Every call and relation carries a
32//! [`Confidence`](sealmap_model::Confidence):
33//!
34//! * `exact`: resolved through explicit paths, imports or declared types to a
35//! symbol defined in the analysed code;
36//! * `inferred`: matched by a weaker rule (a unique, distinctive method name
37//! on an unknown receiver, or a method reached through deref);
38//! * `external`: outside the analysed code.
39//!
40//! Calls into `std`/`core`/`alloc`, prelude constructors (`Some`, `Ok`,
41//! `Vec::new` via `std`) and method calls on receivers of unknown type are
42//! dropped by default ([`ExternalCalls::NonStd`]), which keeps sequence
43//! diagrams dense: they show *your* code talking to itself and to its
44//! dependencies.
45//!
46//! ## Determinism
47//!
48//! Output depends only on the source set and options. Files are processed in
49//! path order, items in source order, and parallel parsing (feature
50//! `parallel`, on by default) collects results in input order, so the model
51//! is identical with or without it.
52//!
53//! ## Example
54//!
55//! ```
56//! use sealmap_model::{SourceSet, Step, SymbolId};
57//! use sealmap_rust::{RustOptions, extract};
58//!
59//! let mut src = SourceSet::new();
60//! src.insert("Cargo.toml", "[package]\nname = \"shop\"").unwrap();
61//! src.insert("src/lib.rs", r#"
62//! pub mod db;
63//! use db::Db;
64//!
65//! /// Order service.
66//! pub struct Orders { db: Db }
67//!
68//! impl Orders {
69//! pub fn place(&self, id: u64) -> Result<(), String> {
70//! if self.db.exists(id) {
71//! return Err("dup".into());
72//! }
73//! self.db.insert(id)?;
74//! Ok(())
75//! }
76//! }
77//! "#).unwrap();
78//! src.insert("src/db.rs", r#"
79//! pub struct Db;
80//! impl Db {
81//! pub fn exists(&self, id: u64) -> bool { false }
82//! pub fn insert(&self, id: u64) -> Result<(), String> { Ok(()) }
83//! }
84//! "#).unwrap();
85//!
86//! let out = extract(&src, &RustOptions::default());
87//! let place = out.codebase.symbol(&SymbolId::new("shop::Orders::place")).unwrap();
88//! let calls: Vec<_> = place.flow.as_ref().unwrap().calls().map(|c| c.target.as_str()).collect();
89//! assert_eq!(calls, ["shop::db::Db::exists", "shop::db::Db::insert"]);
90//! assert!(out.diagnostics.is_empty());
91//! ```
92
93#![forbid(unsafe_code)]
94#![deny(missing_docs)]
95
96mod collect;
97mod layout;
98mod raw;
99mod resolve;
100mod tidy;
101
102use std::path::Path;
103
104use sealmap_frontend::isolate::{COLLECT_STACK_BYTES, map_isolated};
105use sealmap_model::{LoadOptions, SourcePath, SourceSet};
106
107pub use sealmap_frontend::{Diagnostic, ExternalCalls, Extraction};
108
109/// Frontend options.
110#[derive(Debug, Clone)]
111pub struct RustOptions {
112 /// Codebase name, also used as the crate name when no `Cargo.toml` is
113 /// present.
114 pub name: String,
115 /// Include `#[cfg(test)]` modules, `#[test]` functions and files under
116 /// `tests/`, `examples/` and `benches/`. Off by default.
117 pub include_tests: bool,
118 /// External call policy.
119 pub external_calls: ExternalCalls,
120}
121
122impl Default for RustOptions {
123 fn default() -> Self {
124 Self { name: "codebase".into(), include_tests: false, external_calls: ExternalCalls::NonStd }
125 }
126}
127
128/// Extract a [`Codebase`](sealmap_model::Codebase) from the `.rs` (and `Cargo.toml`) files in
129/// `sources`. Never fails: unparsable files are reported in
130/// [`Extraction::diagnostics`].
131pub fn extract(sources: &SourceSet, options: &RustOptions) -> Extraction {
132 let plan = layout::plan(sources, &options.name);
133 let jobs: Vec<_> = plan
134 .into_iter()
135 .filter(|(_, role)| options.include_tests || role.target <= layout::TargetKind::Bin)
136 .filter_map(|(path, role)| sources.get(&path).map(|text| (path.clone(), role, text)))
137 .collect();
138
139 let files = collect_all(&jobs, options);
140
141 let (codebase, diagnostics) = resolve::build(&options.name, files, options);
142 Extraction { codebase, diagnostics }
143}
144
145type Job<'a> = (SourcePath, layout::FileRole, &'a str);
146
147/// Pass 1 over every file, isolated per file (big stacks, panic guard; see
148/// [`sealmap_frontend::isolate`]). A panic while collecting one file degrades
149/// that file to a diagnostic instead of aborting the run.
150fn collect_all(jobs: &[Job<'_>], options: &RustOptions) -> Vec<raw::RawFile> {
151 map_isolated(
152 jobs,
153 COLLECT_STACK_BYTES,
154 |(p, r, t)| collect::collect_file(p, r, t, options),
155 |(p, r, t), why| collect::failed_file(p, r, t, format!("1:1: internal error while collecting: {why}")),
156 )
157}
158
159/// Load the `.rs` and `Cargo.toml` files under `root` (honouring
160/// `.gitignore`, skipping `target/`, hidden directories and the like) without
161/// extracting them.
162pub fn load_dir(root: &Path) -> std::io::Result<SourceSet> {
163 let load = LoadOptions { extensions: vec!["rs".into(), "toml".into()], ..LoadOptions::default() };
164 let mut sources = SourceSet::load_dir(root, &load)?;
165 sources.retain(|p| p.extension() == Some("rs") || p.file_name() == "Cargo.toml");
166 Ok(sources)
167}
168
169/// Load `root` from disk (`.rs` and `Cargo.toml` files, skipping `target/`,
170/// hidden directories and the like) and [`extract`] it.
171///
172/// [`RustOptions::name`] defaults to the directory name when left as
173/// `"codebase"`.
174pub fn extract_dir(root: &Path, options: &RustOptions) -> std::io::Result<(SourceSet, Extraction)> {
175 let sources = load_dir(root)?;
176 let mut options = options.clone();
177 if options.name == "codebase" {
178 if let Some(n) = root.canonicalize().ok().and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
179 {
180 options.name = n;
181 }
182 }
183 let extraction = extract(&sources, &options);
184 Ok((sources, extraction))
185}
186
187/// Compiles and runs the README examples as doctests.
188#[cfg(doctest)]
189#[doc = include_str!("../README.md")]
190struct ReadmeDoctests;