rust-doctor 0.2.0

A unified code health tool for Rust — scan, score, and fix your codebase
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
use cargo_metadata::{DependencyKind, MetadataCommand, TargetKind};
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

/// Detected framework or runtime in the project's dependencies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Framework {
    Tokio,
    AsyncStd,
    Smol,
    Axum,
    ActixWeb,
    Rocket,
    Warp,
    Diesel,
    Sqlx,
    SeaOrm,
    Tonic,
    WasmBindgen,
    WebSys,
    Embassy,
    CortexM,
}

impl std::fmt::Display for Framework {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Tokio => write!(f, "tokio"),
            Self::AsyncStd => write!(f, "async-std"),
            Self::Smol => write!(f, "smol"),
            Self::Axum => write!(f, "axum"),
            Self::ActixWeb => write!(f, "actix-web"),
            Self::Rocket => write!(f, "rocket"),
            Self::Warp => write!(f, "warp"),
            Self::Diesel => write!(f, "diesel"),
            Self::Sqlx => write!(f, "sqlx"),
            Self::SeaOrm => write!(f, "sea-orm"),
            Self::Tonic => write!(f, "tonic"),
            Self::WasmBindgen => write!(f, "wasm-bindgen"),
            Self::WebSys => write!(f, "web-sys"),
            Self::Embassy => write!(f, "embassy"),
            Self::CortexM => write!(f, "cortex-m"),
        }
    }
}

/// Maps crate dependency names to Framework variants.
/// For prefix-based matching (embassy-*), see `detect_frameworks`.
const FRAMEWORK_MAP: &[(&str, Framework)] = &[
    ("tokio", Framework::Tokio),
    ("async-std", Framework::AsyncStd),
    ("smol", Framework::Smol),
    ("axum", Framework::Axum),
    ("actix-web", Framework::ActixWeb),
    ("rocket", Framework::Rocket),
    ("warp", Framework::Warp),
    ("diesel", Framework::Diesel),
    ("sqlx", Framework::Sqlx),
    ("sea-orm", Framework::SeaOrm),
    ("tonic", Framework::Tonic),
    ("wasm-bindgen", Framework::WasmBindgen),
    ("web-sys", Framework::WebSys),
    ("cortex-m", Framework::CortexM),
];

/// Discovered project information from cargo metadata.
#[derive(Debug)]
pub struct ProjectInfo {
    /// Absolute path to the workspace or project root.
    pub root_dir: PathBuf,
    /// Primary package name (first workspace member, or the single package).
    pub name: String,
    /// Primary package version.
    pub version: String,
    /// Rust edition of the primary package.
    pub edition: String,
    /// Detected frameworks/runtimes from dependencies.
    pub frameworks: Vec<Framework>,
    /// Whether this is a Cargo workspace (>1 member).
    pub is_workspace: bool,
    /// Number of workspace members.
    pub member_count: usize,
    /// Whether the primary package has a build script (build.rs).
    pub has_build_script: bool,
    /// The `rust-version` (MSRV) field, if specified.
    pub rust_version: Option<String>,
    /// Whether the project declares `#![no_std]`.
    pub is_no_std: bool,
    /// The `[package.metadata]` table from Cargo.toml (for config fallback).
    pub package_metadata: serde_json::Value,
    /// Workspace member names and their root directories.
    pub workspace_members: Vec<WorkspaceMember>,
}

/// A workspace member package.
#[derive(Debug, Clone)]
pub struct WorkspaceMember {
    /// Package name.
    pub name: String,
    /// Absolute path to the member's root directory (parent of Cargo.toml).
    pub root_dir: PathBuf,
}

