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/ci/docker/host-x86_64/test-various/uefi_qemu_test", EXCEPTIONS_UEFI_QEMU_TEST, None, &[]),
77    ("src/etc/test-float-parse", EXCEPTIONS, None, &[]),
78    ("src/tools/cargo", EXCEPTIONS_CARGO, None, &["src/tools/cargo"]),
79    //("src/tools/miri/test-cargo-miri", &[], None), // FIXME uncomment once all deps are vendored
80    //("src/tools/miri/test_dependencies", &[], None), // FIXME uncomment once all deps are vendored
81    ("src/tools/rust-analyzer", EXCEPTIONS_RUST_ANALYZER, None, &[]),
82    ("src/tools/rustbook", EXCEPTIONS_RUSTBOOK, None, &["src/doc/book", "src/doc/reference"]),
83    ("src/tools/rustc-perf", EXCEPTIONS_RUSTC_PERF, None, &["src/tools/rustc-perf"]),
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    ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0
139    ("similar", "Apache-2.0"),
140    ("sized-chunks", "MPL-2.0+"),
141    ("subtle", "BSD-3-Clause"),
142    ("supports-hyperlinks", "Apache-2.0"),
143    ("unicode-bom", "Apache-2.0"),
144    ("zlib-rs", "Zlib"),
145    // tidy-alphabetical-end
146];
147
148const EXCEPTIONS_RUST_ANALYZER: ExceptionList = &[
149    // tidy-alphabetical-start
150    ("dissimilar", "Apache-2.0"),
151    ("foldhash", "Zlib"),
152    ("notify", "CC0-1.0"),
153    ("option-ext", "MPL-2.0"),
154    ("pulldown-cmark-to-cmark", "Apache-2.0"),
155    ("rustc_apfloat", "Apache-2.0 WITH LLVM-exception"),
156    ("ryu", "Apache-2.0 OR BSL-1.0"), // BSL is not acceptble, but we use it under Apache-2.0
157    ("scip", "Apache-2.0"),
158    // tidy-alphabetical-end
159];
160
161const EXCEPTIONS_RUSTC_PERF: ExceptionList = &[
162    // tidy-alphabetical-start
163    ("alloc-no-stdlib", "BSD-3-Clause"),
164    ("alloc-stdlib", "BSD-3-Clause"),
165    ("brotli", "BSD-3-Clause/MIT"),
166    ("brotli-decompressor", "BSD-3-Clause/MIT"),
167    ("encoding_rs", "(Apache-2.0 OR MIT) AND BSD-3-Clause"),
168    ("inferno", "CDDL-1.0"),
169    ("ring", NON_STANDARD_LICENSE), // see EXCEPTIONS_NON_STANDARD_LICENSE_DEPS for more.
170    ("ryu", "Apache-2.0 OR BSL-1.0"),
171    ("snap", "BSD-3-Clause"),
172    ("subtle", "BSD-3-Clause"),
173    // tidy-alphabetical-end
174];
175
176const EXCEPTIONS_RUSTBOOK: ExceptionList = &[
177    // tidy-alphabetical-start
178    ("cssparser", "MPL-2.0"),
179    ("cssparser-macros", "MPL-2.0"),
180    ("dtoa-short", "MPL-2.0"),
181    ("mdbook", "MPL-2.0"),
182    ("ryu", "Apache-2.0 OR BSL-1.0"),
183    // tidy-alphabetical-end
184];
185
186const EXCEPTIONS_CRANELIFT: ExceptionList = &[
187    // tidy-alphabetical-start
188    ("cranelift-assembler-x64", "Apache-2.0 WITH LLVM-exception"),
189    ("cranelift-assembler-x64-meta", "Apache-2.0 WITH LLVM-exception"),
190    ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"),
191    ("cranelift-bitset", "Apache-2.0 WITH LLVM-exception"),
192    ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"),
193    ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"),
194    ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"),
195    ("cranelift-control", "Apache-2.0 WITH LLVM-exception"),
196    ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"),
197    ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"),
198    ("cranelift-isle", "Apache-2.0 WITH LLVM-exception"),
199    ("cranelift-jit", "Apache-2.0 WITH LLVM-exception"),
200    ("cranelift-module", "Apache-2.0 WITH LLVM-exception"),
201    ("cranelift-native", "Apache-2.0 WITH LLVM-exception"),
202    ("cranelift-object", "Apache-2.0 WITH LLVM-exception"),
203    ("foldhash", "Zlib"),
204    ("mach2", "BSD-2-Clause OR MIT OR Apache-2.0"),
205    ("regalloc2", "Apache-2.0 WITH LLVM-exception"),
206    ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
207    ("wasmtime-jit-icache-coherence", "Apache-2.0 WITH LLVM-exception"),
208    // tidy-alphabetical-end
209];
210
211const EXCEPTIONS_GCC: ExceptionList = &[
212    // tidy-alphabetical-start
213    ("gccjit", "GPL-3.0"),
214    ("gccjit_sys", "GPL-3.0"),
215    // tidy-alphabetical-end
216];
217
218const EXCEPTIONS_BOOTSTRAP: ExceptionList = &[
219    ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde. BSL is not acceptble, but we use it under Apache-2.0
220];
221
222const EXCEPTIONS_UEFI_QEMU_TEST: ExceptionList = &[
223    ("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
224];
225
226/// Placeholder for non-standard license file.
227const NON_STANDARD_LICENSE: &str = "NON_STANDARD_LICENSE";
228
229/// These dependencies have non-standard licenses but are genenrally permitted.
230const EXCEPTIONS_NON_STANDARD_LICENSE_DEPS: &[&str] = &[
231    // `ring` is included because it is an optional dependency of `hyper`,
232    // which is a training data in rustc-perf for optimized build.
233    // The license of it is generally `ISC AND MIT AND OpenSSL`,
234    // though the `package.license` field is not set.
235    //
236    // See https://github.com/briansmith/ring/issues/902
237    "ring",
238];
239
240const PERMITTED_DEPS_LOCATION: &str = concat!(file!(), ":", line!());
241
242/// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
243///
244/// This list is here to provide a speed-bump to adding a new dependency to
245/// rustc. Please check with the compiler team before adding an entry.
246const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
247    // tidy-alphabetical-start
248    "adler2",
249    "aho-corasick",
250    "allocator-api2", // FIXME: only appears in Cargo.lock due to https://github.com/rust-lang/cargo/issues/10801
251    "annotate-snippets",
252    "anstyle",
253    "ar_archive_writer",
254    "arrayref",
255    "arrayvec",
256    "autocfg",
257    "bitflags",
258    "blake3",
259    "block-buffer",
260    "bstr",
261    "cc",
262    "cfg-if",
263    "cfg_aliases",
264    "constant_time_eq",
265    "cpufeatures",
266    "crc32fast",
267    "crossbeam-deque",
268    "crossbeam-epoch",
269    "crossbeam-utils",
270    "crypto-common",
271    "ctrlc",
272    "darling",
273    "darling_core",
274    "darling_macro",
275    "datafrog",
276    "derive-where",
277    "derive_setters",
278    "digest",
279    "displaydoc",
280    "dissimilar",
281    "either",
282    "elsa",
283    "ena",
284    "equivalent",
285    "errno",
286    "expect-test",
287    "fallible-iterator", // dependency of `thorin`
288    "fastrand",
289    "flate2",
290    "fluent-bundle",
291    "fluent-langneg",
292    "fluent-syntax",
293    "fnv",
294    "foldhash",
295    "generic-array",
296    "getopts",
297    "getrandom",
298    "gimli",
299    "gsgdt",
300    "hashbrown",
301    "icu_list",
302    "icu_list_data",
303    "icu_locid",
304    "icu_locid_transform",
305    "icu_locid_transform_data",
306    "icu_provider",
307    "icu_provider_adapters",
308    "icu_provider_macros",
309    "ident_case",
310    "indexmap",
311    "intl-memoizer",
312    "intl_pluralrules",
313    "itertools",
314    "itoa",
315    "jiff",
316    "jiff-static",
317    "jobserver",
318    "lazy_static",
319    "leb128",
320    "libc",
321    "libloading",
322    "linux-raw-sys",
323    "litemap",
324    "lock_api",
325    "log",
326    "matchers",
327    "md-5",
328    "measureme",
329    "memchr",
330    "memmap2",
331    "miniz_oxide",
332    "nix",
333    "nu-ansi-term",
334    "object",
335    "odht",
336    "once_cell",
337    "overload",
338    "parking_lot",
339    "parking_lot_core",
340    "pathdiff",
341    "perf-event-open-sys",
342    "pin-project-lite",
343    "polonius-engine",
344    "portable-atomic", // dependency for platforms doesn't support `AtomicU64` in std
345    "portable-atomic-util",
346    "ppv-lite86",
347    "proc-macro-hack",
348    "proc-macro2",
349    "psm",
350    "pulldown-cmark",
351    "pulldown-cmark-escape",
352    "punycode",
353    "quote",
354    "r-efi",
355    "rand",
356    "rand_chacha",
357    "rand_core",
358    "rand_xoshiro",
359    "redox_syscall",
360    "regex",
361    "regex-automata",
362    "regex-syntax",
363    "rustc-demangle",
364    "rustc-hash",
365    "rustc-literal-escaper",
366    "rustc-rayon-core",
367    "rustc-stable-hash",
368    "rustc_apfloat",
369    "rustix",
370    "ruzstd", // via object in thorin-dwp
371    "ryu",
372    "scoped-tls",
373    "scopeguard",
374    "self_cell",
375    "serde",
376    "serde_derive",
377    "serde_json",
378    "sha1",
379    "sha2",
380    "sharded-slab",
381    "shlex",
382    "smallvec",
383    "stable_deref_trait",
384    "stacker",
385    "static_assertions",
386    "strsim",
387    "syn",
388    "synstructure",
389    "tempfile",
390    "termcolor",
391    "termize",
392    "thin-vec",
393    "thiserror",
394    "thiserror-impl",
395    "thorin-dwp",
396    "thread_local",
397    "tikv-jemalloc-sys",
398    "tinystr",
399    "tinyvec",
400    "tinyvec_macros",
401    "tracing",
402    "tracing-attributes",
403    "tracing-core",
404    "tracing-log",
405    "tracing-subscriber",
406    "tracing-tree",
407    "twox-hash",
408    "type-map",
409    "typenum",
410    "unic-langid",
411    "unic-langid-impl",
412    "unic-langid-macros",
413    "unic-langid-macros-impl",
414    "unicase",
415    "unicode-ident",
416    "unicode-normalization",
417    "unicode-properties",
418    "unicode-script",
419    "unicode-security",
420    "unicode-width",
421    "unicode-xid",
422    "valuable",
423    "version_check",
424    "wasi",
425    "wasm-encoder",
426    "wasmparser",
427    "winapi",
428    "winapi-i686-pc-windows-gnu",
429    "winapi-util",
430    "winapi-x86_64-pc-windows-gnu",
431    "windows",
432    "windows-core",
433    "windows-implement",
434    "windows-interface",
435    "windows-link",
436    "windows-result",
437    "windows-strings",
438    "windows-sys",
439    "windows-targets",
440    "windows_aarch64_gnullvm",
441    "windows_aarch64_msvc",
442    "windows_i686_gnu",
443    "windows_i686_gnullvm",
444    "windows_i686_msvc",
445    "windows_x86_64_gnu",
446    "windows_x86_64_gnullvm",
447    "windows_x86_64_msvc",
448    "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>
449    "writeable",
450    "yoke",
451    "yoke-derive",
452    "zerocopy",
453    "zerocopy-derive",
454    "zerofrom",
455    "zerofrom-derive",
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    "unicode-width",
487    "unwinding",
488    "wasi",
489    "windows-sys",
490    "windows-targets",
491    "windows_aarch64_gnullvm",
492    "windows_aarch64_msvc",
493    "windows_i686_gnu",
494    "windows_i686_gnullvm",
495    "windows_i686_msvc",
496    "windows_x86_64_gnu",
497    "windows_x86_64_gnullvm",
498    "windows_x86_64_msvc",
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    "crc32fast",
526    "equivalent",
527    "fallible-iterator",
528    "foldhash",
529    "gimli",
530    "hashbrown",
531    "indexmap",
532    "libc",
533    "libloading",
534    "log",
535    "mach2",
536    "memchr",
537    "object",
538    "proc-macro2",
539    "quote",
540    "regalloc2",
541    "region",
542    "rustc-hash",
543    "serde",
544    "serde_derive",
545    "smallvec",
546    "stable_deref_trait",
547    "syn",
548    "target-lexicon",
549    "unicode-ident",
550    "wasmtime-jit-icache-coherence",
551    "windows-sys",
552    "windows-targets",
553    "windows_aarch64_gnullvm",
554    "windows_aarch64_msvc",
555    "windows_i686_gnu",
556    "windows_i686_gnullvm",
557    "windows_i686_msvc",
558    "windows_x86_64_gnu",
559    "windows_x86_64_gnullvm",
560    "windows_x86_64_msvc",
561    // tidy-alphabetical-end
562];
563
564/// Dependency checks.
565///
566/// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
567/// to the cargo executable.
568pub fn check(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
569    let mut checked_runtime_licenses = false;
570
571    check_proc_macro_dep_list(root, cargo, bless, bad);
572
573    for &(workspace, exceptions, permitted_deps, submodules) in WORKSPACES {
574        if has_missing_submodule(root, submodules) {
575            continue;
576        }
577
578        if !root.join(workspace).join("Cargo.lock").exists() {
579            tidy_error!(bad, "the `{workspace}` workspace doesn't have a Cargo.lock");
580            continue;
581        }
582
583        let mut cmd = cargo_metadata::MetadataCommand::new();
584        cmd.cargo_path(cargo)
585            .manifest_path(root.join(workspace).join("Cargo.toml"))
586            .features(cargo_metadata::CargoOpt::AllFeatures)
587            .other_options(vec!["--locked".to_owned()]);
588        let metadata = t!(cmd.exec());
589
590        check_license_exceptions(&metadata, exceptions, bad);
591        if let Some((crates, permitted_deps)) = permitted_deps {
592            check_permitted_dependencies(&metadata, workspace, permitted_deps, crates, bad);
593        }
594
595        if workspace == "library" {
596            check_runtime_license_exceptions(&metadata, bad);
597            checked_runtime_licenses = true;
598        }
599    }
600
601    // Sanity check to ensure we don't accidentally remove the workspace containing the runtime
602    // crates.
603    assert!(checked_runtime_licenses);
604}
605
606/// Ensure the list of proc-macro crate transitive dependencies is up to date
607fn check_proc_macro_dep_list(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
608    let mut cmd = cargo_metadata::MetadataCommand::new();
609    cmd.cargo_path(cargo)
610        .manifest_path(root.join("Cargo.toml"))
611        .features(cargo_metadata::CargoOpt::AllFeatures)
612        .other_options(vec!["--locked".to_owned()]);
613    let metadata = t!(cmd.exec());
614    let is_proc_macro_pkg = |pkg: &Package| pkg.targets.iter().any(|target| target.is_proc_macro());
615
616    let mut proc_macro_deps = HashSet::new();
617    for pkg in metadata.packages.iter().filter(|pkg| is_proc_macro_pkg(*pkg)) {
618        deps_of(&metadata, &pkg.id, &mut proc_macro_deps);
619    }
620    // Remove the proc-macro crates themselves
621    proc_macro_deps.retain(|pkg| !is_proc_macro_pkg(&metadata[pkg]));
622
623    let proc_macro_deps: HashSet<_> =
624        proc_macro_deps.into_iter().map(|dep| metadata[dep].name.clone()).collect();
625    let expected = proc_macro_deps::CRATES.iter().map(|s| s.to_string()).collect::<HashSet<_>>();
626
627    let needs_blessing = proc_macro_deps.difference(&expected).next().is_some()
628        || expected.difference(&proc_macro_deps).next().is_some();
629
630    if needs_blessing && bless {
631        let mut proc_macro_deps: Vec<_> = proc_macro_deps.into_iter().collect();
632        proc_macro_deps.sort();
633        let mut file = File::create(root.join("src/bootstrap/src/utils/proc_macro_deps.rs"))
634            .expect("`proc_macro_deps` should exist");
635        writeln!(
636            &mut file,
637            "/// Do not update manually - use `./x.py test tidy --bless`
638/// Holds all direct and indirect dependencies of proc-macro crates in tree.
639/// See <https://github.com/rust-lang/rust/issues/134863>
640pub static CRATES: &[&str] = &[
641    // tidy-alphabetical-start"
642        )
643        .unwrap();
644        for dep in proc_macro_deps {
645            writeln!(&mut file, "    {dep:?},").unwrap();
646        }
647        writeln!(
648            &mut file,
649            "    // tidy-alphabetical-end
650];"
651        )
652        .unwrap();
653    } else {
654        let old_bad = *bad;
655
656        for missing in proc_macro_deps.difference(&expected) {
657            tidy_error!(
658                bad,
659                "proc-macro crate dependency `{missing}` is not registered in `src/bootstrap/src/utils/proc_macro_deps.rs`",
660            );
661        }
662        for extra in expected.difference(&proc_macro_deps) {
663            tidy_error!(
664                bad,
665                "`{extra}` is registered in `src/bootstrap/src/utils/proc_macro_deps.rs`, but is not a proc-macro crate dependency",
666            );
667        }
668        if *bad != old_bad {
669            eprintln!("Run `./x.py test tidy --bless` to regenerate the list");
670        }
671    }
672}
673
674/// Used to skip a check if a submodule is not checked out, and not in a CI environment.
675///
676/// This helps prevent enforcing developers to fetch submodules for tidy.
677pub fn has_missing_submodule(root: &Path, submodules: &[&str]) -> bool {
678    !CiEnv::is_ci()
679        && submodules.iter().any(|submodule| {
680            let path = root.join(submodule);
681            !path.exists()
682            // If the directory is empty, we can consider it as an uninitialized submodule.
683            || read_dir(path).unwrap().next().is_none()
684        })
685}
686
687/// Check that all licenses of runtime dependencies are in the valid list in `LICENSES`.
688///
689/// Unlike for tools we don't allow exceptions to the `LICENSES` list for the runtime with the sole
690/// exception of `fortanix-sgx-abi` which is only used on x86_64-fortanix-unknown-sgx.
691fn check_runtime_license_exceptions(metadata: &Metadata, bad: &mut bool) {
692    for pkg in &metadata.packages {
693        if pkg.source.is_none() {
694            // No need to check local packages.
695            continue;
696        }
697        let license = match &pkg.license {
698            Some(license) => license,
699            None => {
700                tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
701                continue;
702            }
703        };
704        if !LICENSES.contains(&license.as_str()) {
705            // This is a specific exception because SGX is considered "third party".
706            // See https://github.com/rust-lang/rust/issues/62620 for more.
707            // In general, these should never be added and this exception
708            // should not be taken as precedent for any new target.
709            if pkg.name == "fortanix-sgx-abi" && pkg.license.as_deref() == Some("MPL-2.0") {
710                continue;
711            }
712
713            tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
714        }
715    }
716}
717
718/// Check that all licenses of tool dependencies are in the valid list in `LICENSES`.
719///
720/// Packages listed in `exceptions` are allowed for tools.
721fn check_license_exceptions(metadata: &Metadata, exceptions: &[(&str, &str)], bad: &mut bool) {
722    // Validate the EXCEPTIONS list hasn't changed.
723    for (name, license) in exceptions {
724        // Check that the package actually exists.
725        if !metadata.packages.iter().any(|p| p.name == *name) {
726            tidy_error!(
727                bad,
728                "could not find exception package `{}`\n\
729                Remove from EXCEPTIONS list if it is no longer used.",
730                name
731            );
732        }
733        // Check that the license hasn't changed.
734        for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
735            match &pkg.license {
736                None => {
737                    if *license == NON_STANDARD_LICENSE
738                        && EXCEPTIONS_NON_STANDARD_LICENSE_DEPS.contains(&pkg.name.as_str())
739                    {
740                        continue;
741                    }
742                    tidy_error!(
743                        bad,
744                        "dependency exception `{}` does not declare a license expression",
745                        pkg.id
746                    );
747                }
748                Some(pkg_license) => {
749                    if pkg_license.as_str() != *license {
750                        println!("dependency exception `{name}` license has changed");
751                        println!("    previously `{license}` now `{pkg_license}`");
752                        println!("    update EXCEPTIONS for the new license");
753                        *bad = true;
754                    }
755                }
756            }
757        }
758    }
759
760    let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
761
762    // Check if any package does not have a valid license.
763    for pkg in &metadata.packages {
764        if pkg.source.is_none() {
765            // No need to check local packages.
766            continue;
767        }
768        if exception_names.contains(&pkg.name.as_str()) {
769            continue;
770        }
771        let license = match &pkg.license {
772            Some(license) => license,
773            None => {
774                tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
775                continue;
776            }
777        };
778        if !LICENSES.contains(&license.as_str()) {
779            tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
780        }
781    }
782}
783
784/// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
785/// `true` if a check failed.
786///
787/// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
788fn check_permitted_dependencies(
789    metadata: &Metadata,
790    descr: &str,
791    permitted_dependencies: &[&'static str],
792    restricted_dependency_crates: &[&'static str],
793    bad: &mut bool,
794) {
795    let mut has_permitted_dep_error = false;
796    let mut deps = HashSet::new();
797    for to_check in restricted_dependency_crates {
798        let to_check = pkg_from_name(metadata, to_check);
799        deps_of(metadata, &to_check.id, &mut deps);
800    }
801
802    // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
803    for permitted in permitted_dependencies {
804        fn compare(pkg: &Package, permitted: &str) -> bool {
805            if let Some((name, version)) = permitted.split_once("@") {
806                let Ok(version) = Version::parse(version) else {
807                    return false;
808                };
809                pkg.name == name && pkg.version == version
810            } else {
811                pkg.name == permitted
812            }
813        }
814        if !deps.iter().any(|dep_id| compare(pkg_from_id(metadata, dep_id), permitted)) {
815            tidy_error!(
816                bad,
817                "could not find allowed package `{permitted}`\n\
818                Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
819            );
820            has_permitted_dep_error = true;
821        }
822    }
823
824    // Get in a convenient form.
825    let permitted_dependencies: HashMap<_, _> = permitted_dependencies
826        .iter()
827        .map(|s| {
828            if let Some((name, version)) = s.split_once('@') {
829                (name, Version::parse(version).ok())
830            } else {
831                (*s, None)
832            }
833        })
834        .collect();
835
836    for dep in deps {
837        let dep = pkg_from_id(metadata, dep);
838        // If this path is in-tree, we don't require it to be explicitly permitted.
839        if dep.source.is_some() {
840            let is_eq = if let Some(version) = permitted_dependencies.get(dep.name.as_str()) {
841                if let Some(version) = version { version == &dep.version } else { true }
842            } else {
843                false
844            };
845            if !is_eq {
846                tidy_error!(bad, "Dependency for {descr} not explicitly permitted: {}", dep.id);
847                has_permitted_dep_error = true;
848            }
849        }
850    }
851
852    if has_permitted_dep_error {
853        eprintln!("Go to `{PERMITTED_DEPS_LOCATION}` for the list.");
854    }
855}
856
857/// Finds a package with the given name.
858fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
859    let mut i = metadata.packages.iter().filter(|p| p.name == name);
860    let result =
861        i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
862    assert!(i.next().is_none(), "more than one package found for `{name}`");
863    result
864}
865
866fn pkg_from_id<'a>(metadata: &'a Metadata, id: &PackageId) -> &'a Package {
867    metadata.packages.iter().find(|p| &p.id == id).unwrap()
868}
869
870/// Recursively find all dependencies.
871fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId, result: &mut HashSet<&'a PackageId>) {
872    if !result.insert(pkg_id) {
873        return;
874    }
875    let node = metadata
876        .resolve
877        .as_ref()
878        .unwrap()
879        .nodes
880        .iter()
881        .find(|n| &n.id == pkg_id)
882        .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
883    for dep in &node.deps {
884        deps_of(metadata, &dep.pkg, result);
885    }
886}