Skip to main content

composer_autoload/
lib.rs

1//! Generate Composer-compatible `vendor/composer/autoload_*.php`.
2//!
3//! Goal per `AUTOLOADER_PLAN.md`: byte-equivalent output to Composer's
4//! own `dump-autoload`, pinned to a specific upstream version (2.8.12
5//! as of the initial fixture set). Performance-first design: parallel
6//! file scan, SIMD byte search in the classmap pipeline, lazy I/O.
7//!
8//! **Status:** every file `composer dump-autoload` writes under
9//! `vendor/` is now emitted byte-equivalent across the fixtures in
10//! `tests/fixtures/`: `vendor/autoload.php`,
11//! `vendor/composer/autoload_{namespaces,psr4,classmap,files,real,static}.php`,
12//! the vendored `ClassLoader.php` / `InstalledVersions.php` / `LICENSE`,
13//! and `installed.{json,php}`. Conditional features wired in:
14//! `--optimize`, `--classmap-authoritative`, `--no-dev`,
15//! `--apcu-autoloader` (with explicit `apcu_prefix` override for
16//! tests), `config.autoloader-suffix` (composer.json override of the
17//! content-hash), and `config.platform-check` → `platform_check.php`
18//! (the PHP-version + extension guard, byte-equivalent to Composer; see
19//! `emit::platform_check`, built on `composer_semver`'s constraint
20//! lower-bound extraction).
21
22mod autoloader;
23mod collect;
24mod emit;
25mod installed;
26mod lock;
27mod scan;
28mod vendored;
29mod version;
30
31pub use autoloader::{AutoloadHeader, Autoloader, HeaderFlags, user_code_roots};
32
33/// Internal entry points exposed only so the in-tree
34/// `benches/scan.rs` criterion harness can call them. Not a stable
35/// API — names and signatures move with the implementation.
36#[doc(hidden)]
37pub mod bench_api {
38    pub fn clean(input: &[u8]) -> Vec<u8> {
39        crate::scan::cleaner::clean(input)
40    }
41    pub fn find_classes(input: &[u8]) -> Vec<String> {
42        crate::scan::finder::find_classes(input)
43    }
44}
45
46/// Internal entry points exposed only for the integration tests under
47/// `tests/`. Not a stable API.
48#[doc(hidden)]
49pub mod test_api {
50    pub fn normalize_version(input: &str) -> Result<String, String> {
51        crate::version::normalize(input).map_err(|e| e.to_string())
52    }
53}
54
55use std::path::Path;
56
57/// Pinned upstream Composer version that fixtures + byte-equivalence
58/// tests are generated against. Bump in lockstep with regenerating
59/// `tests/fixtures/`.
60pub const REFERENCE_COMPOSER_VERSION: &str = "2.8.12";
61
62/// PSR-noncompliance report for a single class. Composer prints one
63/// of these per rejected class when a file's classes all failed the
64/// `psr-4` / `psr-0` namespace+path rule: it drops every class in
65/// the file and warns. The caller collects them so it can render
66/// the same `Class X located in Y does not comply with psr-N
67/// autoloading standard. Skipping.` line.
68///
69/// `relative_path` is already prefixed with `./` to match Composer's
70/// `preg_replace('{^getcwd()}', '.', ...)` output. The string is
71/// rendered with forward slashes on every platform.
72#[derive(Debug, Clone)]
73pub struct PsrWarning {
74    pub class: String,
75    pub relative_path: String,
76    /// 0 for PSR-0, 4 for PSR-4 — used as the literal in the
77    /// rendered `psr-N` token.
78    pub psr_version: u8,
79}
80
81/// Summary returned by [`dump_autoload`]. `class_count` matches
82/// Composer's `containing N classes` figure: total entries in the
83/// emitted classmap (always includes the synthetic
84/// `Composer\InstalledVersions` row, mirroring Composer).
85#[derive(Debug, Clone)]
86pub struct DumpReport {
87    pub class_count: usize,
88    pub warnings: Vec<PsrWarning>,
89}
90
91/// Inputs for an autoload dump. Names mirror Composer terminology.
92#[derive(Debug, Clone)]
93pub struct DumpRequest<'a> {
94    /// Root project directory. `composer.json` + `composer.lock` are
95    /// read from here; the output is written under `vendor/` here.
96    pub project_root: &'a Path,
97    /// Whether to use the optimized classmap pipeline (`--optimize`).
98    pub optimize: bool,
99    /// Whether to emit the classmap-authoritative static loader
100    /// (`--classmap-authoritative`). Implies `optimize`.
101    pub classmap_authoritative: bool,
102    /// Whether to skip dev autoload entries (`--no-dev`).
103    pub no_dev: bool,
104    /// `--apcu-autoloader` — emits a `setApcuPrefix` call in
105    /// `autoload_real.php`. Has no effect unless the PHP runtime has
106    /// the `APCu` extension loaded; the line is a no-op otherwise.
107    pub apcu_autoloader: bool,
108    /// Explicit `APCu` prefix override (`--apcu-autoloader-prefix=X`).
109    /// When `apcu_autoloader` is true and this is None, Composer
110    /// generates a random `bin2hex(random_bytes(10))` prefix; the caller
111    /// does the same. Supply an explicit value for byte-equivalence
112    /// tests or to stabilize across dumps.
113    pub apcu_prefix: Option<String>,
114    /// `config.autoloader-suffix` override. When set, replaces both
115    /// the value read from `composer.json`'s `config` block and the
116    /// `composer.lock` content-hash as the
117    /// `ComposerAutoloaderInit<X>` / `ComposerStaticInit<X>` suffix.
118    pub autoloader_suffix: Option<String>,
119}
120
121#[derive(Debug)]
122pub enum DumpError {
123    Io(std::io::Error),
124    /// `composer.lock` is malformed or has a missing required field.
125    Lock(String),
126    /// Root `composer.json` is malformed.
127    Manifest(String),
128}
129
130impl std::fmt::Display for DumpError {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        match self {
133            Self::Io(e) => write!(f, "I/O error: {e}"),
134            Self::Lock(m) => write!(f, "composer.lock: {m}"),
135            Self::Manifest(m) => write!(f, "composer.json: {m}"),
136        }
137    }
138}
139
140impl std::error::Error for DumpError {
141    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
142        match self {
143            Self::Io(e) => Some(e),
144            _ => None,
145        }
146    }
147}
148
149impl From<std::io::Error> for DumpError {
150    fn from(e: std::io::Error) -> Self {
151        Self::Io(e)
152    }
153}
154
155/// Generate `vendor/composer/autoload_*.php` for the given project.
156///
157/// Thin wrapper around [`Autoloader::bootstrap`] + [`Autoloader::emit`].
158/// CLI callers (`composer dump-autoload`) and the in-process
159/// install path (`composer_install::install::orchestrate`)
160/// both use this. The long-running server holds an `Autoloader`
161/// directly so it can apply incremental edits without re-walking the
162/// whole project; see `INCREMENTAL_AUTOLOADER_PLAN.md`.
163#[tracing::instrument(skip_all)]
164pub fn dump_autoload(req: &DumpRequest<'_>) -> Result<DumpReport, DumpError> {
165    let loader = Autoloader::bootstrap(req)?;
166    loader.emit()?;
167    Ok(DumpReport {
168        class_count: loader.class_count(),
169        warnings: loader.warnings().to_vec(),
170    })
171}
172
173/// Format an absolute file path the way Composer does in its
174/// noncompliance warning: replace the leading project root with `.`
175/// (so output starts with `./`) and normalize to forward slashes for
176/// cross-platform-consistent display. Falls back to the input path
177/// when the prefix doesn't match (canonicalize mismatch, etc.).
178pub(crate) fn format_relative_path(file: &Path, project_root: &Path) -> String {
179    let canon_root = std::fs::canonicalize(project_root).unwrap_or_else(|_| project_root.into());
180    let rel = file.strip_prefix(&canon_root).unwrap_or(file);
181    let rel_str = rel.to_string_lossy().replace('\\', "/");
182    if rel_str.starts_with("./") || rel_str == "." {
183        rel_str
184    } else {
185        format!("./{rel_str}")
186    }
187}
188
189/// Lightweight ASCII-hex randomness for the `APCu` prefix default.
190/// Mirrors PHP's `bin2hex(random_bytes(n/2))`. `n` is the output
191/// length in hex chars (so `random_bytes(10)` → 20-char hex prefix).
192///
193/// Source of entropy: nanos-since-epoch XOR'd with the process ID
194/// and the address of a stack local — enough to avoid same-tick
195/// collisions on the same host. Composer itself uses a CSPRNG; the
196/// prefix's job is purely to namespace the `APCu` cache so two
197/// unrelated projects on the same SAPI don't share entries. For
198/// byte-equivalence tests, callers should pass an explicit
199/// `apcu_prefix` (no fallback to randomness then).
200fn random_hex_chars(n: usize) -> String {
201    use std::fmt::Write as _;
202    use std::time::{SystemTime, UNIX_EPOCH};
203
204    let local = 0u8;
205    let mut state: u128 = SystemTime::now()
206        .duration_since(UNIX_EPOCH)
207        .map_or(0, |d| d.as_nanos())
208        ^ u128::from(std::process::id())
209        ^ (std::ptr::addr_of!(local) as u128);
210
211    let mut out = String::with_capacity(n);
212    while out.len() < n {
213        // xorshift64-style step on each 64-bit half of the 128-bit
214        // state. We don't need crypto-grade output, just uncorrelated
215        // bytes for a cache-namespace tag.
216        state = state
217            .wrapping_mul(6_364_136_223_846_793_005)
218            .wrapping_add(1_442_695_040_888_963_407);
219        for byte in state.to_le_bytes() {
220            if out.len() >= n {
221                break;
222            }
223            let _ = write!(out, "{byte:02x}");
224        }
225    }
226    out.truncate(n);
227    out
228}
229
230fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
231    // Rename-based atomicity: write to <path>.tmp then rename.
232    // Cheap insurance against partial writes from interrupted runs.
233    let tmp = path.with_extension(format!(
234        "{}.tmp",
235        path.extension().and_then(|s| s.to_str()).unwrap_or("")
236    ));
237    std::fs::write(&tmp, bytes)?;
238    std::fs::rename(&tmp, path)?;
239    Ok(())
240}