roam-macros-core 7.1.0

Code generation core for roam RPC service macros
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
//! Crate name detection for proc-macros.
//!
//! This module provides functionality similar to `proc-macro-crate`, but uses
//! `facet-cargo-toml` for TOML parsing instead of `toml_edit`.

use std::{
    collections::BTreeMap,
    env, fmt,
    path::{Path, PathBuf},
    process::Command,
    sync::Mutex,
    time::SystemTime,
};

use facet_cargo_toml::{CargoToml, Dependency};

/// Error type for crate name detection.
pub enum Error {
    NotFound(PathBuf),
    CargoManifestDirNotSet,
    FailedGettingWorkspaceManifestPath,
    CouldNotRead { path: PathBuf, message: String },
    CrateNotFound { crate_name: String, path: PathBuf },
}

impl std::error::Error for Error {}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::NotFound(path) => {
                write!(
                    f,
                    "Could not find `Cargo.toml` in manifest dir: `{}`.",
                    path.display()
                )
            }
            Error::CargoManifestDirNotSet => {
                f.write_str("`CARGO_MANIFEST_DIR` env variable not set.")
            }
            Error::CouldNotRead { path, message } => {
                write!(f, "Could not read `{}`: {}", path.display(), message)
            }
            Error::CrateNotFound { crate_name, path } => write!(
                f,
                "Could not find `{}` in `dependencies` or `dev-dependencies` in `{}`!",
                crate_name,
                path.display(),
            ),
            Error::FailedGettingWorkspaceManifestPath => {
                f.write_str("Failed to get the path of the workspace manifest path.")
            }
        }
    }
}

/// The crate as found by [`crate_name`].
#[derive(Debug, PartialEq, Clone, Eq)]
pub enum FoundCrate {
    /// The searched crate is this crate itself.
    Itself,
    /// The searched crate was found with this name.
    Name(String),
}

// --- Caching infrastructure ---

type Cache = BTreeMap<String, CacheEntry>;

struct CacheEntry {
    manifest_ts: SystemTime,
    workspace_manifest_ts: SystemTime,
    workspace_manifest_path: PathBuf,
    crate_names: CrateNames,
}

type CrateNames = BTreeMap<String, FoundCrate>;

/// Find the crate name for the given `orig_name` in the current `Cargo.toml`.
///
/// `orig_name` should be the original name of the searched crate (e.g., `"roam-session"`).
///
/// The current `Cargo.toml` is determined by taking `CARGO_MANIFEST_DIR/Cargo.toml`.
///
/// # Returns
///
/// - `Ok(FoundCrate::Itself)` - the searched crate is the current crate being compiled.
/// - `Ok(FoundCrate::Name(new_name))` - the searched crate was found with the given name.
/// - `Err` if an error occurred.
pub fn crate_name(orig_name: &str) -> Result<FoundCrate, Error> {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").map_err(|_| Error::CargoManifestDirNotSet)?;
    let manifest_path = Path::new(&manifest_dir).join("Cargo.toml");

    let manifest_ts = cargo_toml_timestamp(&manifest_path)?;

    static CACHE: Mutex<Cache> = Mutex::new(BTreeMap::new());
    let mut cache = CACHE.lock().unwrap();

    let crate_names = match cache.entry(manifest_dir) {
        std::collections::btree_map::Entry::Occupied(entry) => {
            let cache_entry = entry.into_mut();
            let workspace_manifest_path = cache_entry.workspace_manifest_path.as_path();
            let workspace_manifest_ts = cargo_toml_timestamp(workspace_manifest_path)?;

            // Timestamp changed, rebuild this cache entry.
            if manifest_ts != cache_entry.manifest_ts
                || workspace_manifest_ts != cache_entry.workspace_manifest_ts
            {
                *cache_entry = read_cargo_toml(
                    &manifest_path,
                    workspace_manifest_path,
                    manifest_ts,
                    workspace_manifest_ts,
                )?;
            }

            &cache_entry.crate_names
        }
        std::collections::btree_map::Entry::Vacant(entry) => {
            let workspace_manifest_path =
                workspace_manifest_path(&manifest_path)?.unwrap_or_else(|| manifest_path.clone());
            let workspace_manifest_ts = cargo_toml_timestamp(&workspace_manifest_path)?;

            let cache_entry = entry.insert(read_cargo_toml(
                &manifest_path,
                &workspace_manifest_path,
                manifest_ts,
                workspace_manifest_ts,
            )?);
            &cache_entry.crate_names
        }
    };

    Ok(crate_names
        .get(orig_name)
        .ok_or_else(|| Error::CrateNotFound {
            crate_name: orig_name.to_owned(),
            path: manifest_path,
        })?
        .clone())
}

