tidy/
deps.rs

1//! Checks the licenses of third-party dependencies.
2
3use std::collections::{HashMap, HashSet};
4use std::fs::{File, read_dir};
5use std::io::Write;
6use std::path::Path;
7
8use build_helper::ci::CiEnv;
9use cargo_metadata::semver::Version;
10use cargo_metadata::{Metadata, Package, PackageId};
11
12#[path = "../../../bootstrap/src/utils/proc_macro_deps.rs"]
13mod proc_macro_deps;
14
15/// These are licenses that are allowed for all crates, including the runtime,
16/// rustc, tools, etc.
17#[rustfmt::skip]
18const LICENSES: &[&str] = &[
19    // tidy-alphabetical-start
20    "(MIT OR Apache-2.0) AND Unicode-3.0",                 // unicode_ident (1.0.14)
21    "(MIT OR Apache-2.0) AND Unicode-DFS-2016",            // unicode_ident (1.0.12)
22    "0BSD OR MIT OR Apache-2.0",                           // adler2 license
23    "0BSD",
24    "Apache-2.0 / MIT",
25    "Apache-2.0 OR ISC OR MIT",
26    "Apache-2.0 OR MIT",
27    "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT", // wasi license
28    "Apache-2.0",
29    "Apache-2.0/MIT",
30    "BSD-2-Clause OR Apache-2.0 OR MIT",                   // zerocopy
31    "ISC",
32    "MIT / Apache-2.0",
33    "MIT AND (MIT OR Apache-2.0)",
34    "MIT AND Apache-2.0 WITH LLVM-exception AND (MIT OR Apache-2.0)", // compiler-builtins
35    "MIT OR Apache-2.0 OR LGPL-2.1-or-later",              // r-efi, r-efi-alloc
36    "MIT OR Apache-2.0 OR Zlib",                           // tinyvec_macros
37    "MIT OR Apache-2.0",
38    "MIT OR Zlib OR Apache-2.0",                           // miniz_oxide
39    "MIT",
40    "MIT/Apache-2.0",
41    "Unicode-3.0",                                         // icu4x
42    "Unicode-DFS-2016",                                    // tinystr
43    "Unlicense OR MIT",
44    "Unlicense/MIT",
45    "Zlib OR Apache-2.0 OR MIT",                           // tinyvec
46    // tidy-alphabetical-end
47];
48
49type ExceptionList = &'static [(&'static str, &'static str)];
50
51/// The workspaces to check for licensing and optionally permitted dependencies.
52///
53/// Each entry consists of a tuple with the following elements:
54///
55/// * The path to the workspace root Cargo.toml file.
56/// * The list of license exceptions.
57/// * Optionally a tuple of:
58///     * A list of crates for which dependencies need to be explicitly allowed.
59///     * The list of allowed dependencies.
60/// * Submodules required for the workspace.
61// FIXME auto detect all cargo workspaces
62pub(crate) const WORKSPACES: &[(&str, ExceptionList, Option<(&[&str], &[&str])>, &[&str])] = &[
63    // The root workspace has to be first for check_rustfix to work.
64    (".", EXCEPTIONS, Some((&["rustc-main"], PERMITTED_RUSTC_DEPENDENCIES)), &[]),
65    ("library", EXCEPTIONS_STDLIB, Some((&["sysroot"], PERMITTED_STDLIB_DEPENDENCIES)), &[]),
66    // Outside of the alphabetical section because rustfmt formats it using multiple lines.
67    (
68        "compiler/rustc_codegen_cranelift",
69        EXCEPTIONS_CRANELIFT,
70        Some((&["rustc_codegen_cranelift"], PERMITTED_CRANELIFT_DEPENDENCIES)),
71        &[],
72    ),
73    // tidy-alphabetical-start
74    ("compiler/rustc_codegen_gcc", EXCEPTIONS_GCC, None, &[]),
75    ("src/bootstrap", EXCEPTIONS_BOOTSTRAP, None, &[]),
76    ("src/tools/cargo", EXCEPTIONS_CARGO, None, &["src/tools/cargo"]),
77    //("src/tools/miri/test-cargo-miri", &[], None), // FIXME uncomment once all deps are vendored
78    //("src/tools/miri/test_dependencies", &[], None), // FIXME uncomment once all deps are vendored
79    ("src/tools/rust-analyzer", EXCEPTIONS_RUST_ANALYZER, None, &[]),
80    ("src/tools/rustbook", EXCEPTIONS_RUSTBOOK, None, &["src/doc/book", "src/doc/reference"]),
81    ("src/tools/rustc-perf", EXCEPTIONS_RUSTC_PERF, None, &["src/tools/rustc-perf"]),
82    ("src/tools/test-float-parse", EXCEPTIONS, None, &[]),
83    ("tests/run-make-cargo/uefi-qemu/uefi_qemu_test", EXCEPTIONS_UEFI_QEMU_TEST, None, &[]),
84    // tidy-alphabetical-end
85];
86
87/// These are exceptions to Rust's permissive licensing policy, and
88/// should be considered bugs. Exceptions are only allowed in Rust
89/// tooling. It is _crucial_ that no exception crates be dependencies
90/// of the Rust runtime (std/test).
91#[rustfmt::skip]
92const EXCEPTIONS: ExceptionList = &[
93    // tidy-alphabetical-start
94    ("ar_archive_writer", "Apache-2.0 WITH LLVM-exception"), // rustc
95    ("arrayref", "BSD-2-Clause"),                            // rustc
96    ("blake3", "CC0-1.0 OR Apache-2.0 OR Apache-2.0 WITH LLVM-exception"),  // rustc
97    ("colored", "MPL-2.0"),                                  // rustfmt
98    ("constant_time_eq", "CC0-1.0 OR MIT-0 OR Apache-2.0"),  // rustc
99    ("dissimilar", "Apache-2.0"),                            // rustdoc, rustc_lexer (few tests) via expect-test, (dev deps)
100    ("fluent-langneg", "Apache-2.0"),                        // rustc (fluent translations)
101    ("foldhash", "Zlib"),                                    // rustc
102    ("option-ext", "MPL-2.0"),                               // cargo-miri (via `directories`)
103    ("rustc_apfloat", "Apache-2.0 WITH LLVM-exception"),     // rustc (license is the same as LLVM uses)
104    ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0                       // cargo/... (because of serde)
105    ("self_cell", "Apache-2.0"),                             // rustc (fluent translations)
106    ("wasi-preview1-component-adapter-provider", "Apache-2.0 WITH LLVM-exception"), // rustc
107    // tidy-alphabetical-end
108];
109
110/// These are exceptions to Rust's permissive licensing policy, and
111/// should be considered bugs. Exceptions are only allowed in Rust
112/// tooling. It is _crucial_ that no exception crates be dependencies
113/// of the Rust runtime (std/test).
114#[rustfmt::skip]
115const EXCEPTIONS_STDLIB: ExceptionList = &[
116    // tidy-alphabetical-start
117    ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target. FIXME: this dependency violates the documentation comment above.
118    // tidy-alphabetical-end
119];
120
121const EXCEPTIONS_CARGO: ExceptionList = &[
122    // tidy-alphabetical-start
123    ("arrayref", "BSD-2-Clause"),
124    ("bitmaps", "MPL-2.0+"),
125    ("blake3", "CC0-1.0 OR Apache-2.0 OR Apache-2.0 WITH LLVM-exception"),
126    ("ciborium", "Apache-2.0"),
127    ("ciborium-io", "Apache-2.0"),
128    ("ciborium-ll", "Apache-2.0"),
129    ("constant_time_eq", "CC0-1.0 OR MIT-0 OR Apache-2.0"),
130    ("dunce", "CC0-1.0 OR MIT-0 OR Apache-2.0"),
131    ("encoding_rs", "(Apache-2.0 OR MIT) AND BSD-3-Clause"),
132    ("fiat-crypto", "MIT OR Apache-2.0 OR BSD-1-Clause"),
133    ("foldhash", "Zlib"),
134    ("im-rc", "MPL-2.0+"),
135    ("libz-rs-sys", "Zlib"),
136    ("normalize-line-endings", "Apache-2.0"),
137    ("openssl", "Apache-2.0"),
138    ("ring", "Apache-2.0 AND ISC"),
139    ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0
140    ("similar", "Apache-2.0"),
141    ("sized-chunks", "MPL-2.0+"),
142    ("subtle", "BSD-3-Clause"),
143    ("supports-hyperlinks", "Apache-2.0"),
144    ("unicode-bom", "Apache-2.0"),
145    ("zlib-rs", "Zlib"),
146    // tidy-alphabetical-end
147];
148
149const EXCEPTIONS_RUST_ANALYZER: ExceptionList = &[
150    // tidy-alphabetical-start
151    ("dissimilar", "Apache-2.0"),
152    ("foldhash", "Zlib"),
153    ("notify", "CC0-1.0"),
154    ("option-ext", "MPL-2.0"),
155    ("pulldown-cmark-to-cmark", "Apache-2.0"),
156    ("rustc_apfloat", "Apache-2.0 WITH LLVM-exception"),
157    ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0
158    ("scip", "Apache-2.0"),
159    // tidy-alphabetical-end
160];
161
162const EXCEPTIONS_RUSTC_PERF: ExceptionList = &[
163    // tidy-alphabetical-start
164    ("alloc-no-stdlib", "BSD-3-Clause"),
165    ("alloc-stdlib", "BSD-3-Clause"),
166    ("brotli", "BSD-3-Clause/MIT"),
167    ("brotli-decompressor", "BSD-3-Clause/MIT"),
168    ("encoding_rs", "(Apache-2.0 OR MIT) AND BSD-3-Clause"),
169    ("inferno", "CDDL-1.0"),
170    ("option-ext", "MPL-2.0"),
171    ("ryu", "Apache-2.0 OR BSL-1.0"),
172    ("snap", "BSD-3-Clause"),
173    ("subtle", "BSD-3-Clause"),
174    // tidy-alphabetical-end
175];
176
177const EXCEPTIONS_RUSTBOOK: ExceptionList = &[
178    // tidy-alphabetical-start
179    ("cssparser", "MPL-2.0"),
180    ("cssparser-macros", "MPL-2.0"),
181    ("dtoa-short", "MPL-2.0"),
182    ("mdbook", "MPL-2.0"),
183    ("ryu", "Apache-2.0 OR BSL-1.0"),
184    // tidy-alphabetical-end
185];
186
187const EXCEPTIONS_CRANELIFT: ExceptionList = &[
188    // tidy-alphabetical-start
189    ("cranelift-assembler-x64", "Apache-2.0 WITH LLVM-exception"),
190    ("cranelift-assembler-x64-meta", "Apache-2.0 WITH LLVM-exception"),
191    ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"),
192    ("cranelift-bitset", "Apache-2.0 WITH LLVM-exception"),
193    ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"),
194    ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"),
195    ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"),
196    ("cranelift-control", "Apache-2.0 WITH LLVM-exception"),
197    ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"),
198    ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"),
199    ("cranelift-isle", "Apache-2.0 WITH LLVM-exception"),
200    ("cranelift-jit", "Apache-2.0 WITH LLVM-exception"),
201    ("cranelift-module", "Apache-2.0 WITH LLVM-exception"),
202    ("cranelift-native", "Apache-2.0 WITH LLVM-exception"),
203    ("cranelift-object", "Apache-2.0 WITH LLVM-exception"),
204    ("cranelift-srcgen", "Apache-2.0 WITH LLVM-exception"),
205    ("foldhash", "Zlib"),
206    ("mach2", "BSD-2-Clause OR MIT OR Apache-2.0"),
207    ("regalloc2", "Apache-2.0 WITH LLVM-exception"),
208    ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
209    ("wasmtime-jit-icache-coherence", "Apache-2.0 WITH LLVM-exception"),
210    ("wasmtime-math", "Apache-2.0 WITH LLVM-exception"),
211    // tidy-alphabetical-end
212];
213
214const EXCEPTIONS_GCC: ExceptionList = &[
215    // tidy-alphabetical-start
216    ("gccjit", "GPL-3.0"),
217    ("gccjit_sys", "GPL-3.0"),
218    // tidy-alphabetical-end
219];
220
221const EXCEPTIONS_BOOTSTRAP: ExceptionList = &[
222    ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde. BSL is not acceptble, but we use it under Apache-2.0
223];
224
225const EXCEPTIONS_UEFI_QEMU_TEST: ExceptionList = &[
226    ("r-efi", "MIT OR Apache-2.0 OR LGPL-2.1-or-later"), // LGPL is not acceptable, but we use it under MIT OR Apache-2.0
227];
228
229const PERMITTED_DEPS_LOCATION: &str = concat!(file!(), ":", line!());
230
231/// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
232///
233/// This list is here to provide a speed-bump to adding a new dependency to
234/// rustc. Please check with the compiler team before adding an entry.
235const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
236    // tidy-alphabetical-start
237    "adler2",
238    "aho-corasick",
239    "allocator-api2", // FIXME: only appears in Cargo.lock due to https://github.com/rust-lang/cargo/issues/10801
240    "annotate-snippets",
241    "anstyle",
242    "ar_archive_writer",
243    "arrayref",
244    "arrayvec",
245    "autocfg",
246    "bitflags",
247    "blake3",
248    "block-buffer",
249    "bstr",
250    "cc",
251    "cfg-if",
252    "cfg_aliases",
253    "constant_time_eq",
254    "cpufeatures",
255    "crc32fast",
256    "crossbeam-deque",
257    "crossbeam-epoch",
258    "crossbeam-utils",
259    "crypto-common",
260    "ctrlc",
261    "darling",
262    "darling_core",
263    "darling_macro",
264    "datafrog",
265    "derive-where",
266    "derive_setters",
267    "digest",
268    "displaydoc",
269    "dissimilar",
270    "dyn-clone",
271    "either",
272    "elsa",
273    "ena",
274    "equivalent",
275    "errno",
276    "expect-test",
277    "fallible-iterator", // dependency of `thorin`
278    "fastrand",
279    "flate2",
280    "fluent-bundle",
281    "fluent-langneg",
282    "fluent-syntax",
283    "fnv",
284    "foldhash",
285    "generic-array",
286    "getopts",
287    "getrandom",
288    "gimli",
289    "gsgdt",
290    "hashbrown",
291    "icu_collections",
292    "icu_list",
293    "icu_locale",
294    "icu_locale_core",
295    "icu_locale_data",
296    "icu_provider",
297    "ident_case",
298    "indexmap",
299    "intl-memoizer",
300    "intl_pluralrules",
301    "itertools",
302    "itoa",
303    "jiff",
304    "jiff-static",
305    "jobserver",
306    "lazy_static",
307    "leb128",
308    "libc",
309    "libloading",
310    "linux-raw-sys",
311    "litemap",
312    "lock_api",
313    "log",
314    "matchers",
315    "md-5",
316    "measureme",
317    "memchr",
318    "memmap2",
319    "miniz_oxide",
320    "nix",
321    "nu-ansi-term",
322    "object",
323    "odht",
324    "once_cell",
325    "overload",
326    "parking_lot",
327    "parking_lot_core",
328    "pathdiff",
329    "perf-event-open-sys",
330    "pin-project-lite",
331    "polonius-engine",
332    "portable-atomic", // dependency for platforms doesn't support `AtomicU64` in std
333    "portable-atomic-util",
334    "potential_utf",
335    "ppv-lite86",
336    "proc-macro-hack",
337    "proc-macro2",
338    "psm",
339    "pulldown-cmark",
340    "pulldown-cmark-escape",
341    "punycode",
342    "quote",
343    "r-efi",
344    "rand",
345    "rand_chacha",
346    "rand_core",
347    "rand_xorshift", // dependency for doc-tests in rustc_thread_pool
348    "rand_xoshiro",
349    "redox_syscall",
350    "ref-cast",
351    "ref-cast-impl",
352    "regex",
353    "regex-automata",
354    "regex-syntax",
355    "rustc-demangle",
356    "rustc-hash",
357    "rustc-literal-escaper",
358    "rustc-stable-hash",
359    "rustc_apfloat",
360    "rustix",
361    "ruzstd", // via object in thorin-dwp
362    "ryu",
363    "schemars",
364    "schemars_derive",
365    "scoped-tls",
366    "scopeguard",
367    "self_cell",
368    "serde",
369    "serde_derive",
370    "serde_derive_internals",
371    "serde_json",
372    "serde_path_to_error",
373    "sha1",
374    "sha2",
375    "sharded-slab",
376    "shlex",
377    "smallvec",
378    "stable_deref_trait",
379    "stacker",
380    "static_assertions",
381    "strsim",
382    "syn",
383    "synstructure",
384    "tempfile",
385    "termcolor",
386    "termize",
387    "thin-vec",
388    "thiserror",
389    "thiserror-impl",
390    "thorin-dwp",
391    "thread_local",
392    "tikv-jemalloc-sys",
393    "tinystr",
394    "tinyvec",
395    "tinyvec_macros",
396    "tracing",
397    "tracing-attributes",
398    "tracing-core",
399    "tracing-log",
400    "tracing-subscriber",
401    "tracing-tree",
402    "twox-hash",
403    "type-map",
404    "typenum",
405    "unic-langid",
406    "unic-langid-impl",
407    "unic-langid-macros",
408    "unic-langid-macros-impl",
409    "unicase",
410    "unicode-ident",
411    "unicode-normalization",
412    "unicode-properties",
413    "unicode-script",
414    "unicode-security",
415    "unicode-width",
416    "unicode-xid",
417    "valuable",
418    "version_check",
419    "wasi",
420    "wasm-encoder",
421    "wasmparser",
422    "winapi",
423    "winapi-i686-pc-windows-gnu",
424    "winapi-util",
425    "winapi-x86_64-pc-windows-gnu",
426    "windows",
427    "windows-collections",
428    "windows-core",
429    "windows-future",
430    "windows-implement",
431    "windows-interface",
432    "windows-link",
433    "windows-numerics",
434    "windows-result",
435    "windows-strings",
436    "windows-sys",
437    "windows-targets",
438    "windows-threading",
439    "windows_aarch64_gnullvm",
440    "windows_aarch64_msvc",
441    "windows_i686_gnu",
442    "windows_i686_gnullvm",
443    "windows_i686_msvc",
444    "windows_x86_64_gnu",
445    "windows_x86_64_gnullvm",
446    "windows_x86_64_msvc",
447    "wit-bindgen-rt@0.39.0", // pinned to a specific version due to using a binary blob: <https://github.com/rust-lang/rust/pull/136395#issuecomment-2692769062>
448    "writeable",
449    "yoke",
450    "yoke-derive",
451    "zerocopy",
452    "zerocopy-derive",
453    "zerofrom",
454    "zerofrom-derive",
455    "zerotrie",
456    "zerovec",
457    "zerovec-derive",
458    // tidy-alphabetical-end
459];
460
461const PERMITTED_STDLIB_DEPENDENCIES: &[&str] = &[
462    // tidy-alphabetical-start
463    "addr2line",
464    "adler2",
465    "cc",
466    "cfg-if",
467    "compiler_builtins",
468    "dlmalloc",
469    "fortanix-sgx-abi",
470    "getopts",
471    "gimli",
472    "hashbrown",
473    "hermit-abi",
474    "libc",
475    "memchr",
476    "miniz_oxide",
477    "object",
478    "r-efi",
479    "r-efi-alloc",
480    "rand",
481    "rand_core",
482    "rand_xorshift",
483    "rustc-demangle",
484    "rustc-literal-escaper",
485    "shlex",
486    "unwinding",
487    "wasi",
488    "windows-sys",
489    "windows-targets",
490    "windows_aarch64_gnullvm",
491    "windows_aarch64_msvc",
492    "windows_i686_gnu",
493    "windows_i686_gnullvm",
494    "windows_i686_msvc",
495    "windows_x86_64_gnu",
496    "windows_x86_64_gnullvm",
497    "windows_x86_64_msvc",
498    "wit-bindgen",
499    // tidy-alphabetical-end
500];
501
502const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
503    // tidy-alphabetical-start
504    "allocator-api2",
505    "anyhow",
506    "arbitrary",
507    "bitflags",
508    "bumpalo",
509    "cfg-if",
510    "cranelift-assembler-x64",
511    "cranelift-assembler-x64-meta",
512    "cranelift-bforest",
513    "cranelift-bitset",
514    "cranelift-codegen",
515    "cranelift-codegen-meta",
516    "cranelift-codegen-shared",
517    "cranelift-control",
518    "cranelift-entity",
519    "cranelift-frontend",
520    "cranelift-isle",
521    "cranelift-jit",
522    "cranelift-module",
523    "cranelift-native",
524    "cranelift-object",
525    "cranelift-srcgen",
526    "crc32fast",
527    "equivalent",
528    "fallible-iterator",
529    "foldhash",
530    "gimli",
531    "hashbrown",
532    "indexmap",
533    "libc",
534    "libloading",
535    "libm",
536    "log",
537    "mach2",
538    "memchr",
539    "object",
540    "proc-macro2",
541    "quote",
542    "regalloc2",
543    "region",
544    "rustc-hash",
545    "serde",
546    "serde_derive",
547    "smallvec",
548    "stable_deref_trait",
549    "syn",
550    "target-lexicon",
551    "unicode-ident",
552    "wasmtime-jit-icache-coherence",
553    "wasmtime-math",
554    "windows-sys",
555    "windows-targets",
556    "windows_aarch64_gnullvm",
557    "windows_aarch64_msvc",
558    "windows_i686_gnu",
559    "windows_i686_gnullvm",
560    "windows_i686_msvc",
561    "windows_x86_64_gnu",
562    "windows_x86_64_gnullvm",
563    "windows_x86_64_msvc",
564    // tidy-alphabetical-end
565];
566
567/// Dependency checks.
568///
569/// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
570/// to the cargo executable.
571pub fn check(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
572    let mut checked_runtime_licenses = false;
573
574    check_proc_macro_dep_list(root, cargo, bless, bad);
575
576    for &(workspace, exceptions, permitted_deps, submodules) in WORKSPACES {
577        if has_missing_submodule(root, submodules) {
578            continue;
579        }
580
581        if !root.join(workspace).join("Cargo.lock").exists() {
582            tidy_error!(bad, "the `{workspace}` workspace doesn't have a Cargo.lock");
583            continue;
584        }
585
586        let mut cmd = cargo_metadata::MetadataCommand::new();
587        cmd.cargo_path(cargo)
588            .manifest_path(root.join(workspace).join("Cargo.toml"))
589            .features(cargo_metadata::CargoOpt::AllFeatures)
590            .other_options(vec!["--locked".to_owned()]);
591        let metadata = t!(cmd.exec());
592
593        check_license_exceptions(&metadata, workspace, exceptions, bad);
594        if let Some((crates, permitted_deps)) = permitted_deps {
595            check_permitted_dependencies(&metadata, workspace, permitted_deps, crates, bad);
596        }
597
598        if workspace == "library" {
599            check_runtime_license_exceptions(&metadata, bad);
600            check_runtime_no_duplicate_dependencies(&metadata, bad);
601            check_runtime_no_proc_macros(&metadata, bad);
602            checked_runtime_licenses = true;
603        }
604    }
605
606    // Sanity check to ensure we don't accidentally remove the workspace containing the runtime
607    // crates.
608    assert!(checked_runtime_licenses);
609}
610
611/// Ensure the list of proc-macro crate transitive dependencies is up to date
612fn check_proc_macro_dep_list(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
613    let mut cmd = cargo_metadata::MetadataCommand::new();
614    cmd.cargo_path(cargo)
615        .manifest_path(root.join("Cargo.toml"))
616        .features(cargo_metadata::CargoOpt::AllFeatures)
617        .other_options(vec!["--locked".to_owned()]);
618    let metadata = t!(cmd.exec());
619    let is_proc_macro_pkg = |pkg: &Package| pkg.targets.iter().any(|target| target.is_proc_macro());
620
621    let mut proc_macro_deps = HashSet::new();
622    for pkg in metadata.packages.iter().filter(|pkg| is_proc_macro_pkg(pkg)) {
623        deps_of(&metadata, &pkg.id, &mut proc_macro_deps);
624    }
625    // Remove the proc-macro crates themselves
626    proc_macro_deps.retain(|pkg| !is_proc_macro_pkg(&metadata[pkg]));
627
628    let proc_macro_deps: HashSet<_> =
629        proc_macro_deps.into_iter().map(|dep| metadata[dep].name.as_ref()).collect();
630    let expected = proc_macro_deps::CRATES.iter().copied().collect::<HashSet<_>>();
631
632    let needs_blessing = proc_macro_deps.difference(&expected).next().is_some()
633        || expected.difference(&proc_macro_deps).next().is_some();
634
635    if needs_blessing && bless {
636        let mut proc_macro_deps: Vec<_> = proc_macro_deps.into_iter().collect();
637        proc_macro_deps.sort();
638        let mut file = File::create(root.join("src/bootstrap/src/utils/proc_macro_deps.rs"))
639            .expect("`proc_macro_deps` should exist");
640        writeln!(
641            &mut file,
642            "/// Do not update manually - use `./x.py test tidy --bless`
643/// Holds all direct and indirect dependencies of proc-macro crates in tree.
644/// See <https://github.com/rust-lang/rust/issues/134863>
645pub static CRATES: &[&str] = &[
646    // tidy-alphabetical-start"
647        )
648        .unwrap();
649        for dep in proc_macro_deps {
650            writeln!(&mut file, "    {dep:?},").unwrap();
651        }
652        writeln!(
653            &mut file,
654            "    // tidy-alphabetical-end
655];"
656        )
657        .unwrap();
658    } else {
659        let old_bad = *bad;
660
661        for missing in proc_macro_deps.difference(&expected) {
662            tidy_error!(
663                bad,
664                "proc-macro crate dependency `{missing}` is not registered in `src/bootstrap/src/utils/proc_macro_deps.rs`",
665            );
666        }
667        for extra in expected.difference(&proc_macro_deps) {
668            tidy_error!(
669                bad,
670                "`{extra}` is registered in `src/bootstrap/src/utils/proc_macro_deps.rs`, but is not a proc-macro crate dependency",
671            );
672        }
673        if *bad != old_bad {
674            eprintln!("Run `./x.py test tidy --bless` to regenerate the list");
675        }
676    }
677}
678
679/// Used to skip a check if a submodule is not checked out, and not in a CI environment.
680///
681/// This helps prevent enforcing developers to fetch submodules for tidy.
682pub fn has_missing_submodule(root: &Path, submodules: &[&str]) -> bool {
683    !CiEnv::is_ci()
684        && submodules.iter().any(|submodule| {
685            let path = root.join(submodule);
686            !path.exists()
687            // If the directory is empty, we can consider it as an uninitialized submodule.
688            || read_dir(path).unwrap().next().is_none()
689        })
690}
691
692/// Check that all licenses of runtime dependencies are in the valid list in `LICENSES`.
693///
694/// Unlike for tools we don't allow exceptions to the `LICENSES` list for the runtime with the sole
695/// exception of `fortanix-sgx-abi` which is only used on x86_64-fortanix-unknown-sgx.
696fn check_runtime_license_exceptions(metadata: &Metadata, bad: &mut bool) {
697    for pkg in &metadata.packages {
698        if pkg.source.is_none() {
699            // No need to check local packages.
700            continue;
701        }
702        let license = match &pkg.license {
703            Some(license) => license,
704            None => {
705                tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
706                continue;
707            }
708        };
709        if !LICENSES.contains(&license.as_str()) {
710            // This is a specific exception because SGX is considered "third party".
711            // See https://github.com/rust-lang/rust/issues/62620 for more.
712            // In general, these should never be added and this exception
713            // should not be taken as precedent for any new target.
714            if *pkg.name == "fortanix-sgx-abi" && pkg.license.as_deref() == Some("MPL-2.0") {
715                continue;
716            }
717
718            tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
719        }
720    }
721}
722
723/// Check that all licenses of tool dependencies are in the valid list in `LICENSES`.
724///
725/// Packages listed in `exceptions` are allowed for tools.
726fn check_license_exceptions(
727    metadata: &Metadata,
728    workspace: &str,
729    exceptions: &[(&str, &str)],
730    bad: &mut bool,
731) {
732    // Validate the EXCEPTIONS list hasn't changed.
733    for (name, license) in exceptions {
734        // Check that the package actually exists.
735        if !metadata.packages.iter().any(|p| *p.name == *name) {
736            tidy_error!(
737                bad,
738                "could not find exception package `{}` in workspace `{workspace}`\n\
739                Remove from EXCEPTIONS list if it is no longer used.",
740                name
741            );
742        }
743        // Check that the license hasn't changed.
744        for pkg in metadata.packages.iter().filter(|p| *p.name == *name) {
745            match &pkg.license {
746                None => {
747                    tidy_error!(
748                        bad,
749                        "dependency exception `{}` in workspace `{workspace}` does not declare a license expression",
750                        pkg.id
751                    );
752                }
753                Some(pkg_license) => {
754                    if pkg_license.as_str() != *license {
755                        println!(
756                            "dependency exception `{name}` license in workspace `{workspace}` has changed"
757                        );
758                        println!("    previously `{license}` now `{pkg_license}`");
759                        println!("    update EXCEPTIONS for the new license");
760                        *bad = true;
761                    }
762                }
763            }
764        }
765    }
766
767    let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
768
769    // Check if any package does not have a valid license.
770    for pkg in &metadata.packages {
771        if pkg.source.is_none() {
772            // No need to check local packages.
773            continue;
774        }
775        if exception_names.contains(&pkg.name.as_str()) {
776            continue;
777        }
778        let license = match &pkg.license {
779            Some(license) => license,
780            None => {
781                tidy_error!(
782                    bad,
783                    "dependency `{}` in workspace `{workspace}` does not define a license expression",
784                    pkg.id
785                );
786                continue;
787            }
788        };
789        if !LICENSES.contains(&license.as_str()) {
790            tidy_error!(
791                bad,
792                "invalid license `{}` for package `{}` in workspace `{workspace}`",
793                license,
794                pkg.id
795            );
796        }
797    }
798}
799
800fn check_runtime_no_duplicate_dependencies(metadata: &Metadata, bad: &mut bool) {
801    let mut seen_pkgs = HashSet::new();
802    for pkg in &metadata.packages {
803        if pkg.source.is_none() {
804            continue;
805        }
806
807        // Skip the `wasi` crate here which the standard library explicitly
808        // depends on two version of (one for the `wasm32-wasip1` target and
809        // another for the `wasm32-wasip2` target).
810        if pkg.name.to_string() != "wasi" && !seen_pkgs.insert(&*pkg.name) {
811            tidy_error!(
812                bad,
813                "duplicate package `{}` is not allowed for the standard library",
814                pkg.name
815            );
816        }
817    }
818}
819
820fn check_runtime_no_proc_macros(metadata: &Metadata, bad: &mut bool) {
821    for pkg in &metadata.packages {
822        if pkg.targets.iter().any(|target| target.is_proc_macro()) {
823            tidy_error!(
824                bad,
825                "proc macro `{}` is not allowed as standard library dependency.\n\
826                Using proc macros in the standard library would break cross-compilation \
827                as proc-macros don't get shipped for the host tuple.",
828                pkg.name
829            );
830        }
831    }
832}
833
834/// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
835/// `true` if a check failed.
836///
837/// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
838fn check_permitted_dependencies(
839    metadata: &Metadata,
840    descr: &str,
841    permitted_dependencies: &[&'static str],
842    restricted_dependency_crates: &[&'static str],
843    bad: &mut bool,
844) {
845    let mut has_permitted_dep_error = false;
846    let mut deps = HashSet::new();
847    for to_check in restricted_dependency_crates {
848        let to_check = pkg_from_name(metadata, to_check);
849        deps_of(metadata, &to_check.id, &mut deps);
850    }
851
852    // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
853    for permitted in permitted_dependencies {
854        fn compare(pkg: &Package, permitted: &str) -> bool {
855            if let Some((name, version)) = permitted.split_once("@") {
856                let Ok(version) = Version::parse(version) else {
857                    return false;
858                };
859                *pkg.name == name && pkg.version == version
860            } else {
861                *pkg.name == permitted
862            }
863        }
864        if !deps.iter().any(|dep_id| compare(pkg_from_id(metadata, dep_id), permitted)) {
865            tidy_error!(
866                bad,
867                "could not find allowed package `{permitted}`\n\
868                Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
869            );
870            has_permitted_dep_error = true;
871        }
872    }
873
874    // Get in a convenient form.
875    let permitted_dependencies: HashMap<_, _> = permitted_dependencies
876        .iter()
877        .map(|s| {
878            if let Some((name, version)) = s.split_once('@') {
879                (name, Version::parse(version).ok())
880            } else {
881                (*s, None)
882            }
883        })
884        .collect();
885
886    for dep in deps {
887        let dep = pkg_from_id(metadata, dep);
888        // If this path is in-tree, we don't require it to be explicitly permitted.
889        if dep.source.is_some() {
890            let is_eq = if let Some(version) = permitted_dependencies.get(dep.name.as_str()) {
891                if let Some(version) = version { version == &dep.version } else { true }
892            } else {
893                false
894            };
895            if !is_eq {
896                tidy_error!(bad, "Dependency for {descr} not explicitly permitted: {}", dep.id);
897                has_permitted_dep_error = true;
898            }
899        }
900    }
901
902    if has_permitted_dep_error {
903        eprintln!("Go to `{PERMITTED_DEPS_LOCATION}` for the list.");
904    }
905}
906
907/// Finds a package with the given name.
908fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
909    let mut i = metadata.packages.iter().filter(|p| *p.name == name);
910    let result =
911        i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
912    assert!(i.next().is_none(), "more than one package found for `{name}`");
913    result
914}
915
916fn pkg_from_id<'a>(metadata: &'a Metadata, id: &PackageId) -> &'a Package {
917    metadata.packages.iter().find(|p| &p.id == id).unwrap()
918}
919
920/// Recursively find all dependencies.
921fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId, result: &mut HashSet<&'a PackageId>) {
922    if !result.insert(pkg_id) {
923        return;
924    }
925    let node = metadata
926        .resolve
927        .as_ref()
928        .unwrap()
929        .nodes
930        .iter()
931        .find(|n| &n.id == pkg_id)
932        .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
933    for dep in &node.deps {
934        deps_of(metadata, &dep.pkg, result);
935    }
936}