1#![expect(
6 clippy::large_unopt_stack_frames,
7 reason = "the clap::Subcommand derive on `Subcommand` triggers this lint"
8)]
9
10use std::path::{Path, PathBuf};
11
12use clap::{CommandFactory, Parser, ValueEnum};
13use clap_complete::Generator;
14#[cfg(feature = "tracing")]
15use tracing::instrument;
16
17use crate::core::backend::CodegenBackendKind;
18use crate::core::build_steps::perf::PerfArgs;
19use crate::core::build_steps::setup::Profile;
20use crate::core::build_steps::test::TestTarget;
21use crate::core::builder::{Builder, Kind};
22use crate::core::config::Config;
23use crate::core::config::target_selection::{TargetSelectionList, target_selection_list};
24use crate::core::session::Session;
25use crate::utils::helpers;
26
27#[derive(Copy, Clone, Default, Debug, ValueEnum)]
28pub enum Color {
29 Always,
30 Never,
31 #[default]
32 Auto,
33}
34
35#[derive(Copy, Clone, Default, Debug, ValueEnum)]
37pub enum Warnings {
38 Deny,
39 Warn,
40 #[default]
41 Default,
42}
43
44#[derive(Debug, Parser)]
46#[command(
47 override_usage = "x.py <subcommand> [options] [<paths>...]",
48 disable_help_subcommand(true),
49 about = "",
50 next_line_help(false)
51)]
52pub struct Flags {
53 #[command(subcommand)]
54 pub cmd: Subcommand,
55
56 #[arg(global = true, short, long, action = clap::ArgAction::Count, conflicts_with = "quiet")]
57 pub verbose: u8, #[arg(global = true, short, long, conflicts_with = "verbose")]
60 pub quiet: bool,
62 #[arg(global = true, short, long)]
63 pub incremental: bool,
65 #[arg(global = true, long, value_hint = clap::ValueHint::FilePath, value_name = "FILE")]
66 pub config: Option<PathBuf>,
68 #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
69 pub build_dir: Option<PathBuf>,
71
72 #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "BUILD")]
73 pub build: Option<String>,
75
76 #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "HOST", value_parser = target_selection_list)]
77 pub host: Option<TargetSelectionList>,
79
80 #[arg(global = true, long, value_hint = clap::ValueHint::Other, value_name = "TARGET", value_parser = target_selection_list)]
81 pub target: Option<TargetSelectionList>,
83
84 #[arg(global = true, long, value_name = "PATH")]
85 pub exclude: Vec<PathBuf>, #[arg(global = true, long, value_name = "PATH")]
88 pub skip: Vec<PathBuf>,
90 #[arg(global = true, long)]
91 pub include_default_paths: bool,
93
94 #[arg(global = true, value_hint = clap::ValueHint::Other, long)]
96 pub rustc_error_format: Option<String>,
97
98 #[arg(global = true, long, value_hint = clap::ValueHint::CommandString, value_name = "CMD")]
99 pub on_fail: Option<String>,
101 #[arg(global = true, long)]
102 pub dry_run: bool,
104 #[arg(global = true, long)]
106 pub dump_bootstrap_shims: bool,
107 #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
108 pub stage: Option<u32>,
111
112 #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
113 pub keep_stage: Vec<u32>,
116 #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "N")]
117 pub keep_stage_std: Vec<u32>,
120 #[arg(global = true, long, value_hint = clap::ValueHint::DirPath, value_name = "DIR")]
121 pub src: Option<PathBuf>,
123
124 #[arg(
125 global = true,
126 short,
127 long,
128 value_hint = clap::ValueHint::Other,
129 value_name = "JOBS"
130 )]
131 pub jobs: Option<u32>,
133 #[arg(global = true, long)]
136 #[arg(value_enum, default_value_t=Warnings::Default, value_name = "deny|warn")]
137 pub warnings: Warnings,
141
142 #[arg(global = true, long)]
143 pub json_output: bool,
145 #[arg(global = true, long)]
146 pub compile_time_deps: bool,
148
149 #[arg(global = true, long, value_name = "STYLE")]
150 #[arg(value_enum, default_value_t = Color::Auto)]
151 pub color: Color,
153
154 #[arg(global = true, long)]
155 pub bypass_bootstrap_lock: bool,
160
161 #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
163 pub rust_profile_generate: Option<PathBuf>,
165 #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
168 pub rust_profile_use: Option<PathBuf>,
169 #[arg(global = true, value_hint = clap::ValueHint::FilePath, long, value_name = "PROFILE")]
172 pub llvm_profile_use: Option<PathBuf>,
173 #[arg(global = true, long)]
180 pub llvm_profile_generate: bool,
181 #[arg(global = true, long)]
183 pub enable_bolt_settings: bool,
184 #[arg(global = true, long)]
186 pub skip_stage0_validation: bool,
187 #[arg(global = true, long)]
189 pub reproducible_artifact: Vec<String>,
190 #[arg(global = true)]
191 pub paths: Vec<PathBuf>,
193 #[arg(global = true, value_hint = clap::ValueHint::Other, long, value_name = "section.option=value")]
195 pub set: Vec<String>,
196 #[arg(global = true, last(true), value_name = "ARGS")]
198 pub free_args: Vec<String>,
199 #[arg(global = true, long, value_name = "bool")]
201 pub ci: Option<bool>,
202 #[arg(global = true, long)]
206 pub skip_std_check_if_no_download_rustc: bool,
207}
208
209impl Flags {
210 pub fn try_parse_verbose_help(args: &[String]) -> bool {
213 #[derive(Parser)]
215 #[command(disable_help_flag(true))]
216 struct HelpVerboseOnly {
217 #[arg(short, long)]
218 help: bool,
219 #[arg(global = true, short, long, action = clap::ArgAction::Count)]
220 pub verbose: u8,
221 #[arg(value_enum)]
222 cmd: Kind,
223 }
224 if let Ok(HelpVerboseOnly { help: true, verbose: 1.., cmd: subcommand }) =
225 HelpVerboseOnly::try_parse_from(normalize_args(args))
226 {
227 println!("NOTE: updating submodules before printing available paths");
228 let flags = Self::parse(&[String::from("build")]);
229 let config = Config::parse(flags);
230 let sess = Session::new(config);
231 let paths = Builder::get_help(&sess, subcommand);
232 if let Some(s) = paths {
233 println!("{s}");
234 } else {
235 panic!("No paths available for subcommand `{}`", subcommand.as_str());
236 }
237 true
238 } else {
239 false
240 }
241 }
242
243 #[cfg_attr(
244 feature = "tracing",
245 instrument(level = "trace", name = "Flags::parse", skip_all, fields(args = ?args))
246 )]
247 pub fn parse(args: &[String]) -> Self {
248 Flags::parse_from(normalize_args(args))
249 }
250}
251
252fn normalize_args(args: &[String]) -> Vec<String> {
253 let first = String::from("x.py");
254 let it = std::iter::once(first).chain(args.iter().cloned());
255 it.collect()
256}
257
258#[derive(Debug, Clone, clap::Subcommand)]
259pub enum Subcommand {
260 #[command(visible_aliases = ["b"], long_about = "\n
261 Arguments:
262 This subcommand accepts a number of paths to directories to the crates
263 and/or artifacts to compile. For example, for a quick build of a usable
264 compiler:
265 ./x.py build --stage 1 library/std
266 This will build a compiler and standard library from the local source code.
267 Once this is done, build/$ARCH/stage1 contains a usable compiler.
268 If no arguments are passed then the default artifacts for that stage are
269 compiled. For example:
270 ./x.py build --stage 0
271 ./x.py build ")]
272 Build {
274 #[arg(long)]
275 timings: bool,
277 },
278 #[command(visible_aliases = ["c"], long_about = "\n
279 Arguments:
280 This subcommand accepts a number of paths to directories to the crates
281 and/or artifacts to compile. For example:
282 ./x.py check library/std
283 If no arguments are passed then many artifacts are checked.")]
284 Check {
286 #[arg(long)]
287 all_targets: bool,
289 #[arg(long)]
290 timings: bool,
292 },
293 #[command(long_about = "\n
295 Arguments:
296 This subcommand accepts a number of paths to directories to the crates
297 and/or artifacts to run clippy against. For example:
298 ./x.py clippy library/core
299 ./x.py clippy library/core library/proc_macro")]
300 Clippy {
301 #[arg(long)]
302 fix: bool,
303 #[arg(long, requires = "fix")]
304 allow_dirty: bool,
305 #[arg(long, requires = "fix")]
306 allow_staged: bool,
307 #[arg(global = true, short = 'A', action = clap::ArgAction::Append, value_name = "LINT")]
309 allow: Vec<String>,
310 #[arg(global = true, short = 'D', action = clap::ArgAction::Append, value_name = "LINT")]
312 deny: Vec<String>,
313 #[arg(global = true, short = 'W', action = clap::ArgAction::Append, value_name = "LINT")]
315 warn: Vec<String>,
316 #[arg(global = true, short = 'F', action = clap::ArgAction::Append, value_name = "LINT")]
318 forbid: Vec<String>,
319 },
320
321 #[command(long_about = "\n
323 Arguments:
324 This subcommand accepts a number of paths to directories to the crates
325 and/or artifacts to run `cargo fix` against. For example:
326 ./x.py fix library/core
327 ./x.py fix library/core library/proc_macro")]
328 Fix {
329 #[arg(long)]
332 allow_dirty: bool,
333 },
334
335 #[command(
337 name = "fmt",
338 long_about = "\n
339 Arguments:
340 This subcommand optionally accepts a `--check` flag which succeeds if
341 formatting is correct and fails if it is not. For example:
342 ./x.py fmt
343 ./x.py fmt --check"
344 )]
345 Format {
346 #[arg(long)]
348 check: bool,
349
350 #[arg(long)]
352 all: bool,
353 },
354 #[command(visible_aliases = ["d"], long_about = "\n
355 Arguments:
356 This subcommand accepts a number of paths to directories of documentation
357 to build. For example:
358 ./x.py doc src/doc/book
359 ./x.py doc src/doc/nomicon
360 ./x.py doc src/doc/book library/std
361 ./x.py doc library/std --json
362 ./x.py doc library/std --open
363 If no arguments are passed then everything is documented:
364 ./x.py doc
365 ./x.py doc --stage 1")]
366 Doc {
368 #[arg(long)]
369 open: bool,
371 #[arg(long)]
372 json: bool,
374 },
375 #[command(visible_aliases = ["t"], long_about = "\n
376 Arguments:
377 This subcommand accepts a number of paths to test directories that
378 should be compiled and run. For example:
379 ./x.py test tests/ui
380 ./x.py test library/std --test-args hash_map
381 ./x.py test library/std --stage 0 --all-targets
382 ./x.py test tests/ui --bless
383 ./x.py test tests/ui --compare-mode next-solver
384 Note that `test tests/* --stage N` does NOT depend on `build compiler/rustc --stage N`;
385 just like `build library/std --stage N` it tests the compiler produced by the previous
386 stage.
387 Execute tool tests with a tool name argument:
388 ./x.py test tidy
389 If no arguments are passed then the complete artifacts for that stage are
390 compiled and tested.
391 ./x.py test
392 ./x.py test --stage 1")]
393 Test {
395 #[arg(long)]
396 no_fail_fast: bool,
398 #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
399 test_args: Vec<String>,
402 #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
404 compiletest_rustc_args: Vec<String>,
405 #[arg(long)]
406 all_targets: bool,
408 #[arg(long)]
409 doc: bool,
411 #[arg(long)]
413 tests: bool,
414 #[arg(long)]
415 bless: bool,
417 #[arg(long)]
418 extra_checks: Option<String>,
424 #[arg(long)]
425 force_rerun: bool,
427 #[arg(long)]
428 only_modified: bool,
430 #[arg(long, value_name = "COMPARE MODE")]
431 compare_mode: Option<String>,
433 #[arg(long, value_name = "check | build | run")]
434 pass: Option<String>,
436 #[arg(long, value_name = "auto | always | never")]
437 run: Option<String>,
439 #[arg(long)]
440 rustfix_coverage: bool,
443 #[arg(long)]
444 no_capture: bool,
446 #[arg(long, default_value_t = true, action = clap::ArgAction::Set, default_missing_value = "true", num_args = 0..=1, require_equals = true)]
447 verbose_run_make_subprocess_output: bool,
450 #[arg(long)]
451 test_codegen_backend: Option<CodegenBackendKind>,
453 #[arg(long)]
454 bypass_ignore_backends: bool,
456
457 #[arg(long)]
459 #[doc(hidden)]
460 no_doc: bool,
461
462 #[arg(long)]
466 record: bool,
467 #[arg(long)]
469 rerun: bool,
470 },
471 Miri {
473 #[arg(long)]
474 no_fail_fast: bool,
476 #[arg(long, value_name = "ARGS", allow_hyphen_values(true))]
477 test_args: Vec<String>,
480 #[arg(long)]
481 all_targets: bool,
483 #[arg(long)]
484 doc: bool,
486 #[arg(long)]
488 tests: bool,
489
490 #[arg(long)]
492 #[doc(hidden)]
493 no_doc: bool,
494 },
495 Bench {
497 #[arg(long, allow_hyphen_values(true))]
498 test_args: Vec<String>,
499 },
500 Clean {
502 #[arg(long)]
503 all: bool,
505 #[arg(long, value_name = "N")]
506 stage: Option<u32>,
508 },
509 Dist,
511 Install,
513 #[command(visible_aliases = ["r"], long_about = "\n
514 Arguments:
515 This subcommand accepts a number of paths to tools to build and run. For
516 example:
517 ./x.py run src/tools/bump-stage0
518 At least a tool needs to be called.")]
519 Run {
521 #[arg(long, allow_hyphen_values(true))]
523 args: Vec<String>,
524 },
525 #[command(long_about = format!(
527 "\n
528x.py setup creates a `bootstrap.toml` which changes the defaults for x.py itself,
529as well as setting up a git pre-push hook, VS Code config and toolchain link.
530Arguments:
531 This subcommand accepts a 'profile' to use for builds. For example:
532 ./x.py setup library
533 The profile is optional and you will be prompted interactively if it is not given.
534 The following profiles are available:
535{}
536 To only set up the git hook, editor config or toolchain link, you may use
537 ./x.py setup hook
538 ./x.py setup editor
539 ./x.py setup link", Profile::all_for_help(" ").trim_end()))]
540 Setup {
541 #[arg(value_name = "<PROFILE>|hook|editor|link")]
544 profile: Option<PathBuf>,
545 },
546 Vendor {
548 #[arg(long)]
550 sync: Vec<PathBuf>,
551 #[arg(long)]
553 versioned_dirs: bool,
554 },
555 Perf(PerfArgs),
557}
558
559impl Default for Subcommand {
560 fn default() -> Self {
561 Subcommand::Build { timings: false }
562 }
563}
564
565impl Subcommand {
566 pub fn compiletest_rustc_args(&self) -> Vec<&str> {
567 match *self {
568 Subcommand::Test { ref compiletest_rustc_args, .. } => {
569 compiletest_rustc_args.iter().flat_map(|s| s.split_whitespace()).collect()
570 }
571 _ => vec![],
572 }
573 }
574
575 pub fn fail_fast(&self) -> bool {
576 match *self {
577 Subcommand::Test { no_fail_fast, .. } | Subcommand::Miri { no_fail_fast, .. } => {
578 !no_fail_fast
579 }
580 _ => false,
581 }
582 }
583
584 pub fn test_target(&self) -> TestTarget {
585 match *self {
586 Subcommand::Test { mut all_targets, doc, tests, no_doc, .. }
587 | Subcommand::Miri { mut all_targets, doc, tests, no_doc, .. } => {
588 all_targets = all_targets || no_doc;
590
591 match (all_targets, doc, tests) {
592 (true, true, _) | (true, _, true) | (_, true, true) => {
593 panic!("You can only set one of `--all-targets`, `--doc` and `--tests`.")
594 }
595 (true, false, false) => TestTarget::AllTargets,
596 (false, true, false) => TestTarget::DocOnly,
597 (false, false, true) => TestTarget::Tests,
598 (false, false, false) => TestTarget::Default,
599 }
600 }
601 _ => TestTarget::Default,
602 }
603 }
604
605 pub fn no_doc(&self) -> bool {
606 match *self {
607 Subcommand::Test { no_doc, .. } | Subcommand::Miri { no_doc, .. } => no_doc,
608 _ => false,
609 }
610 }
611
612 pub fn bless(&self) -> bool {
613 match *self {
614 Subcommand::Test { bless, .. } => bless,
615 _ => false,
616 }
617 }
618
619 pub fn extra_checks(&self) -> Option<&str> {
620 match *self {
621 Subcommand::Test { ref extra_checks, .. } => extra_checks.as_ref().map(String::as_str),
622 _ => None,
623 }
624 }
625
626 pub fn only_modified(&self) -> bool {
627 match *self {
628 Subcommand::Test { only_modified, .. } => only_modified,
629 _ => false,
630 }
631 }
632
633 pub fn force_rerun(&self) -> bool {
634 match *self {
635 Subcommand::Test { force_rerun, .. } => force_rerun,
636 _ => false,
637 }
638 }
639
640 pub fn no_capture(&self) -> bool {
641 match *self {
642 Subcommand::Test { no_capture, .. } => no_capture,
643 _ => false,
644 }
645 }
646
647 pub fn verbose_run_make_subprocess_output(&self) -> bool {
648 match *self {
649 Subcommand::Test { verbose_run_make_subprocess_output, .. } => {
650 verbose_run_make_subprocess_output
651 }
652 _ => true,
653 }
654 }
655
656 pub fn rustfix_coverage(&self) -> bool {
657 match *self {
658 Subcommand::Test { rustfix_coverage, .. } => rustfix_coverage,
659 _ => false,
660 }
661 }
662
663 pub fn compare_mode(&self) -> Option<&str> {
664 match *self {
665 Subcommand::Test { ref compare_mode, .. } => compare_mode.as_ref().map(|s| &s[..]),
666 _ => None,
667 }
668 }
669
670 pub fn pass(&self) -> Option<&str> {
671 match *self {
672 Subcommand::Test { ref pass, .. } => pass.as_ref().map(|s| &s[..]),
673 _ => None,
674 }
675 }
676
677 pub fn run(&self) -> Option<&str> {
678 match *self {
679 Subcommand::Test { ref run, .. } => run.as_ref().map(|s| &s[..]),
680 _ => None,
681 }
682 }
683
684 pub fn open(&self) -> bool {
685 match *self {
686 Subcommand::Doc { open, .. } => open,
687 _ => false,
688 }
689 }
690
691 pub fn json(&self) -> bool {
692 match *self {
693 Subcommand::Doc { json, .. } => json,
694 _ => false,
695 }
696 }
697
698 pub fn timings(&self) -> bool {
699 match *self {
700 Subcommand::Build { timings, .. } | Subcommand::Check { timings, .. } => timings,
701 _ => false,
702 }
703 }
704
705 pub fn vendor_versioned_dirs(&self) -> bool {
706 match *self {
707 Subcommand::Vendor { versioned_dirs, .. } => versioned_dirs,
708 _ => false,
709 }
710 }
711
712 pub fn vendor_sync_args(&self) -> Vec<PathBuf> {
713 match self {
714 Subcommand::Vendor { sync, .. } => sync.clone(),
715 _ => vec![],
716 }
717 }
718
719 pub fn test_codegen_backend(&self) -> Option<&CodegenBackendKind> {
720 match self {
721 Subcommand::Test { test_codegen_backend, .. } => test_codegen_backend.as_ref(),
722 _ => None,
723 }
724 }
725
726 pub fn bypass_ignore_backends(&self) -> bool {
727 match self {
728 Subcommand::Test { bypass_ignore_backends, .. } => *bypass_ignore_backends,
729 _ => false,
730 }
731 }
732
733 pub fn record(&self) -> bool {
734 match self {
735 Subcommand::Test { record, .. } => *record,
736 _ => false,
737 }
738 }
739
740 pub fn rerun(&self) -> bool {
741 match self {
742 Subcommand::Test { rerun, .. } => *rerun,
743 _ => false,
744 }
745 }
746
747 pub(crate) fn check_all_targets(&self) -> bool {
749 matches!(self, Subcommand::Check { all_targets: true, .. })
750 }
751}
752
753pub fn get_completion(shell: &dyn Generator, path: &Path) -> Option<String> {
756 let mut cmd = Flags::command();
757 let current = if !path.exists() {
758 String::new()
759 } else {
760 std::fs::read_to_string(path).unwrap_or_else(|_| {
761 eprintln!("couldn't read {}", path.display());
762 helpers::exit_process(1);
763 })
764 };
765 let mut buf = Vec::new();
766 let (bin_name, _) = path
767 .file_name()
768 .expect("path should be a regular file")
769 .to_str()
770 .expect("file name should be UTF-8")
771 .rsplit_once('.')
772 .expect("file name should have an extension");
773
774 cmd.set_bin_name(bin_name);
777 cmd.build();
778 shell.generate(&cmd, &mut buf);
779 if buf == current.as_bytes() {
780 return None;
781 }
782 Some(String::from_utf8(buf).expect("completion script should be UTF-8"))
783}
784
785pub fn top_level_help() -> String {
787 let mut cmd = Flags::command();
788 cmd.render_help().to_string()
789}