/// Run cargo metadata and discover project characteristics.
///
/// `manifest_path` should point to the Cargo.toml file.
/// If `offline` is true, passes `--offline` to cargo to prevent network access.
/// Returns `Ok(ProjectInfo)` on success, or an error if cargo metadata fails.
pub fn discover_project(
    manifest_path: &Path,
    offline: bool,
) -> Result<ProjectInfo, crate::error::DiscoveryError> {
    use crate::error::DiscoveryError;

    let mut cmd = MetadataCommand::new();
    cmd.manifest_path(manifest_path).no_deps();
    if offline {
        cmd.other_options(["--offline".to_string()]);
    }
    let metadata = cmd
        .exec()
        .map_err(|source| DiscoveryError::CargoMetadata { source })?;

    let workspace_root = PathBuf::from(metadata.workspace_root.as_std_path());
    let members = metadata.workspace_packages();
    let member_count = members.len();
    let is_workspace = member_count > 1;

    // Use first workspace member as "primary" package
    let primary = members.first().ok_or(DiscoveryError::NoPackages)?;

    let name = primary.name.clone();
    let version = primary.version.to_string();
    let edition = primary.edition.as_str().to_string();
    let rust_version = primary
        .rust_version
        .as_ref()
        .map(std::string::ToString::to_string);

    // Detect build script
    let has_build_script = primary
        .targets
        .iter()
        .any(|t| t.kind.contains(&TargetKind::CustomBuild));

    // Collect all dependency names across all workspace members
    let all_dep_names: HashSet<&str> = members
        .iter()
        .flat_map(|pkg| {
            pkg.dependencies
                .iter()
                .filter(|d| d.kind == DependencyKind::Normal)
                .map(|d| d.name.as_str())
        })
        .collect();

    let frameworks = detect_frameworks(&all_dep_names);

    // Detect #![no_std] from primary package's lib.rs or main.rs
    let is_no_std = detect_no_std(primary);

    let package_metadata = primary.metadata.clone();

    // Collect workspace member info
    let workspace_members_info: Vec<WorkspaceMember> = members
        .iter()
        .map(|pkg| WorkspaceMember {
            name: pkg.name.clone(),
            root_dir: PathBuf::from(pkg.manifest_path.parent().map_or(
                workspace_root.as_path(),
                cargo_metadata::camino::Utf8Path::as_std_path,
            )),
        })
        .collect();

    Ok(ProjectInfo {
        root_dir: workspace_root,
        name,
        version,
        edition,
        frameworks,
        is_workspace,
        member_count,
        has_build_script,
        rust_version,
        is_no_std,
        package_metadata,
        workspace_members: workspace_members_info,
    })
}

/// Detect frameworks from dependency names.
fn detect_frameworks(dep_names: &HashSet<&str>) -> Vec<Framework> {
    let mut frameworks: Vec<Framework> = FRAMEWORK_MAP
        .iter()
        .filter(|(crate_name, _)| dep_names.contains(crate_name))
        .map(|(_, framework)| *framework)
        .collect();

    // Prefix-based detection for embassy-* crates
    if dep_names.iter().any(|name| name.starts_with("embassy-"))
        && !frameworks.contains(&Framework::Embassy)
    {
        frameworks.push(Framework::Embassy);
    }

    frameworks
}

/// Detect `#![no_std]` by scanning the primary source file's first 10 lines.
fn detect_no_std(pkg: &cargo_metadata::Package) -> bool {
    // Find lib or bin target's source path
    let src_path = pkg
        .targets
        .iter()
        .find(|t| {
            t.kind.contains(&TargetKind::Lib)
                || t.kind.contains(&TargetKind::RLib)
                || t.kind.contains(&TargetKind::Bin)
        })
        .map(|t| t.src_path.as_std_path());

    src_path.is_some_and(file_declares_no_std)
}

/// Returns `true` if the file declares `#![no_std]` in its first 10 lines.
fn file_declares_no_std(path: &Path) -> bool {
    let Ok(file) = File::open(path) else {
        return false;
    };
    let reader = BufReader::new(file);

    for line in reader.lines().take(10) {
        let Ok(line) = line else {
            break;
        };
        let trimmed = line.trim();
        // Check for #![no_std], tolerating internal whitespace like #![ no_std ]
        if trimmed
            .strip_prefix("#![")
            .and_then(|s| s.strip_suffix(']'))
            .is_some_and(|inner| inner.trim() == "no_std")
        {
            return true;
        }
    }
    false
}