fn workspace_manifest_path(cargo_toml_manifest: &Path) -> Result<Option<PathBuf>, Error> {
    let Ok(cargo) = env::var("CARGO") else {
        return Ok(None);
    };

    let output = Command::new(cargo)
        .arg("locate-project")
        .args(["--workspace", "--message-format=plain"])
        .arg(format!("--manifest-path={}", cargo_toml_manifest.display()))
        .output()
        .map_err(|_| Error::FailedGettingWorkspaceManifestPath)?;

    String::from_utf8(output.stdout)
        .map_err(|_| Error::FailedGettingWorkspaceManifestPath)
        .map(|s| {
            let path = s.trim();
            if path.is_empty() {
                None
            } else {
                Some(path.into())
            }
        })
}

fn cargo_toml_timestamp(manifest_path: &Path) -> Result<SystemTime, Error> {
    std::fs::metadata(manifest_path)
        .and_then(|meta| meta.modified())
        .map_err(|source| {
            if source.kind() == std::io::ErrorKind::NotFound {
                Error::NotFound(manifest_path.to_owned())
            } else {
                Error::CouldNotRead {
                    path: manifest_path.to_owned(),
                    message: source.to_string(),
                }
            }
        })
}

fn read_cargo_toml(
    manifest_path: &Path,
    workspace_manifest_path: &Path,
    manifest_ts: SystemTime,
    workspace_manifest_ts: SystemTime,
) -> Result<CacheEntry, Error> {
    let manifest = open_cargo_toml(manifest_path)?;

    let workspace_dependencies = if manifest_path != workspace_manifest_path {
        let workspace_manifest = open_cargo_toml(workspace_manifest_path)?;
        extract_workspace_dependencies(&workspace_manifest)
    } else {
        extract_workspace_dependencies(&manifest)
    };

    let crate_names = extract_crate_names(&manifest, workspace_dependencies);

    Ok(CacheEntry {
        manifest_ts,
        workspace_manifest_ts,
        crate_names,
        workspace_manifest_path: workspace_manifest_path.to_path_buf(),
    })
}

fn open_cargo_toml(path: &Path) -> Result<CargoToml, Error> {
    // Convert std::path::Path to camino::Utf8Path
    let utf8_path = path.to_str().ok_or_else(|| Error::CouldNotRead {
        path: path.into(),
        message: "path is not valid UTF-8".to_owned(),
    })?;

    CargoToml::from_path(utf8_path).map_err(|e| Error::CouldNotRead {
        path: path.into(),
        message: e.to_string(),
    })
}

/// Extract workspace dependencies mapping dep_name -> package_name
fn extract_workspace_dependencies(workspace_toml: &CargoToml) -> BTreeMap<String, String> {
    let Some(workspace) = &workspace_toml.workspace else {
        return BTreeMap::new();
    };
    let Some(deps) = &workspace.dependencies else {
        return BTreeMap::new();
    };

    deps.iter()
        .map(|(dep_name, dep)| {
            let pkg_name = get_package_name(dep).unwrap_or(dep_name.as_str());
            (dep_name.clone(), pkg_name.to_owned())
        })
        .collect()
}

/// Get the actual package name from a dependency (handling `package = "..."` renames)
fn get_package_name(dep: &Dependency) -> Option<&str> {
    match dep {
        Dependency::Version(_) => None,
        Dependency::Workspace(_) => None,
        Dependency::Detailed(detail) => detail.package.as_ref().map(|s| s.value.as_str()),
    }
}

/// Check if this is a workspace dependency
fn is_workspace_dep(dep: &Dependency) -> bool {
    matches!(dep, Dependency::Workspace(_))
}

/// Make sure that the given crate name is a valid rust identifier.
fn sanitize_crate_name(name: &str) -> String {
    name.replace('-', "_")
}

