Skip to main content

sealmap_rust/
lib.rs

1//! # sealmap-rust
2//!
3//! A pure-Rust language adapter 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`, ...). Each
19//!    manifest's dependency tables say which workspace crates a crate can
20//!    reach. Without any manifest, the whole set is one crate named after
21//!    [`RustOptions::name`].
22//! 2. **Collect (per file, parallel).** Each file is parsed and reduced to
23//!    plain data: items, `use` tables, impl blocks and unresolved call flows.
24//! 3. **Resolve (whole workspace, sequential).** Paths are resolved through
25//!    local items, `use` imports (including renames, globs and `pub use`
26//!    re-exports), `crate`/`self`/`super`/`Self`, and sibling workspace crates.
27//!    Method calls are resolved from the receiver's declared or constructed
28//!    type (`self`, `self.field`, typed params, `let x = Foo::new()`, a
29//!    struct literal), and `Self::f(..)` from the enclosing impl's self type.
30//!    Calls in `match` guards are part of their arm.
31//!
32//! ## Ids
33//!
34//! Every definition gets a `sym:` id in the `cargo` package named after its
35//! crate (see `sealmap_extract::ids` for the full table):
36//! `sym:cargo shop . db/Db#insert().`. Binary, test, example and bench
37//! targets are packages of their own (`shop_main`, `test_it`, ...), so a
38//! binary and the library never share an id.
39//!
40//! ## Fingerprints
41//!
42//! Every symbol carries `sig_hash` (its contract) and `body_hash` (its
43//! implementation), computed with `sealmap_extract::fingerprint` from syn's
44//! token streams. Comments, doc comments, whitespace, lint attributes and the
45//! rewrites rustfmt makes (trailing commas, braces around a closure or match
46//! arm body, `use` order) never change them; neither does moving an item
47//! within or between files. Reflowing tokio, VisionClaw and sealmap itself
48//! with an aggressive rustfmt configuration changes no id and no
49//! fingerprint.
50//!
51//! ## What "resolved" means here
52//!
53//! There is no type checker. Every call and relation carries a
54//! [`Confidence`](sealmap_model::Confidence):
55//!
56//! * `exact`: resolved through explicit paths, imports or declared types to a
57//!   symbol defined in the analysed code;
58//! * `inferred`: matched by a weaker rule (a distinctive method name on an
59//!   unknown receiver, when exactly one method of that name lives in a crate
60//!   the caller can reach; or a method reached through deref). Two reachable
61//!   candidates are an ambiguity, and no edge is guessed;
62//! * `external`: outside the analysed code.
63//!
64//! Calls into `std`/`core`/`alloc`, prelude constructors (`Some`, `Ok`,
65//! `Vec::new` via `std`) and method calls on receivers of unknown type are
66//! dropped by default ([`ExternalCalls::NonStd`]), which keeps sequence
67//! diagrams dense: they show *your* code talking to itself and to its
68//! dependencies.
69//!
70//! ## Determinism
71//!
72//! Output depends only on the source set and options. Files are processed in
73//! path order, items in source order, and parallel parsing (feature
74//! `parallel`, on by default) collects results in input order, so the model
75//! is identical with or without it.
76//!
77//! ## Example
78//!
79//! ```
80//! use sealmap_model::{SourceSet, Step, SymbolId};
81//! use sealmap_rust::{RustOptions, extract};
82//!
83//! let mut src = SourceSet::new();
84//! src.insert("Cargo.toml", "[package]\nname = \"shop\"").unwrap();
85//! src.insert("src/lib.rs", r#"
86//!     pub mod db;
87//!     use db::Db;
88//!
89//!     /// Order service.
90//!     pub struct Orders { db: Db }
91//!
92//!     impl Orders {
93//!         pub fn place(&self, id: u64) -> Result<(), String> {
94//!             if self.db.exists(id) {
95//!                 return Err("dup".into());
96//!             }
97//!             self.db.insert(id)?;
98//!             Ok(())
99//!         }
100//!     }
101//! "#).unwrap();
102//! src.insert("src/db.rs", r#"
103//!     pub struct Db;
104//!     impl Db {
105//!         pub fn exists(&self, id: u64) -> bool { false }
106//!         pub fn insert(&self, id: u64) -> Result<(), String> { Ok(()) }
107//!     }
108//! "#).unwrap();
109//!
110//! let out = extract(&src, &RustOptions::default());
111//! let place = out.codebase.symbol(&SymbolId::parse("sym:cargo shop . Orders#place().").unwrap()).unwrap();
112//! let calls: Vec<_> = place.flow.as_ref().unwrap().calls().map(|c| c.target.to_string()).collect();
113//! assert_eq!(calls, ["sym:cargo shop . db/Db#exists().", "sym:cargo shop . db/Db#insert()."]);
114//! assert!(out.diagnostics.is_empty());
115//! ```
116
117#![forbid(unsafe_code)]
118#![deny(missing_docs)]
119
120mod collect;
121mod fingerprint;
122mod layout;
123mod raw;
124mod resolve;
125mod tidy;
126
127use std::path::Path;
128
129use sealmap_extract::isolate::{COLLECT_STACK_BYTES, map_isolated};
130use sealmap_model::{LoadOptions, SourcePath, SourceSet};
131
132pub use sealmap_extract::{Diagnostic, ExternalCalls, Extraction};
133
134/// Language adapter options.
135#[derive(Debug, Clone)]
136pub struct RustOptions {
137    /// Codebase name, also used as the crate name when no `Cargo.toml` is
138    /// present.
139    pub name: String,
140    /// Include `#[cfg(test)]` modules, `#[test]` functions and files under
141    /// `tests/`, `examples/` and `benches/`. Off by default.
142    pub include_tests: bool,
143    /// External call policy.
144    pub external_calls: ExternalCalls,
145}
146
147impl Default for RustOptions {
148    fn default() -> Self {
149        Self { name: "codebase".into(), include_tests: false, external_calls: ExternalCalls::NonStd }
150    }
151}
152
153/// Extract a [`Codebase`](sealmap_model::Codebase) from the `.rs` (and `Cargo.toml`) files in
154/// `sources`. Never fails: unparsable files are reported in
155/// [`Extraction::diagnostics`].
156pub fn extract(sources: &SourceSet, options: &RustOptions) -> Extraction {
157    let plan = layout::plan(sources, &options.name);
158    let jobs: Vec<_> = plan
159        .roles
160        .iter()
161        .filter(|(_, role)| options.include_tests || role.target <= layout::TargetKind::Bin)
162        .filter_map(|(path, role)| sources.get(path).map(|text| (path.clone(), role.clone(), text)))
163        .collect();
164
165    let files = collect_all(&jobs, options);
166
167    let (codebase, diagnostics) = resolve::build(&options.name, files, &plan, options);
168    Extraction { codebase, diagnostics }
169}
170
171type Job<'a> = (SourcePath, layout::FileRole, &'a str);
172
173/// Pass 1 over every file, isolated per file (big stacks, panic guard; see
174/// [`sealmap_extract::isolate`]). A panic while collecting one file degrades
175/// that file to a diagnostic instead of aborting the run.
176fn collect_all(jobs: &[Job<'_>], options: &RustOptions) -> Vec<raw::RawFile> {
177    map_isolated(
178        jobs,
179        COLLECT_STACK_BYTES,
180        |(p, r, t)| collect::collect_file(p, r, t, options),
181        |(p, r, t), why| collect::failed_file(p, r, t, format!("1:1: internal error while collecting: {why}")),
182    )
183}
184
185/// Load the `.rs` and `Cargo.toml` files under `root` (honouring
186/// `.gitignore`, skipping `target/`, hidden directories and the like) without
187/// extracting them.
188pub fn load_dir(root: &Path) -> std::io::Result<SourceSet> {
189    let load = LoadOptions { extensions: vec!["rs".into(), "toml".into()], ..LoadOptions::default() };
190    let mut sources = SourceSet::load_dir(root, &load)?;
191    sources.retain(|p| p.extension() == Some("rs") || p.file_name() == "Cargo.toml");
192    Ok(sources)
193}
194
195/// Load `root` from disk (`.rs` and `Cargo.toml` files, skipping `target/`,
196/// hidden directories and the like) and [`extract`] it.
197///
198/// [`RustOptions::name`] defaults to the directory name when left as
199/// `"codebase"`.
200pub fn extract_dir(root: &Path, options: &RustOptions) -> std::io::Result<(SourceSet, Extraction)> {
201    let sources = load_dir(root)?;
202    let mut options = options.clone();
203    if options.name == "codebase" {
204        if let Some(n) = root.canonicalize().ok().and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
205        {
206            options.name = n;
207        }
208    }
209    let extraction = extract(&sources, &options);
210    Ok((sources, extraction))
211}
212
213/// Compiles and runs the README examples as doctests.
214#[cfg(doctest)]
215#[doc = include_str!("../README.md")]
216struct ReadmeDoctests;