/// Validate a directory, discover the project, and load file config.
///
/// Shared bootstrap logic used by both the CLI entry point and the MCP server.
/// Returns the canonicalized directory, project info, and file config.
pub fn bootstrap_project(
    directory: &Path,
    offline: bool,
) -> Result<(PathBuf, ProjectInfo, Option<crate::config::FileConfig>), crate::error::BootstrapError>
{
    let target_dir = directory.canonicalize().map_err(|source| {
        crate::error::BootstrapError::InvalidDirectory {
            path: directory.display().to_string(),
            source,
        }
    })?;

    let cargo_toml = target_dir.join("Cargo.toml");
    if !cargo_toml.try_exists().unwrap_or(false) {
        return Err(crate::error::BootstrapError::NoCargo { path: target_dir });
    }

    let project_info = discover_project(&cargo_toml, offline)?;

    let file_config = match crate::config::load_file_config(
        &project_info.root_dir,
        Some(&project_info.package_metadata),
    ) {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Warning: {e}\nUsing default configuration.");
            None
        }
    };

    Ok((target_dir, project_info, file_config))
}

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

    #[test]
    fn test_detect_frameworks_tokio() {
        let deps: HashSet<&str> = ["tokio", "serde"].into_iter().collect();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.contains(&Framework::Tokio));
        assert!(!frameworks.contains(&Framework::Axum));
    }

    #[test]
    fn test_detect_frameworks_web_stack() {
        let deps: HashSet<&str> = ["tokio", "axum", "sqlx", "serde"].into_iter().collect();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.contains(&Framework::Tokio));
        assert!(frameworks.contains(&Framework::Axum));
        assert!(frameworks.contains(&Framework::Sqlx));
    }

    #[test]
    fn test_detect_frameworks_embassy_prefix() {
        let deps: HashSet<&str> = ["embassy-executor", "embassy-time"].into_iter().collect();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.contains(&Framework::Embassy));
    }

    #[test]
    fn test_detect_frameworks_cortex_m() {
        let deps: HashSet<&str> = ["cortex-m", "cortex-m-rt"].into_iter().collect();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.contains(&Framework::CortexM));
    }

    #[test]
    fn test_detect_frameworks_empty() {
        let deps: HashSet<&str> = HashSet::new();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.is_empty());
    }

    #[test]
    fn test_detect_frameworks_no_match() {
        let deps: HashSet<&str> = ["serde", "rand", "log"].into_iter().collect();
        let frameworks = detect_frameworks(&deps);
        assert!(frameworks.is_empty());
    }

    #[test]
    fn test_file_declares_no_std_true() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("lib.rs");
        let mut f = File::create(&file_path).unwrap();
        writeln!(f, "#![no_std]").unwrap();
        writeln!(f, "pub fn hello() {{}}").unwrap();
        drop(f);

        assert!(file_declares_no_std(&file_path));
    }

    #[test]
    fn test_file_declares_no_std_false() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("lib.rs");
        let mut f = File::create(&file_path).unwrap();
        writeln!(f, "use std::io;").unwrap();
        writeln!(f, "pub fn hello() {{}}").unwrap();
        drop(f);

        assert!(!file_declares_no_std(&file_path));
    }

    #[test]
    fn test_file_declares_no_std_with_comments() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("lib.rs");
        let mut f = File::create(&file_path).unwrap();
        writeln!(f, "// Copyright 2026").unwrap();
        writeln!(f, "//! Crate documentation").unwrap();
        writeln!(f, "#![no_std]").unwrap();
        writeln!(f, "pub fn hello() {{}}").unwrap();
        drop(f);

        assert!(file_declares_no_std(&file_path));
    }

    #[test]
    fn test_file_declares_no_std_beyond_line_10() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("lib.rs");
        let mut f = File::create(&file_path).unwrap();
        for i in 1..=11 {
            writeln!(f, "// Line {i}").unwrap();
        }
        writeln!(f, "#![no_std]").unwrap();
        drop(f);

        // no_std is on line 12, beyond the 10-line scan window
        assert!(!file_declares_no_std(&file_path));
    }

    #[test]
    fn test_file_declares_no_std_nonexistent() {
        assert!(!file_declares_no_std(Path::new("/nonexistent/lib.rs")));
    }

    #[test]
    fn test_framework_display() {
        assert_eq!(Framework::Tokio.to_string(), "tokio");
        assert_eq!(Framework::ActixWeb.to_string(), "actix-web");
        assert_eq!(Framework::SeaOrm.to_string(), "sea-orm");
        assert_eq!(Framework::WasmBindgen.to_string(), "wasm-bindgen");
    }

    #[test]
    fn test_file_declares_no_std_with_internal_spaces() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("lib.rs");
        let mut f = File::create(&file_path).unwrap();
        writeln!(f, "#![ no_std ]").unwrap();
        drop(f);

        assert!(file_declares_no_std(&file_path));
    }

    #[test]
    fn test_discover_project_on_self() {
        // Run discovery on rust-doctor itself
        let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        let info = discover_project(&manifest, false).unwrap();

        assert_eq!(info.name, "rust-doctor");
        assert_eq!(info.version, env!("CARGO_PKG_VERSION"));
        assert_eq!(info.edition, "2024");
        assert!(!info.is_workspace);
        assert_eq!(info.member_count, 1);
        assert!(!info.has_build_script);
        assert!(!info.is_no_std);
        // rust-doctor depends on tokio (for MCP server)
        assert!(info.frameworks.contains(&Framework::Tokio));
    }

    #[test]
    fn test_discover_project_bad_path() {
        let result = discover_project(Path::new("/nonexistent/Cargo.toml"), false);
        assert!(result.is_err());
    }
}