/// Extract all crate names from dependencies
fn extract_crate_names(
    cargo_toml: &CargoToml,
    workspace_dependencies: BTreeMap<String, String>,
) -> CrateNames {
    let package_name = cargo_toml
        .package
        .as_ref()
        .and_then(|p| p.name.as_ref())
        .map(|s| s.value.as_str());

    // Check if we're building the crate itself
    let root_pkg = package_name.map(|name| {
        let cr = match env::var_os("CARGO_TARGET_TMPDIR") {
            // We're running for a library/binary crate
            None => FoundCrate::Itself,
            // We're running for an integration test
            Some(_) => FoundCrate::Name(sanitize_crate_name(name)),
        };
        (name.to_owned(), cr)
    });

    // Collect all dependency tables
    let mut all_deps: Vec<(&String, &Dependency)> = Vec::new();

    if let Some(deps) = &cargo_toml.dependencies {
        all_deps.extend(deps.iter());
    }
    if let Some(deps) = &cargo_toml.dev_dependencies {
        all_deps.extend(deps.iter());
    }
    if let Some(deps) = &cargo_toml.build_dependencies {
        all_deps.extend(deps.iter());
    }
    // Target-specific dependencies
    if let Some(targets) = &cargo_toml.target {
        for target_deps in targets.values() {
            if let Some(deps) = &target_deps.dependencies {
                all_deps.extend(deps.iter());
            }
            if let Some(deps) = &target_deps.dev_dependencies {
                all_deps.extend(deps.iter());
            }
            if let Some(deps) = &target_deps.build_dependencies {
                all_deps.extend(deps.iter());
            }
        }
    }

    let dep_pkgs = all_deps.into_iter().filter_map(|(dep_name, dep)| {
        let pkg_name = get_package_name(dep).unwrap_or(dep_name.as_str());

        // Skip if this is the root package (handled above)
        if package_name.is_some_and(|n| n == pkg_name) {
            return None;
        }

        // Resolve workspace dependencies
        let pkg_name = if is_workspace_dep(dep) {
            workspace_dependencies
                .get(pkg_name)
                .map(|p| p.as_str())
                .unwrap_or(pkg_name)
        } else {
            pkg_name
        };

        let cr = FoundCrate::Name(sanitize_crate_name(dep_name));
        Some((pkg_name.to_owned(), cr))
    });

    root_pkg.into_iter().chain(dep_pkgs).collect()
}

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

    fn parse_manifest(src: &str) -> CargoToml {
        CargoToml::parse(src).expect("manifest parse")
    }

    #[test]
    fn sanitize_crate_name_replaces_dashes() {
        assert_eq!(sanitize_crate_name("roam-session"), "roam_session");
        assert_eq!(sanitize_crate_name("already_clean"), "already_clean");
    }

    #[test]
    fn extract_workspace_dependencies_maps_alias_to_package_name() {
        let workspace = parse_manifest(
            r#"
            [workspace]
            [workspace.dependencies]
            foo = "1"
            alias = { version = "1", package = "real-crate" }
            "#,
        );

        let map = extract_workspace_dependencies(&workspace);
        assert_eq!(map.get("foo").expect("foo dep"), "foo");
        assert_eq!(map.get("alias").expect("alias dep"), "real-crate");
    }

    #[test]
    fn get_package_name_and_workspace_detection_work() {
        let manifest = parse_manifest(
            r#"
            [package]
            name = "demo"
            version = "0.1.0"

            [dependencies]
            v = "1"
            w = { workspace = true }
            d = { version = "1", package = "dep-real" }
            "#,
        );
        let deps = manifest.dependencies.as_ref().expect("dependencies table");
        let v = deps.get("v").expect("v");
        let w = deps.get("w").expect("w");
        let d = deps.get("d").expect("d");

        assert!(get_package_name(v).is_none());
        assert!(get_package_name(w).is_none());
        assert_eq!(get_package_name(d), Some("dep-real"));
        assert!(!is_workspace_dep(v));
        assert!(is_workspace_dep(w));
        assert!(!is_workspace_dep(d));
    }

    #[test]
    fn extract_crate_names_resolves_regular_renamed_and_workspace_deps() {
        let manifest = parse_manifest(
            r#"
            [package]
            name = "demo"
            version = "0.1.0"

            [dependencies]
            foo = "1"
            renamed = { version = "1", package = "real-renamed" }
            wsp = { workspace = true }
            "#,
        );

        let mut workspace = BTreeMap::new();
        workspace.insert("wsp".to_string(), "workspace-real".to_string());

        let names = extract_crate_names(&manifest, workspace);
        assert_eq!(names.get("foo"), Some(&FoundCrate::Name("foo".to_string())));
        assert_eq!(
            names.get("real-renamed"),
            Some(&FoundCrate::Name("renamed".to_string()))
        );
        assert_eq!(
            names.get("workspace-real"),
            Some(&FoundCrate::Name("wsp".to_string()))
        );
    }
}