Skip to main content

rust_anything/
library.rs

1//! Libraries (no `main`, no server): the front door is the library's public API as a Rust crate,
2//! `rust/app`, re-exporting each unit's `port.rs` once it is wired. Until the lift, the original
3//! package keeps its callers and reaches Rust through each unit's bindings and shadow drop-in,
4//! which honors the unit's kill switch.
5
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::{Context, Result, bail, ensure};
11use serde::{Deserialize, Serialize};
12
13use crate::app::{Failure, Fallback, Problem, ReplayOutcome};
14use crate::front_door::{APP_DIR, State, ident};
15use crate::lang::Lang;
16
17/// One unit of the library's public API, as `analyze` found it.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ApiUnit {
20    pub unit: String,
21    /// The module that re-exports it in `rust/app`.
22    pub module: String,
23    pub exports: Vec<String>,
24}
25
26/// The exported functions and classes of `files`, as `bridge` sees them.
27fn exports_of(root: &Path, lang: Lang, files: &[String]) -> Vec<String> {
28    let mut out = Vec::new();
29    for file in files {
30        let Ok(text) = std::fs::read_to_string(root.join(file)) else {
31            continue;
32        };
33        if lang == Lang::Ts {
34            out.extend(
35                crate::ts::exports::exported_functions(file, &text)
36                    .into_iter()
37                    .map(|f| f.name),
38            );
39            out.extend(
40                crate::ts::exports::exported_classes(file, &text)
41                    .into_iter()
42                    .map(|c| c.name),
43            );
44        } else {
45            let (functions, classes) = crate::lang::exports(lang, file, &text);
46            out.extend(functions.into_iter().map(|f| f.name));
47            out.extend(classes.into_iter().map(|c| c.name));
48        }
49    }
50    out
51}
52
53/// The public API: every unit that moves to Rust, with its exports.
54pub(crate) fn public_api(root: &Path, report: &crate::analyze::Report) -> Vec<ApiUnit> {
55    let mut taken = BTreeMap::new();
56    let mut out = Vec::new();
57    for unit in report
58        .units
59        .iter()
60        .filter(|u| u.status != crate::analyze::Status::Keep)
61    {
62        let exports = exports_of(root, report.language, &unit.files);
63        if exports.is_empty() {
64            continue;
65        }
66        let stem = unit
67            .id
68            .trim_end_matches('/')
69            .rsplit('/')
70            .next()
71            .unwrap_or(&unit.id);
72        let stem = stem.split('.').next().unwrap_or(stem);
73        let mut module = ident(stem);
74        let n = taken.entry(module.clone()).or_insert(0);
75        *n += 1;
76        if *n > 1 {
77            module = format!("{module}_{n}");
78        }
79        out.push(ApiUnit {
80            unit: unit.id.clone(),
81            module,
82            exports,
83        });
84    }
85    out
86}
87
88pub(crate) fn cargo_toml(package: &str, name: &str) -> String {
89    format!(
90        "[package]\nname = \"{package}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
91         description = \"`{name}`'s public API in Rust, generated by rust-anything: each unit's port, re-exported\"\n\n\
92         [lib]\npath = \"src/lib.rs\"\n\n\
93         [dependencies]\n\n\
94         [workspace]\n"
95    )
96}
97
98/// `rust/app/src/lib.rs`: the wired units' ports, one module each.
99pub(crate) fn lib_rs(state: &State, lifted: bool) -> String {
100    let mut out = if lifted {
101        format!(
102            "//! `{}`'s public API in Rust. Written by `rust-anything app lift`: every unit is a plain\n\
103             //! Rust library here.\n",
104            state.name
105        )
106    } else {
107        format!(
108            "//! `{}`'s public API in Rust. Generated by `rust-anything app wire` from rust-anything.json;\n\
109             //! it is rewritten on every wire until the lift.\n",
110            state.name
111        )
112    };
113    let wired = |api: &ApiUnit| {
114        state
115            .units
116            .iter()
117            .find(|u| u.unit.as_deref() == Some(&api.unit))
118    };
119    let pending: Vec<String> = state
120        .api
121        .iter()
122        .filter(|a| wired(a).is_none())
123        .map(|a| format!("`{}`", a.unit))
124        .collect();
125    if !pending.is_empty() {
126        out += &format!(
127            "//!\n//! Still only in the original: {}.\n",
128            pending.join(", ")
129        );
130    }
131    out.push('\n');
132    for api in &state.api {
133        if let Some(unit) = wired(api) {
134            out += &format!(
135                "pub use {}::port as {};\n",
136                unit.crate_name.replace('-', "_"),
137                api.module
138            );
139        }
140    }
141    out
142}
143
144pub(crate) const CARGO_CONFIG: &str = ".cargo/config.toml";
145
146/// A PyO3 unit's `cdylib` gets linked when `rust/app` depends on it; on macOS the Python symbols
147/// are only there at load time.
148pub(crate) fn allow_python_symbols(app_dir: &Path) -> Result<()> {
149    let path = app_dir.join(CARGO_CONFIG);
150    if path.exists() {
151        return Ok(());
152    }
153    std::fs::create_dir_all(app_dir.join(".cargo"))?;
154    std::fs::write(
155        &path,
156        "[target.'cfg(target_os = \"macos\")']
157         rustflags = [\"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]
158",
159    )?;
160    Ok(())
161}
162
163pub(crate) fn cargo_build_lib(app_dir: &Path, target_dir: Option<&Path>) -> Result<()> {
164    let mut cmd = Command::new("cargo");
165    cmd.args(["build", "--quiet", "--manifest-path"])
166        .arg(app_dir.join("Cargo.toml"))
167        .current_dir(app_dir);
168    if let Some(dir) = target_dir {
169        cmd.env("CARGO_TARGET_DIR", dir);
170    }
171    let out = crate::process::output(&mut cmd, crate::process::BUILD).context("running cargo")?;
172    ensure!(
173        out.status.success(),
174        "cargo build in {} failed:\n{}",
175        app_dir.display(),
176        String::from_utf8_lossy(&out.stderr)
177    );
178    Ok(())
179}
180
181/// The public API exports Rust does not answer yet: unwired units, and exports kept in the
182/// original language.
183pub(crate) fn pending(state: &State) -> Vec<String> {
184    let mut out = Vec::new();
185    for api in &state.api {
186        let wired = state
187            .units
188            .iter()
189            .find(|u| u.unit.as_deref() == Some(&api.unit));
190        for name in &api.exports {
191            if wired.is_none_or(|u| u.kept.contains(name)) {
192                out.push(format!("{}: {name}", api.unit));
193            }
194        }
195    }
196    out
197}
198
199/// The recorded cases of every wired unit, through its bindings (`diff`), and the share of the
200/// API still answered by the original.
201pub(crate) fn replay(repo: &Path, state: &State, unit: Option<&str>) -> Result<ReplayOutcome> {
202    crate::app::write_report(crate::app::grouped(replay_unwritten(repo, state, unit)?))
203}
204
205/// `replay` without writing the report.
206pub(crate) fn replay_unwritten(
207    repo: &Path,
208    state: &State,
209    unit: Option<&str>,
210) -> Result<ReplayOutcome> {
211    let app_dir = repo.join(APP_DIR);
212    let mut outcome = ReplayOutcome {
213        build: vec!["the units' bindings".to_string()],
214        passed: 0,
215        total: 0,
216        skipped: 0,
217        failures: Vec::new(),
218        fallback: None,
219        report: app_dir.join(crate::app::REPORT_FILE),
220        groups: Vec::new(),
221    };
222    let units = crate::app::only_case(state.units.iter().collect(), unit, |u| &u.name)?;
223    for unit in units {
224        let crate_dir = app_dir.join(&unit.path);
225        match crate::harness::diff(&crate::harness::DiffOptions {
226            crate_dir: &crate_dir,
227            module: None,
228            ignore_key_order: false,
229            float_tolerance: None,
230            node_args: &[],
231        }) {
232            Ok(d) => {
233                outcome.total += d.total;
234                outcome.passed += d.passed;
235                for m in &d.mismatches {
236                    let args = m["args"]
237                        .as_array()
238                        .map(|a| a.iter().map(ToString::to_string).collect())
239                        .unwrap_or_default();
240                    outcome.failures.push(Failure {
241                        case: format!("{}: {}", unit.name, m["fn"].as_str().unwrap_or("?")),
242                        args,
243                        problems: vec![{
244                            let p = Problem::new(
245                                "result",
246                                format!("- {}\n+ {}\n", m["expected"], m["actual"]),
247                            );
248                            match serde_json::from_value(m["at"].clone()) {
249                                Ok(at) => p.at(at),
250                                Err(_) => p,
251                            }
252                        }],
253                    });
254                }
255                if !d.missing.is_empty() {
256                    outcome.total += 1;
257                    outcome.failures.push(Failure {
258                        case: format!("{}: api", unit.name),
259                        args: Vec::new(),
260                        problems: vec![
261                            Problem::new("exports", format!("missing: {}\n", d.missing.join(", ")))
262                                .at(crate::mismatch::At::new("missing key")),
263                        ],
264                    });
265                }
266            }
267            Err(e) => {
268                outcome.total += 1;
269                outcome.failures.push(Failure {
270                    case: unit.name.clone(),
271                    args: Vec::new(),
272                    problems: vec![
273                        Problem::new(
274                            "replay",
275                            format!(
276                                "{e:#}\n(build it first: rust-anything build {})\n",
277                                crate_dir.display()
278                            ),
279                        )
280                        .at(crate::mismatch::At::new("no response")),
281                    ],
282                });
283            }
284        }
285    }
286    let names = pending(state);
287    let exports: usize = state.api.iter().map(|a| a.exports.len()).sum();
288    outcome.fallback = Some(Fallback {
289        cases: names.len(),
290        total: exports,
291        rate: names.len() as f64 / exports.max(1) as f64,
292        names,
293    });
294    Ok(outcome)
295}
296
297/// Files of the original that name a unit's bindings or shadow: after the lift those are gone.
298pub(crate) fn original_references(repo: &Path, state: &State) -> Vec<String> {
299    let needles: Vec<String> = state
300        .units
301        .iter()
302        .flat_map(|u| [u.crate_name.clone(), u.crate_name.replace('-', "_")])
303        .collect();
304    let mut out = Vec::new();
305    let walker = crate::walk::filtered(repo, |e| {
306        !matches!(
307            e.file_name().to_string_lossy().as_ref(),
308            "rust" | "target" | "node_modules" | ".git"
309        )
310    })
311    .build();
312    for entry in walker.flatten() {
313        let path = entry.path();
314        if !path.is_file() || std::fs::metadata(path).is_ok_and(|m| m.len() > 1 << 20) {
315            continue;
316        }
317        let Ok(text) = std::fs::read_to_string(path) else {
318            continue;
319        };
320        if needles.iter().any(|n| text.contains(n.as_str())) {
321            out.push(
322                path.strip_prefix(repo)
323                    .unwrap_or(path)
324                    .to_string_lossy()
325                    .into_owned(),
326            );
327        }
328    }
329    out.sort();
330    out
331}
332
333/// The unit a library crate ports, checked against the public API.
334pub(crate) fn api_unit<'s>(state: &'s State, unit: &str) -> Result<&'s ApiUnit> {
335    let wanted = unit.trim_end_matches('/');
336    match state
337        .api
338        .iter()
339        .find(|a| a.unit.trim_end_matches('/') == wanted)
340    {
341        Some(a) => Ok(a),
342        None => bail!(
343            "`{unit}` is not part of the public API (units: {})",
344            state
345                .api
346                .iter()
347                .map(|a| a.unit.as_str())
348                .collect::<Vec<_>>()
349                .join(", ")
350        ),
351    }
352}
353
354/// The shadow drop-in for a crate: written once, then kept.
355pub(crate) fn shadow_for(crate_dir: &Path, previous: Option<&str>) -> Result<Option<PathBuf>> {
356    if let Some(p) = previous {
357        return Ok(Some(PathBuf::from(p)));
358    }
359    match crate::shadow::shadow(crate_dir, None) {
360        Ok(o) => Ok(Some(o.path)),
361        Err(e) if format!("{e:#}").contains("exists") => Ok(None),
362        Err(e) => Err(e),
363    }
364}