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    ("cranelift-srcgen", "Apache-2.0 WITH LLVM-exception"),
204    ("foldhash", "Zlib"),
205    ("mach2", "BSD-2-Clause OR MIT OR Apache-2.0"),
206    ("regalloc2", "Apache-2.0 WITH LLVM-exception"),
207    ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
208    ("wasmtime-jit-icache-coherence", "Apache-2.0 WITH LLVM-exception"),
209    // tidy-alphabetical-end
210];
211
212const EXCEPTIONS_GCC: ExceptionList = &[
213    // tidy-alphabetical-start
214    ("gccjit", "GPL-3.0"),
215    ("gccjit_sys", "GPL-3.0"),
216    // tidy-alphabetical-end
217];
218
219const EXCEPTIONS_BOOTSTRAP: ExceptionList = &[
220    ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde. BSL is not acceptble, but we use it under Apache-2.0
221];
222
223const EXCEPTIONS_UEFI_QEMU_TEST: ExceptionList = &[
224    ("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
225];
226
227/// Placeholder for non-standard license file.
228const NON_STANDARD_LICENSE: &str = "NON_STANDARD_LICENSE";
229
230/// These dependencies have non-standard licenses but are genenrally permitted.
231const EXCEPTIONS_NON_STANDARD_LICENSE_DEPS: &[&str] = &[
232    // `ring` is included because it is an optional dependency of `hyper`,
233    // which is a training data in rustc-perf for optimized build.
234    // The license of it is generally `ISC AND MIT AND OpenSSL`,
235    // though the `package.license` field is not set.
236    //
237    // See https://github.com/briansmith/ring/issues/902
238    "ring",
239];
240
241const PERMITTED_DEPS_LOCATION: &str = concat!(file!(), ":", line!());
242
243/// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
244///
245/// This list is here to provide a speed-bump to adding a new dependency to
246/// rustc. Please check with the compiler team before adding an entry.
247const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
248    // tidy-alphabetical-start
249    "adler2",
250    "aho-corasick",
251    "allocator-api2", // FIXME: only appears in Cargo.lock due to https://github.com/rust-lang/cargo/issues/10801
252    "annotate-snippets",
253    "anstyle",
254    "ar_archive_writer",
255    "arrayref",
256    "arrayvec",
257    "autocfg",
258    "bitflags",
259    "blake3",
260    "block-buffer",
261    "bstr",
262    "cc",
263    "cfg-if",
264    "cfg_aliases",
265    "constant_time_eq",
266    "cpufeatures",
267    "crc32fast",
268    "crossbeam-deque",
269    "crossbeam-epoch",
270    "crossbeam-utils",
271    "crypto-common",
272    "ctrlc",
273    "darling",
274    "darling_core",
275    "darling_macro",
276    "datafrog",
277    "derive-where",
278    "derive_setters",
279    "digest",
280    "displaydoc",
281    "dissimilar",
282    "either",
283    "elsa",
284    "ena",
285    "equivalent",
286    "errno",
287    "expect-test",
288    "fallible-iterator", // dependency of `thorin`
289    "fastrand",
290    "flate2",
291    "fluent-bundle",
292    "fluent-langneg",
293    "fluent-syntax",
294    "fnv",
295    "foldhash",
296    "generic-array",
297    "getopts",
298    "getrandom",
299    "gimli",
300    "gsgdt",
301    "hashbrown",
302    "icu_list",
303    "icu_list_data",
304    "icu_locid",
305    "icu_locid_transform",
306    "icu_locid_transform_data",
307    "icu_provider",
308    "icu_provider_adapters",
309    "icu_provider_macros",
310    "ident_case",
311    "indexmap",
312    "intl-memoizer",
313    "intl_pluralrules",
314    "itertools",
315    "itoa",
316    "jiff",
317    "jiff-static",
318    "jobserver",
319    "lazy_static",
320    "leb128",
321    "libc",
322    "libloading",
323    "linux-raw-sys",
324    "litemap",
325    "lock_api",
326    "log",
327    "matchers",
328    "md-5",
329    "measureme",
330    "memchr",
331    "memmap2",
332    "miniz_oxide",
333    "nix",
334    "nu-ansi-term",
335    "object",
336    "odht",
337    "once_cell",
338    "overload",
339    "parking_lot",
340    "parking_lot_core",
341    "pathdiff",
342    "perf-event-open-sys",
343    "pin-project-lite",
344    "polonius-engine",
345    "portable-atomic", // dependency for platforms doesn't support `AtomicU64` in std
346    "portable-atomic-util",
347    "ppv-lite86",
348    "proc-macro-hack",
349    "proc-macro2",
350    "psm",
351    "pulldown-cmark",
352    "pulldown-cmark-escape",
353    "punycode",
354    "quote",
355    "r-efi",
356    "rand",
357    "rand_chacha",
358    "rand_core",
359    "rand_xoshiro",
360    "redox_syscall",
361    "regex",
362    "regex-automata",
363    "regex-syntax",
364    "rustc-demangle",
365    "rustc-hash",
366    "rustc-literal-escaper",
367    "rustc-rayon-core",
368    "rustc-stable-hash",
369    "rustc_apfloat",
370    "rustix",
371    "ruzstd", // via object in thorin-dwp
372    "ryu",
373    "scoped-tls",
374    "scopeguard",
375    "self_cell",
376    "serde",
377    "serde_derive",
378    "serde_json",
379    "sha1",
380    "sha2",
381    "sharded-slab",
382    "shlex",
383    "smallvec",
384    "stable_deref_trait",
385    "stacker",
386    "static_assertions",
387    "strsim",
388    "syn",
389    "synstructure",
390    "tempfile",
391    "termcolor",
392    "termize",
393    "thin-vec",
394    "thiserror",
395    "thiserror-impl",
396    "thorin-dwp",
397    "thread_local",
398    "tikv-jemalloc-sys",
399    "tinystr",
400    "tinyvec",
401    "tinyvec_macros",
402    "tracing",
403    "tracing-attributes",
404    "tracing-core",
405    "tracing-log",
406    "tracing-subscriber",
407    "tracing-tree",
408    "twox-hash",
409    "type-map",
410    "typenum",
411    "unic-langid",
412    "unic-langid-impl",
413    "unic-langid-macros",
414    "unic-langid-macros-impl",
415    "unicase",
416    "unicode-ident",
417    "unicode-normalization",
418    "unicode-properties",
419    "unicode-script",
420    "unicode-security",
421    "unicode-width",
422    "unicode-xid",
423    "valuable",
424    "version_check",
425    "wasi",
426    "wasm-encoder",
427    "wasmparser",
428    "winapi",
429    "winapi-i686-pc-windows-gnu",
430    "winapi-util",
431    "winapi-x86_64-pc-windows-gnu",
432    "windows",
433    "windows-collections",
434    "windows-core",
435    "windows-future",
436    "windows-implement",
437    "windows-interface",
438    "windows-link",
439    "windows-numerics",
440    "windows-result",
441    "windows-strings",
442    "windows-sys",
443    "windows-targets",
444    "windows_aarch64_gnullvm",
445    "windows_aarch64_msvc",
446    "windows_i686_gnu",
447    "windows_i686_gnullvm",
448    "windows_i686_msvc",
449    "windows_x86_64_gnu",
450    "windows_x86_64_gnullvm",
451    "windows_x86_64_msvc",
452    "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>
453    "writeable",
454    "yoke",
455    "yoke-derive",
456    "zerocopy",
457    "zerocopy-derive",
458    "zerofrom",
459    "zerofrom-derive",
460    "zerovec",
461    "zerovec-derive",
462    // tidy-alphabetical-end
463];
464
465const PERMITTED_STDLIB_DEPENDENCIES: &[&str] = &[
466    // tidy-alphabetical-start
467    "addr2line",
468    "adler2",
469    "cc",
470    "cfg-if",
471    "compiler_builtins",
472    "dlmalloc",
473    "fortanix-sgx-abi",
474    "getopts",
475    "gimli",
476    "hashbrown",
477    "hermit-abi",
478    "libc",
479    "memchr",
480    "miniz_oxide",
481    "object",
482    "r-efi",
483    "r-efi-alloc",
484    "rand",
485    "rand_core",
486    "rand_xorshift",
487    "rustc-demangle",
488    "rustc-literal-escaper",
489    "shlex",
490    "unicode-width",
491    "unwinding",
492    "wasi",
493    "windows-sys",
494    "windows-targets",
495    "windows_aarch64_gnullvm",
496    "windows_aarch64_msvc",
497    "windows_i686_gnu",
498    "windows_i686_gnullvm",
499    "windows_i686_msvc",
500    "windows_x86_64_gnu",
501    "windows_x86_64_gnullvm",
502    "windows_x86_64_msvc",
503    // tidy-alphabetical-end
504];
505
506const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
507    // tidy-alphabetical-start
508    "allocator-api2",
509    "anyhow",
510    "arbitrary",
511    "bitflags",
512    "bumpalo",
513    "cfg-if",
514    "cranelift-assembler-x64",
515    "cranelift-assembler-x64-meta",
516    "cranelift-bforest",
517    "cranelift-bitset",
518    "cranelift-codegen",
519    "cranelift-codegen-meta",
520    "cranelift-codegen-shared",
521    "cranelift-control",
522    "cranelift-entity",
523    "cranelift-frontend",
524    "cranelift-isle",
525    "cranelift-jit",
526    "cranelift-module",
527    "cranelift-native",
528    "cranelift-object",
529    "cranelift-srcgen",
530    "crc32fast",
531    "equivalent",
532    "fallible-iterator",
533    "foldhash",
534    "gimli",
535    "hashbrown",
536    "indexmap",
537    "libc",
538    "libloading",
539    "log",
540    "mach2",
541    "memchr",
542    "object",
543    "proc-macro2",
544    "quote",
545    "regalloc2",
546    "region",
547    "rustc-hash",
548    "serde",
549    "serde_derive",
550    "smallvec",
551    "stable_deref_trait",
552    "syn",
553    "target-lexicon",
554    "unicode-ident",
555    "wasmtime-jit-icache-coherence",
556    "windows-sys",
557    "windows-targets",
558    "windows_aarch64_gnullvm",
559    "windows_aarch64_msvc",
560    "windows_i686_gnu",
561    "windows_i686_gnullvm",
562    "windows_i686_msvc",
563    "windows_x86_64_gnu",
564    "windows_x86_64_gnullvm",
565    "windows_x86_64_msvc",
566    // tidy-alphabetical-end
567];
568
569/// Dependency checks.
570///
571/// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
572/// to the cargo executable.
573pub fn check(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
574    let mut checked_runtime_licenses = false;
575
576    check_proc_macro_dep_list(root, cargo, bless, bad);
577
578    for &(workspace, exceptions, permitted_deps, submodules) in WORKSPACES {
579        if has_missing_submodule(root, submodules) {
580            continue;
581        }
582
583        if !root.join(workspace).join("Cargo.lock").exists() {
584            tidy_error!(bad, "the `{workspace}` workspace doesn't have a Cargo.lock");
585            continue;
586        }
587
588        let mut cmd = cargo_metadata::MetadataCommand::new();
589        cmd.cargo_path(cargo)
590            .manifest_path(root.join(workspace).join("Cargo.toml"))
591            .features(cargo_metadata::CargoOpt::AllFeatures)
592            .other_options(vec!["--locked".to_owned()]);
593        let metadata = t!(cmd.exec());
594
595        check_license_exceptions(&metadata, exceptions, bad);
596        if let Some((crates, permitted_deps)) = permitted_deps {
597            check_permitted_dependencies(&metadata, workspace, permitted_deps, crates, bad);
598        }
599
600        if workspace == "library" {
601            check_runtime_license_exceptions(&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.clone()).collect();
630    let expected = proc_macro_deps::CRATES.iter().map(|s| s.to_string()).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(metadata: &Metadata, exceptions: &[(&str, &str)], bad: &mut bool) {
727    // Validate the EXCEPTIONS list hasn't changed.
728    for (name, license) in exceptions {
729        // Check that the package actually exists.
730        if !metadata.packages.iter().any(|p| p.name == *name) {
731            tidy_error!(
732                bad,
733                "could not find exception package `{}`\n\
734                Remove from EXCEPTIONS list if it is no longer used.",
735                name
736            );
737        }
738        // Check that the license hasn't changed.
739        for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
740            match &pkg.license {
741                None => {
742                    if *license == NON_STANDARD_LICENSE
743                        && EXCEPTIONS_NON_STANDARD_LICENSE_DEPS.contains(&pkg.name.as_str())
744                    {
745                        continue;
746                    }
747                    tidy_error!(
748                        bad,
749                        "dependency exception `{}` does not declare a license expression",
750                        pkg.id
751                    );
752                }
753                Some(pkg_license) => {
754                    if pkg_license.as_str() != *license {
755                        println!("dependency exception `{name}` license has changed");
756                        println!("    previously `{license}` now `{pkg_license}`");
757                        println!("    update EXCEPTIONS for the new license");
758                        *bad = true;
759                    }
760                }
761            }
762        }
763    }
764
765    let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
766
767    // Check if any package does not have a valid license.
768    for pkg in &metadata.packages {
769        if pkg.source.is_none() {
770            // No need to check local packages.
771            continue;
772        }
773        if exception_names.contains(&pkg.name.as_str()) {
774            continue;
775        }
776        let license = match &pkg.license {
777            Some(license) => license,
778            None => {
779                tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
780                continue;
781            }
782        };
783        if !LICENSES.contains(&license.as_str()) {
784            tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
785        }
786    }
787}
788
789/// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
790/// `true` if a check failed.
791///
792/// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
793fn check_permitted_dependencies(
794    metadata: &Metadata,
795    descr: &str,
796    permitted_dependencies: &[&'static str],
797    restricted_dependency_crates: &[&'static str],
798    bad: &mut bool,
799) {
800    let mut has_permitted_dep_error = false;
801    let mut deps = HashSet::new();
802    for to_check in restricted_dependency_crates {
803        let to_check = pkg_from_name(metadata, to_check);
804        deps_of(metadata, &to_check.id, &mut deps);
805    }
806
807    // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
808    for permitted in permitted_dependencies {
809        fn compare(pkg: &Package, permitted: &str) -> bool {
810            if let Some((name, version)) = permitted.split_once("@") {
811                let Ok(version) = Version::parse(version) else {
812                    return false;
813                };
814                pkg.name == name && pkg.version == version
815            } else {
816                pkg.name == permitted
817            }
818        }
819        if !deps.iter().any(|dep_id| compare(pkg_from_id(metadata, dep_id), permitted)) {
820            tidy_error!(
821                bad,
822                "could not find allowed package `{permitted}`\n\
823                Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
824            );
825            has_permitted_dep_error = true;
826        }
827    }
828
829    // Get in a convenient form.
830    let permitted_dependencies: HashMap<_, _> = permitted_dependencies
831        .iter()
832        .map(|s| {
833            if let Some((name, version)) = s.split_once('@') {
834                (name, Version::parse(version).ok())
835            } else {
836                (*s, None)
837            }
838        })
839        .collect();
840
841    for dep in deps {
842        let dep = pkg_from_id(metadata, dep);
843        // If this path is in-tree, we don't require it to be explicitly permitted.
844        if dep.source.is_some() {
845            let is_eq = if let Some(version) = permitted_dependencies.get(dep.name.as_str()) {
846                if let Some(version) = version { version == &dep.version } else { true }
847            } else {
848                false
849            };
850            if !is_eq {
851                tidy_error!(bad, "Dependency for {descr} not explicitly permitted: {}", dep.id);
852                has_permitted_dep_error = true;
853            }
854        }
855    }
856
857    if has_permitted_dep_error {
858        eprintln!("Go to `{PERMITTED_DEPS_LOCATION}` for the list.");
859    }
860}
861
862/// Finds a package with the given name.
863fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
864    let mut i = metadata.packages.iter().filter(|p| p.name == name);
865    let result =
866        i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
867    assert!(i.next().is_none(), "more than one package found for `{name}`");
868    result
869}
870
871fn pkg_from_id<'a>(metadata: &'a Metadata, id: &PackageId) -> &'a Package {
872    metadata.packages.iter().find(|p| &p.id == id).unwrap()
873}
874
875/// Recursively find all dependencies.
876fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId, result: &mut HashSet<&'a PackageId>) {
877    if !result.insert(pkg_id) {
878        return;
879    }
880    let node = metadata
881        .resolve
882        .as_ref()
883        .unwrap()
884        .nodes
885        .iter()
886        .find(|n| &n.id == pkg_id)
887        .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
888    for dep in &node.deps {
889        deps_of(metadata, &dep.pkg, result);
890    }
891}