1use 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#[rustfmt::skip]
18const LICENSES: &[&str] = &[
19 "(MIT OR Apache-2.0) AND Unicode-3.0", "(MIT OR Apache-2.0) AND Unicode-DFS-2016", "0BSD OR MIT OR Apache-2.0", "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", "Apache-2.0",
29 "Apache-2.0/MIT",
30 "BSD-2-Clause OR Apache-2.0 OR MIT", "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)", "MIT OR Apache-2.0 OR LGPL-2.1-or-later", "MIT OR Apache-2.0 OR Zlib", "MIT OR Apache-2.0",
38 "MIT OR Zlib OR Apache-2.0", "MIT",
40 "MIT/Apache-2.0",
41 "Unicode-3.0", "Unicode-DFS-2016", "Unlicense OR MIT",
44 "Unlicense/MIT",
45 "Zlib OR Apache-2.0 OR MIT", ];
48
49type ExceptionList = &'static [(&'static str, &'static str)];
50
51pub(crate) const WORKSPACES: &[(&str, ExceptionList, Option<(&[&str], &[&str])>, &[&str])] = &[
63 (".", EXCEPTIONS, Some((&["rustc-main"], PERMITTED_RUSTC_DEPENDENCIES)), &[]),
65 ("library", EXCEPTIONS_STDLIB, Some((&["sysroot"], PERMITTED_STDLIB_DEPENDENCIES)), &[]),
66 (
68 "compiler/rustc_codegen_cranelift",
69 EXCEPTIONS_CRANELIFT,
70 Some((&["rustc_codegen_cranelift"], PERMITTED_CRANELIFT_DEPENDENCIES)),
71 &[],
72 ),
73 ("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/tools/cargo", EXCEPTIONS_CARGO, None, &["src/tools/cargo"]),
78 ("src/tools/rust-analyzer", EXCEPTIONS_RUST_ANALYZER, None, &[]),
81 ("src/tools/rustbook", EXCEPTIONS_RUSTBOOK, None, &["src/doc/book", "src/doc/reference"]),
82 ("src/tools/rustc-perf", EXCEPTIONS_RUSTC_PERF, None, &["src/tools/rustc-perf"]),
83 ("src/tools/test-float-parse", EXCEPTIONS, None, &[]),
84 ];
86
87#[rustfmt::skip]
92const EXCEPTIONS: ExceptionList = &[
93 ("ar_archive_writer", "Apache-2.0 WITH LLVM-exception"), ("arrayref", "BSD-2-Clause"), ("blake3", "CC0-1.0 OR Apache-2.0 OR Apache-2.0 WITH LLVM-exception"), ("colored", "MPL-2.0"), ("constant_time_eq", "CC0-1.0 OR MIT-0 OR Apache-2.0"), ("dissimilar", "Apache-2.0"), ("fluent-langneg", "Apache-2.0"), ("foldhash", "Zlib"), ("option-ext", "MPL-2.0"), ("rustc_apfloat", "Apache-2.0 WITH LLVM-exception"), ("ryu", "Apache-2.0 OR BSL-1.0"), ("self_cell", "Apache-2.0"), ("wasi-preview1-component-adapter-provider", "Apache-2.0 WITH LLVM-exception"), ];
109
110#[rustfmt::skip]
115const EXCEPTIONS_STDLIB: ExceptionList = &[
116 ("fortanix-sgx-abi", "MPL-2.0"), ];
120
121const EXCEPTIONS_CARGO: ExceptionList = &[
122 ("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"), ("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 ];
147
148const EXCEPTIONS_RUST_ANALYZER: ExceptionList = &[
149 ("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"), ("scip", "Apache-2.0"),
158 ];
160
161const EXCEPTIONS_RUSTC_PERF: ExceptionList = &[
162 ("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), ("ryu", "Apache-2.0 OR BSL-1.0"),
171 ("snap", "BSD-3-Clause"),
172 ("subtle", "BSD-3-Clause"),
173 ];
175
176const EXCEPTIONS_RUSTBOOK: ExceptionList = &[
177 ("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 ];
185
186const EXCEPTIONS_CRANELIFT: ExceptionList = &[
187 ("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 ];
211
212const EXCEPTIONS_GCC: ExceptionList = &[
213 ("gccjit", "GPL-3.0"),
215 ("gccjit_sys", "GPL-3.0"),
216 ];
218
219const EXCEPTIONS_BOOTSTRAP: ExceptionList = &[
220 ("ryu", "Apache-2.0 OR BSL-1.0"), ];
222
223const EXCEPTIONS_UEFI_QEMU_TEST: ExceptionList = &[
224 ("r-efi", "MIT OR Apache-2.0 OR LGPL-2.1-or-later"), ];
226
227const NON_STANDARD_LICENSE: &str = "NON_STANDARD_LICENSE";
229
230const EXCEPTIONS_NON_STANDARD_LICENSE_DEPS: &[&str] = &[
232 "ring",
239];
240
241const PERMITTED_DEPS_LOCATION: &str = concat!(file!(), ":", line!());
242
243const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
248 "adler2",
250 "aho-corasick",
251 "allocator-api2", "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", "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", "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_xorshift", "rand_xoshiro",
361 "redox_syscall",
362 "regex",
363 "regex-automata",
364 "regex-syntax",
365 "rustc-demangle",
366 "rustc-hash",
367 "rustc-literal-escaper",
368 "rustc-stable-hash",
369 "rustc_apfloat",
370 "rustix",
371 "ruzstd", "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-threading",
445 "windows_aarch64_gnullvm",
446 "windows_aarch64_msvc",
447 "windows_i686_gnu",
448 "windows_i686_gnullvm",
449 "windows_i686_msvc",
450 "windows_x86_64_gnu",
451 "windows_x86_64_gnullvm",
452 "windows_x86_64_msvc",
453 "wit-bindgen-rt@0.39.0", "writeable",
455 "yoke",
456 "yoke-derive",
457 "zerocopy",
458 "zerocopy-derive",
459 "zerofrom",
460 "zerofrom-derive",
461 "zerovec",
462 "zerovec-derive",
463 ];
465
466const PERMITTED_STDLIB_DEPENDENCIES: &[&str] = &[
467 "addr2line",
469 "adler2",
470 "cc",
471 "cfg-if",
472 "compiler_builtins",
473 "dlmalloc",
474 "fortanix-sgx-abi",
475 "getopts",
476 "gimli",
477 "hashbrown",
478 "hermit-abi",
479 "libc",
480 "memchr",
481 "miniz_oxide",
482 "object",
483 "r-efi",
484 "r-efi-alloc",
485 "rand",
486 "rand_core",
487 "rand_xorshift",
488 "rustc-demangle",
489 "rustc-literal-escaper",
490 "shlex",
491 "unicode-width",
492 "unwinding",
493 "wasi",
494 "windows-sys",
495 "windows-targets",
496 "windows_aarch64_gnullvm",
497 "windows_aarch64_msvc",
498 "windows_i686_gnu",
499 "windows_i686_gnullvm",
500 "windows_i686_msvc",
501 "windows_x86_64_gnu",
502 "windows_x86_64_gnullvm",
503 "windows_x86_64_msvc",
504 ];
506
507const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
508 "allocator-api2",
510 "anyhow",
511 "arbitrary",
512 "bitflags",
513 "bumpalo",
514 "cfg-if",
515 "cranelift-assembler-x64",
516 "cranelift-assembler-x64-meta",
517 "cranelift-bforest",
518 "cranelift-bitset",
519 "cranelift-codegen",
520 "cranelift-codegen-meta",
521 "cranelift-codegen-shared",
522 "cranelift-control",
523 "cranelift-entity",
524 "cranelift-frontend",
525 "cranelift-isle",
526 "cranelift-jit",
527 "cranelift-module",
528 "cranelift-native",
529 "cranelift-object",
530 "cranelift-srcgen",
531 "crc32fast",
532 "equivalent",
533 "fallible-iterator",
534 "foldhash",
535 "gimli",
536 "hashbrown",
537 "indexmap",
538 "libc",
539 "libloading",
540 "log",
541 "mach2",
542 "memchr",
543 "object",
544 "proc-macro2",
545 "quote",
546 "regalloc2",
547 "region",
548 "rustc-hash",
549 "serde",
550 "serde_derive",
551 "smallvec",
552 "stable_deref_trait",
553 "syn",
554 "target-lexicon",
555 "unicode-ident",
556 "wasmtime-jit-icache-coherence",
557 "windows-sys",
558 "windows-targets",
559 "windows_aarch64_gnullvm",
560 "windows_aarch64_msvc",
561 "windows_i686_gnu",
562 "windows_i686_gnullvm",
563 "windows_i686_msvc",
564 "windows_x86_64_gnu",
565 "windows_x86_64_gnullvm",
566 "windows_x86_64_msvc",
567 ];
569
570pub fn check(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
575 let mut checked_runtime_licenses = false;
576
577 check_proc_macro_dep_list(root, cargo, bless, bad);
578
579 for &(workspace, exceptions, permitted_deps, submodules) in WORKSPACES {
580 if has_missing_submodule(root, submodules) {
581 continue;
582 }
583
584 if !root.join(workspace).join("Cargo.lock").exists() {
585 tidy_error!(bad, "the `{workspace}` workspace doesn't have a Cargo.lock");
586 continue;
587 }
588
589 let mut cmd = cargo_metadata::MetadataCommand::new();
590 cmd.cargo_path(cargo)
591 .manifest_path(root.join(workspace).join("Cargo.toml"))
592 .features(cargo_metadata::CargoOpt::AllFeatures)
593 .other_options(vec!["--locked".to_owned()]);
594 let metadata = t!(cmd.exec());
595
596 check_license_exceptions(&metadata, exceptions, bad);
597 if let Some((crates, permitted_deps)) = permitted_deps {
598 check_permitted_dependencies(&metadata, workspace, permitted_deps, crates, bad);
599 }
600
601 if workspace == "library" {
602 check_runtime_license_exceptions(&metadata, bad);
603 checked_runtime_licenses = true;
604 }
605 }
606
607 assert!(checked_runtime_licenses);
610}
611
612fn check_proc_macro_dep_list(root: &Path, cargo: &Path, bless: bool, bad: &mut bool) {
614 let mut cmd = cargo_metadata::MetadataCommand::new();
615 cmd.cargo_path(cargo)
616 .manifest_path(root.join("Cargo.toml"))
617 .features(cargo_metadata::CargoOpt::AllFeatures)
618 .other_options(vec!["--locked".to_owned()]);
619 let metadata = t!(cmd.exec());
620 let is_proc_macro_pkg = |pkg: &Package| pkg.targets.iter().any(|target| target.is_proc_macro());
621
622 let mut proc_macro_deps = HashSet::new();
623 for pkg in metadata.packages.iter().filter(|pkg| is_proc_macro_pkg(*pkg)) {
624 deps_of(&metadata, &pkg.id, &mut proc_macro_deps);
625 }
626 proc_macro_deps.retain(|pkg| !is_proc_macro_pkg(&metadata[pkg]));
628
629 let proc_macro_deps: HashSet<_> =
630 proc_macro_deps.into_iter().map(|dep| metadata[dep].name.clone()).collect();
631 let expected = proc_macro_deps::CRATES.iter().map(|s| s.to_string()).collect::<HashSet<_>>();
632
633 let needs_blessing = proc_macro_deps.difference(&expected).next().is_some()
634 || expected.difference(&proc_macro_deps).next().is_some();
635
636 if needs_blessing && bless {
637 let mut proc_macro_deps: Vec<_> = proc_macro_deps.into_iter().collect();
638 proc_macro_deps.sort();
639 let mut file = File::create(root.join("src/bootstrap/src/utils/proc_macro_deps.rs"))
640 .expect("`proc_macro_deps` should exist");
641 writeln!(
642 &mut file,
643 "/// Do not update manually - use `./x.py test tidy --bless`
644/// Holds all direct and indirect dependencies of proc-macro crates in tree.
645/// See <https://github.com/rust-lang/rust/issues/134863>
646pub static CRATES: &[&str] = &[
647 // tidy-alphabetical-start"
648 )
649 .unwrap();
650 for dep in proc_macro_deps {
651 writeln!(&mut file, " {dep:?},").unwrap();
652 }
653 writeln!(
654 &mut file,
655 " // tidy-alphabetical-end
656];"
657 )
658 .unwrap();
659 } else {
660 let old_bad = *bad;
661
662 for missing in proc_macro_deps.difference(&expected) {
663 tidy_error!(
664 bad,
665 "proc-macro crate dependency `{missing}` is not registered in `src/bootstrap/src/utils/proc_macro_deps.rs`",
666 );
667 }
668 for extra in expected.difference(&proc_macro_deps) {
669 tidy_error!(
670 bad,
671 "`{extra}` is registered in `src/bootstrap/src/utils/proc_macro_deps.rs`, but is not a proc-macro crate dependency",
672 );
673 }
674 if *bad != old_bad {
675 eprintln!("Run `./x.py test tidy --bless` to regenerate the list");
676 }
677 }
678}
679
680pub fn has_missing_submodule(root: &Path, submodules: &[&str]) -> bool {
684 !CiEnv::is_ci()
685 && submodules.iter().any(|submodule| {
686 let path = root.join(submodule);
687 !path.exists()
688 || read_dir(path).unwrap().next().is_none()
690 })
691}
692
693fn check_runtime_license_exceptions(metadata: &Metadata, bad: &mut bool) {
698 for pkg in &metadata.packages {
699 if pkg.source.is_none() {
700 continue;
702 }
703 let license = match &pkg.license {
704 Some(license) => license,
705 None => {
706 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
707 continue;
708 }
709 };
710 if !LICENSES.contains(&license.as_str()) {
711 if pkg.name == "fortanix-sgx-abi" && pkg.license.as_deref() == Some("MPL-2.0") {
716 continue;
717 }
718
719 tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
720 }
721 }
722}
723
724fn check_license_exceptions(metadata: &Metadata, exceptions: &[(&str, &str)], bad: &mut bool) {
728 for (name, license) in exceptions {
730 if !metadata.packages.iter().any(|p| p.name == *name) {
732 tidy_error!(
733 bad,
734 "could not find exception package `{}`\n\
735 Remove from EXCEPTIONS list if it is no longer used.",
736 name
737 );
738 }
739 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
741 match &pkg.license {
742 None => {
743 if *license == NON_STANDARD_LICENSE
744 && EXCEPTIONS_NON_STANDARD_LICENSE_DEPS.contains(&pkg.name.as_str())
745 {
746 continue;
747 }
748 tidy_error!(
749 bad,
750 "dependency exception `{}` does not declare a license expression",
751 pkg.id
752 );
753 }
754 Some(pkg_license) => {
755 if pkg_license.as_str() != *license {
756 println!("dependency exception `{name}` license has changed");
757 println!(" previously `{license}` now `{pkg_license}`");
758 println!(" update EXCEPTIONS for the new license");
759 *bad = true;
760 }
761 }
762 }
763 }
764 }
765
766 let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
767
768 for pkg in &metadata.packages {
770 if pkg.source.is_none() {
771 continue;
773 }
774 if exception_names.contains(&pkg.name.as_str()) {
775 continue;
776 }
777 let license = match &pkg.license {
778 Some(license) => license,
779 None => {
780 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
781 continue;
782 }
783 };
784 if !LICENSES.contains(&license.as_str()) {
785 tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
786 }
787 }
788}
789
790fn check_permitted_dependencies(
795 metadata: &Metadata,
796 descr: &str,
797 permitted_dependencies: &[&'static str],
798 restricted_dependency_crates: &[&'static str],
799 bad: &mut bool,
800) {
801 let mut has_permitted_dep_error = false;
802 let mut deps = HashSet::new();
803 for to_check in restricted_dependency_crates {
804 let to_check = pkg_from_name(metadata, to_check);
805 deps_of(metadata, &to_check.id, &mut deps);
806 }
807
808 for permitted in permitted_dependencies {
810 fn compare(pkg: &Package, permitted: &str) -> bool {
811 if let Some((name, version)) = permitted.split_once("@") {
812 let Ok(version) = Version::parse(version) else {
813 return false;
814 };
815 pkg.name == name && pkg.version == version
816 } else {
817 pkg.name == permitted
818 }
819 }
820 if !deps.iter().any(|dep_id| compare(pkg_from_id(metadata, dep_id), permitted)) {
821 tidy_error!(
822 bad,
823 "could not find allowed package `{permitted}`\n\
824 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
825 );
826 has_permitted_dep_error = true;
827 }
828 }
829
830 let permitted_dependencies: HashMap<_, _> = permitted_dependencies
832 .iter()
833 .map(|s| {
834 if let Some((name, version)) = s.split_once('@') {
835 (name, Version::parse(version).ok())
836 } else {
837 (*s, None)
838 }
839 })
840 .collect();
841
842 for dep in deps {
843 let dep = pkg_from_id(metadata, dep);
844 if dep.source.is_some() {
846 let is_eq = if let Some(version) = permitted_dependencies.get(dep.name.as_str()) {
847 if let Some(version) = version { version == &dep.version } else { true }
848 } else {
849 false
850 };
851 if !is_eq {
852 tidy_error!(bad, "Dependency for {descr} not explicitly permitted: {}", dep.id);
853 has_permitted_dep_error = true;
854 }
855 }
856 }
857
858 if has_permitted_dep_error {
859 eprintln!("Go to `{PERMITTED_DEPS_LOCATION}` for the list.");
860 }
861}
862
863fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
865 let mut i = metadata.packages.iter().filter(|p| p.name == name);
866 let result =
867 i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
868 assert!(i.next().is_none(), "more than one package found for `{name}`");
869 result
870}
871
872fn pkg_from_id<'a>(metadata: &'a Metadata, id: &PackageId) -> &'a Package {
873 metadata.packages.iter().find(|p| &p.id == id).unwrap()
874}
875
876fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId, result: &mut HashSet<&'a PackageId>) {
878 if !result.insert(pkg_id) {
879 return;
880 }
881 let node = metadata
882 .resolve
883 .as_ref()
884 .unwrap()
885 .nodes
886 .iter()
887 .find(|n| &n.id == pkg_id)
888 .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
889 for dep in &node.deps {
890 deps_of(metadata, &dep.pkg, result);
891 }
892}