]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/lib.rs
Rollup merge of #73362 - erikdesjardins:bounds, r=nikomatsakis
[rust.git] / src / bootstrap / lib.rs
1 //! Implementation of rustbuild, the Rust build system.
2 //!
3 //! This module, and its descendants, are the implementation of the Rust build
4 //! system. Most of this build system is backed by Cargo but the outer layer
5 //! here serves as the ability to orchestrate calling Cargo, sequencing Cargo
6 //! builds, building artifacts like LLVM, etc. The goals of rustbuild are:
7 //!
8 //! * To be an easily understandable, easily extensible, and maintainable build
9 //!   system.
10 //! * Leverage standard tools in the Rust ecosystem to build the compiler, aka
11 //!   crates.io and Cargo.
12 //! * A standard interface to build across all platforms, including MSVC
13 //!
14 //! ## Architecture
15 //!
16 //! The build system defers most of the complicated logic managing invocations
17 //! of rustc and rustdoc to Cargo itself. However, moving through various stages
18 //! and copying artifacts is still necessary for it to do. Each time rustbuild
19 //! is invoked, it will iterate through the list of predefined steps and execute
20 //! each serially in turn if it matches the paths passed or is a default rule.
21 //! For each step rustbuild relies on the step internally being incremental and
22 //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded
23 //! to appropriate test harnesses and such.
24 //!
25 //! Most of the "meaty" steps that matter are backed by Cargo, which does indeed
26 //! have its own parallelism and incremental management. Later steps, like
27 //! tests, aren't incremental and simply run the entire suite currently.
28 //! However, compiletest itself tries to avoid running tests when the artifacts
29 //! that are involved (mainly the compiler) haven't changed.
30 //!
31 //! When you execute `x.py build`, the steps executed are:
32 //!
33 //! * First, the python script is run. This will automatically download the
34 //!   stage0 rustc and cargo according to `src/stage0.txt`, or use the cached
35 //!   versions if they're available. These are then used to compile rustbuild
36 //!   itself (using Cargo). Finally, control is then transferred to rustbuild.
37 //!
38 //! * Rustbuild takes over, performs sanity checks, probes the environment,
39 //!   reads configuration, and starts executing steps as it reads the command
40 //!   line arguments (paths) or going through the default rules.
41 //!
42 //!   The build output will be something like the following:
43 //!
44 //!   Building stage0 std artifacts
45 //!   Copying stage0 std
46 //!   Building stage0 test artifacts
47 //!   Copying stage0 test
48 //!   Building stage0 compiler artifacts
49 //!   Copying stage0 rustc
50 //!   Assembling stage1 compiler
51 //!   Building stage1 std artifacts
52 //!   Copying stage1 std
53 //!   Building stage1 test artifacts
54 //!   Copying stage1 test
55 //!   Building stage1 compiler artifacts
56 //!   Copying stage1 rustc
57 //!   Assembling stage2 compiler
58 //!   Uplifting stage1 std
59 //!   Uplifting stage1 test
60 //!   Uplifting stage1 rustc
61 //!
62 //! Let's disect that a little:
63 //!
64 //! ## Building stage0 {std,test,compiler} artifacts
65 //!
66 //! These steps use the provided (downloaded, usually) compiler to compile the
67 //! local Rust source into libraries we can use.
68 //!
69 //! ## Copying stage0 {std,test,rustc}
70 //!
71 //! This copies the build output from Cargo into
72 //! `build/$HOST/stage0-sysroot/lib/rustlib/$ARCH/lib`. FIXME: this step's
73 //! documentation should be expanded -- the information already here may be
74 //! incorrect.
75 //!
76 //! ## Assembling stage1 compiler
77 //!
78 //! This copies the libraries we built in "building stage0 ... artifacts" into
79 //! the stage1 compiler's lib directory. These are the host libraries that the
80 //! compiler itself uses to run. These aren't actually used by artifacts the new
81 //! compiler generates. This step also copies the rustc and rustdoc binaries we
82 //! generated into build/$HOST/stage/bin.
83 //!
84 //! The stage1/bin/rustc is a fully functional compiler, but it doesn't yet have
85 //! any libraries to link built binaries or libraries to. The next 3 steps will
86 //! provide those libraries for it; they are mostly equivalent to constructing
87 //! the stage1/bin compiler so we don't go through them individually.
88 //!
89 //! ## Uplifting stage1 {std,test,rustc}
90 //!
91 //! This step copies the libraries from the stage1 compiler sysroot into the
92 //! stage2 compiler. This is done to avoid rebuilding the compiler; libraries
93 //! we'd build in this step should be identical (in function, if not necessarily
94 //! identical on disk) so there's no need to recompile the compiler again. Note
95 //! that if you want to, you can enable the full-bootstrap option to change this
96 //! behavior.
97 //!
98 //! Each step is driven by a separate Cargo project and rustbuild orchestrates
99 //! copying files between steps and otherwise preparing for Cargo to run.
100 //!
101 //! ## Further information
102 //!
103 //! More documentation can be found in each respective module below, and you can
104 //! also check out the `src/bootstrap/README.md` file for more information.
105
106 #![feature(drain_filter)]
107
108 use std::cell::{Cell, RefCell};
109 use std::collections::{HashMap, HashSet};
110 use std::env;
111 use std::fs::{self, File, OpenOptions};
112 use std::io::{Read, Seek, SeekFrom, Write};
113 use std::path::{Path, PathBuf};
114 use std::process::{self, Command};
115 use std::slice;
116 use std::str;
117
118 #[cfg(unix)]
119 use std::os::unix::fs::symlink as symlink_file;
120 #[cfg(windows)]
121 use std::os::windows::fs::symlink_file;
122
123 use build_helper::{mtime, output, run, run_suppressed, t, try_run, try_run_suppressed};
124 use filetime::FileTime;
125
126 use crate::util::{exe, libdir, CiEnv};
127
128 mod builder;
129 mod cache;
130 mod cc_detect;
131 mod channel;
132 mod check;
133 mod clean;
134 mod compile;
135 mod config;
136 mod dist;
137 mod doc;
138 mod flags;
139 mod format;
140 mod install;
141 mod metadata;
142 mod native;
143 mod run;
144 mod sanity;
145 mod test;
146 mod tool;
147 mod toolstate;
148 pub mod util;
149
150 #[cfg(windows)]
151 mod job;
152
153 #[cfg(all(unix, not(target_os = "haiku")))]
154 mod job {
155     pub unsafe fn setup(build: &mut crate::Build) {
156         if build.config.low_priority {
157             libc::setpriority(libc::PRIO_PGRP as _, 0, 10);
158         }
159     }
160 }
161
162 #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
163 mod job {
164     pub unsafe fn setup(_build: &mut crate::Build) {}
165 }
166
167 use crate::cache::{Interned, INTERNER};
168 pub use crate::config::Config;
169 use crate::flags::Subcommand;
170
171 const LLVM_TOOLS: &[&str] = &[
172     "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
173     "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
174     "llvm-objdump", // used to disassemble programs
175     "llvm-profdata", // used to inspect and merge files generated by profiles
176     "llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
177     "llvm-size", // used to prints the size of the linker sections of a program
178     "llvm-strip", // used to discard symbols from binary files to reduce their size
179     "llvm-ar", // used for creating and modifying archive files
180 ];
181
182 /// A structure representing a Rust compiler.
183 ///
184 /// Each compiler has a `stage` that it is associated with and a `host` that
185 /// corresponds to the platform the compiler runs on. This structure is used as
186 /// a parameter to many methods below.
187 #[derive(Eq, PartialOrd, Ord, PartialEq, Clone, Copy, Hash, Debug)]
188 pub struct Compiler {
189     stage: u32,
190     host: Interned<String>,
191 }
192
193 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
194 pub enum DocTests {
195     /// Run normal tests and doc tests (default).
196     Yes,
197     /// Do not run any doc tests.
198     No,
199     /// Only run doc tests.
200     Only,
201 }
202
203 pub enum GitRepo {
204     Rustc,
205     Llvm,
206 }
207
208 /// Global configuration for the build system.
209 ///
210 /// This structure transitively contains all configuration for the build system.
211 /// All filesystem-encoded configuration is in `config`, all flags are in
212 /// `flags`, and then parsed or probed information is listed in the keys below.
213 ///
214 /// This structure is a parameter of almost all methods in the build system,
215 /// although most functions are implemented as free functions rather than
216 /// methods specifically on this structure itself (to make it easier to
217 /// organize).
218 pub struct Build {
219     /// User-specified configuration from `config.toml`.
220     config: Config,
221
222     // Properties derived from the above configuration
223     src: PathBuf,
224     out: PathBuf,
225     rust_info: channel::GitInfo,
226     cargo_info: channel::GitInfo,
227     rls_info: channel::GitInfo,
228     clippy_info: channel::GitInfo,
229     miri_info: channel::GitInfo,
230     rustfmt_info: channel::GitInfo,
231     in_tree_llvm_info: channel::GitInfo,
232     local_rebuild: bool,
233     fail_fast: bool,
234     doc_tests: DocTests,
235     verbosity: usize,
236
237     // Targets for which to build
238     build: Interned<String>,
239     hosts: Vec<Interned<String>>,
240     targets: Vec<Interned<String>>,
241
242     // Stage 0 (downloaded) compiler, lld and cargo or their local rust equivalents
243     initial_rustc: PathBuf,
244     initial_cargo: PathBuf,
245     initial_lld: PathBuf,
246     initial_libdir: PathBuf,
247
248     // Runtime state filled in later on
249     // C/C++ compilers and archiver for all targets
250     cc: HashMap<Interned<String>, cc::Tool>,
251     cxx: HashMap<Interned<String>, cc::Tool>,
252     ar: HashMap<Interned<String>, PathBuf>,
253     ranlib: HashMap<Interned<String>, PathBuf>,
254     // Miscellaneous
255     crates: HashMap<Interned<String>, Crate>,
256     is_sudo: bool,
257     ci_env: CiEnv,
258     delayed_failures: RefCell<Vec<String>>,
259     prerelease_version: Cell<Option<u32>>,
260     tool_artifacts:
261         RefCell<HashMap<Interned<String>, HashMap<String, (&'static str, PathBuf, Vec<String>)>>>,
262 }
263
264 #[derive(Debug)]
265 struct Crate {
266     name: Interned<String>,
267     deps: HashSet<Interned<String>>,
268     id: String,
269     path: PathBuf,
270 }
271
272 impl Crate {
273     fn is_local(&self, build: &Build) -> bool {
274         self.path.starts_with(&build.config.src) && !self.path.to_string_lossy().ends_with("_shim")
275     }
276
277     fn local_path(&self, build: &Build) -> PathBuf {
278         assert!(self.is_local(build));
279         self.path.strip_prefix(&build.config.src).unwrap().into()
280     }
281 }
282
283 /// When building Rust various objects are handled differently.
284 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
285 pub enum DependencyType {
286     /// Libraries originating from proc-macros.
287     Host,
288     /// Typical Rust libraries.
289     Target,
290     /// Non Rust libraries and objects shipped to ease usage of certain targets.
291     TargetSelfContained,
292 }
293
294 /// The various "modes" of invoking Cargo.
295 ///
296 /// These entries currently correspond to the various output directories of the
297 /// build system, with each mod generating output in a different directory.
298 #[derive(Debug, Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
299 pub enum Mode {
300     /// Build the standard library, placing output in the "stageN-std" directory.
301     Std,
302
303     /// Build librustc, and compiler libraries, placing output in the "stageN-rustc" directory.
304     Rustc,
305
306     /// Build codegen libraries, placing output in the "stageN-codegen" directory
307     Codegen,
308
309     /// Build some tools, placing output in the "stageN-tools" directory. The
310     /// "other" here is for miscellaneous sets of tools that are built using the
311     /// bootstrap compiler in its entirety (target libraries and all).
312     /// Typically these tools compile with stable Rust.
313     ToolBootstrap,
314
315     /// Compile a tool which uses all libraries we compile (up to rustc).
316     /// Doesn't use the stage0 compiler libraries like "other", and includes
317     /// tools like rustdoc, cargo, rls, etc.
318     ToolStd,
319     ToolRustc,
320 }
321
322 impl Mode {
323     pub fn is_tool(&self) -> bool {
324         match self {
325             Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd => true,
326             _ => false,
327         }
328     }
329 }
330
331 impl Build {
332     /// Creates a new set of build configuration from the `flags` on the command
333     /// line and the filesystem `config`.
334     ///
335     /// By default all build output will be placed in the current directory.
336     pub fn new(config: Config) -> Build {
337         let src = config.src.clone();
338         let out = config.out.clone();
339
340         let is_sudo = match env::var_os("SUDO_USER") {
341             Some(sudo_user) => match env::var_os("USER") {
342                 Some(user) => user != sudo_user,
343                 None => false,
344             },
345             None => false,
346         };
347
348         let ignore_git = config.ignore_git;
349         let rust_info = channel::GitInfo::new(ignore_git, &src);
350         let cargo_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/cargo"));
351         let rls_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rls"));
352         let clippy_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/clippy"));
353         let miri_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/miri"));
354         let rustfmt_info = channel::GitInfo::new(ignore_git, &src.join("src/tools/rustfmt"));
355
356         // we always try to use git for LLVM builds
357         let in_tree_llvm_info = channel::GitInfo::new(false, &src.join("src/llvm-project"));
358
359         let initial_target_libdir_str = if config.dry_run {
360             "/dummy/lib/path/to/lib/".to_string()
361         } else {
362             output(
363                 Command::new(&config.initial_rustc)
364                     .arg("--target")
365                     .arg(config.build)
366                     .arg("--print")
367                     .arg("target-libdir"),
368             )
369         };
370         let initial_target_dir = Path::new(&initial_target_libdir_str).parent().unwrap();
371         let initial_lld = initial_target_dir.join("bin").join("rust-lld");
372
373         let initial_sysroot = if config.dry_run {
374             "/dummy".to_string()
375         } else {
376             output(Command::new(&config.initial_rustc).arg("--print").arg("sysroot"))
377         };
378         let initial_libdir = initial_target_dir
379             .parent()
380             .unwrap()
381             .parent()
382             .unwrap()
383             .strip_prefix(initial_sysroot.trim())
384             .unwrap()
385             .to_path_buf();
386
387         let mut build = Build {
388             initial_rustc: config.initial_rustc.clone(),
389             initial_cargo: config.initial_cargo.clone(),
390             initial_lld,
391             initial_libdir,
392             local_rebuild: config.local_rebuild,
393             fail_fast: config.cmd.fail_fast(),
394             doc_tests: config.cmd.doc_tests(),
395             verbosity: config.verbose,
396
397             build: config.build,
398             hosts: config.hosts.clone(),
399             targets: config.targets.clone(),
400
401             config,
402             src,
403             out,
404
405             rust_info,
406             cargo_info,
407             rls_info,
408             clippy_info,
409             miri_info,
410             rustfmt_info,
411             in_tree_llvm_info,
412             cc: HashMap::new(),
413             cxx: HashMap::new(),
414             ar: HashMap::new(),
415             ranlib: HashMap::new(),
416             crates: HashMap::new(),
417             is_sudo,
418             ci_env: CiEnv::current(),
419             delayed_failures: RefCell::new(Vec::new()),
420             prerelease_version: Cell::new(None),
421             tool_artifacts: Default::default(),
422         };
423
424         build.verbose("finding compilers");
425         cc_detect::find(&mut build);
426         build.verbose("running sanity check");
427         sanity::check(&mut build);
428
429         // If local-rust is the same major.minor as the current version, then force a
430         // local-rebuild
431         let local_version_verbose =
432             output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
433         let local_release = local_version_verbose
434             .lines()
435             .filter(|x| x.starts_with("release:"))
436             .next()
437             .unwrap()
438             .trim_start_matches("release:")
439             .trim();
440         let my_version = channel::CFG_RELEASE_NUM;
441         if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
442             build.verbose(&format!("auto-detected local-rebuild {}", local_release));
443             build.local_rebuild = true;
444         }
445
446         build.verbose("learning about cargo");
447         metadata::build(&mut build);
448
449         build
450     }
451
452     pub fn build_triple(&self) -> &[Interned<String>] {
453         unsafe { slice::from_raw_parts(&self.build, 1) }
454     }
455
456     /// Executes the entire build, as configured by the flags and configuration.
457     pub fn build(&mut self) {
458         unsafe {
459             job::setup(self);
460         }
461
462         if let Subcommand::Format { check } = self.config.cmd {
463             return format::format(self, check);
464         }
465
466         if let Subcommand::Clean { all } = self.config.cmd {
467             return clean::clean(self, all);
468         }
469
470         {
471             let builder = builder::Builder::new(&self);
472             if let Some(path) = builder.paths.get(0) {
473                 if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
474                     return;
475                 }
476             }
477         }
478
479         if !self.config.dry_run {
480             {
481                 self.config.dry_run = true;
482                 let builder = builder::Builder::new(&self);
483                 builder.execute_cli();
484             }
485             self.config.dry_run = false;
486             let builder = builder::Builder::new(&self);
487             builder.execute_cli();
488         } else {
489             let builder = builder::Builder::new(&self);
490             builder.execute_cli();
491         }
492
493         // Check for postponed failures from `test --no-fail-fast`.
494         let failures = self.delayed_failures.borrow();
495         if failures.len() > 0 {
496             println!("\n{} command(s) did not execute successfully:\n", failures.len());
497             for failure in failures.iter() {
498                 println!("  - {}\n", failure);
499             }
500             process::exit(1);
501         }
502     }
503
504     /// Clear out `dir` if `input` is newer.
505     ///
506     /// After this executes, it will also ensure that `dir` exists.
507     fn clear_if_dirty(&self, dir: &Path, input: &Path) -> bool {
508         let stamp = dir.join(".stamp");
509         let mut cleared = false;
510         if mtime(&stamp) < mtime(input) {
511             self.verbose(&format!("Dirty - {}", dir.display()));
512             let _ = fs::remove_dir_all(dir);
513             cleared = true;
514         } else if stamp.exists() {
515             return cleared;
516         }
517         t!(fs::create_dir_all(dir));
518         t!(File::create(stamp));
519         cleared
520     }
521
522     /// Gets the space-separated set of activated features for the standard
523     /// library.
524     fn std_features(&self) -> String {
525         let mut features = "panic-unwind".to_string();
526
527         if self.config.llvm_libunwind {
528             features.push_str(" llvm-libunwind");
529         }
530         if self.config.backtrace {
531             features.push_str(" backtrace");
532         }
533         if self.config.profiler {
534             features.push_str(" profiler");
535         }
536         features
537     }
538
539     /// Gets the space-separated set of activated features for the compiler.
540     fn rustc_features(&self) -> String {
541         let mut features = String::new();
542         if self.config.jemalloc {
543             features.push_str("jemalloc");
544         }
545         if self.config.llvm_enabled() {
546             features.push_str(" llvm");
547         }
548         features
549     }
550
551     /// Component directory that Cargo will produce output into (e.g.
552     /// release/debug)
553     fn cargo_dir(&self) -> &'static str {
554         if self.config.rust_optimize { "release" } else { "debug" }
555     }
556
557     fn tools_dir(&self, compiler: Compiler) -> PathBuf {
558         let out = self.out.join(&*compiler.host).join(format!("stage{}-tools-bin", compiler.stage));
559         t!(fs::create_dir_all(&out));
560         out
561     }
562
563     /// Returns the root directory for all output generated in a particular
564     /// stage when running with a particular host compiler.
565     ///
566     /// The mode indicates what the root directory is for.
567     fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf {
568         let suffix = match mode {
569             Mode::Std => "-std",
570             Mode::Rustc => "-rustc",
571             Mode::Codegen => "-codegen",
572             Mode::ToolBootstrap => "-bootstrap-tools",
573             Mode::ToolStd | Mode::ToolRustc => "-tools",
574         };
575         self.out.join(&*compiler.host).join(format!("stage{}{}", compiler.stage, suffix))
576     }
577
578     /// Returns the root output directory for all Cargo output in a given stage,
579     /// running a particular compiler, whether or not we're building the
580     /// standard library, and targeting the specified architecture.
581     fn cargo_out(&self, compiler: Compiler, mode: Mode, target: Interned<String>) -> PathBuf {
582         self.stage_out(compiler, mode).join(&*target).join(self.cargo_dir())
583     }
584
585     /// Root output directory for LLVM compiled for `target`
586     ///
587     /// Note that if LLVM is configured externally then the directory returned
588     /// will likely be empty.
589     fn llvm_out(&self, target: Interned<String>) -> PathBuf {
590         self.out.join(&*target).join("llvm")
591     }
592
593     fn lld_out(&self, target: Interned<String>) -> PathBuf {
594         self.out.join(&*target).join("lld")
595     }
596
597     /// Output directory for all documentation for a target
598     fn doc_out(&self, target: Interned<String>) -> PathBuf {
599         self.out.join(&*target).join("doc")
600     }
601
602     /// Output directory for all documentation for a target
603     fn compiler_doc_out(&self, target: Interned<String>) -> PathBuf {
604         self.out.join(&*target).join("compiler-doc")
605     }
606
607     /// Output directory for some generated md crate documentation for a target (temporary)
608     fn md_doc_out(&self, target: Interned<String>) -> Interned<PathBuf> {
609         INTERNER.intern_path(self.out.join(&*target).join("md-doc"))
610     }
611
612     /// Output directory for all crate documentation for a target (temporary)
613     ///
614     /// The artifacts here are then copied into `doc_out` above.
615     fn crate_doc_out(&self, target: Interned<String>) -> PathBuf {
616         self.out.join(&*target).join("crate-docs")
617     }
618
619     /// Returns `true` if no custom `llvm-config` is set for the specified target.
620     ///
621     /// If no custom `llvm-config` was specified then Rust's llvm will be used.
622     fn is_rust_llvm(&self, target: Interned<String>) -> bool {
623         match self.config.target_config.get(&target) {
624             Some(ref c) => c.llvm_config.is_none(),
625             None => true,
626         }
627     }
628
629     /// Returns the path to `FileCheck` binary for the specified target
630     fn llvm_filecheck(&self, target: Interned<String>) -> PathBuf {
631         let target_config = self.config.target_config.get(&target);
632         if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) {
633             s.to_path_buf()
634         } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) {
635             let llvm_bindir = output(Command::new(s).arg("--bindir"));
636             let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", &*target));
637             if filecheck.exists() {
638                 filecheck
639             } else {
640                 // On Fedora the system LLVM installs FileCheck in the
641                 // llvm subdirectory of the libdir.
642                 let llvm_libdir = output(Command::new(s).arg("--libdir"));
643                 let lib_filecheck =
644                     Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", &*target));
645                 if lib_filecheck.exists() {
646                     lib_filecheck
647                 } else {
648                     // Return the most normal file name, even though
649                     // it doesn't exist, so that any error message
650                     // refers to that.
651                     filecheck
652                 }
653             }
654         } else {
655             let base = self.llvm_out(self.config.build).join("build");
656             let base = if !self.config.ninja && self.config.build.contains("msvc") {
657                 if self.config.llvm_optimize {
658                     if self.config.llvm_release_debuginfo {
659                         base.join("RelWithDebInfo")
660                     } else {
661                         base.join("Release")
662                     }
663                 } else {
664                     base.join("Debug")
665                 }
666             } else {
667                 base
668             };
669             base.join("bin").join(exe("FileCheck", &*target))
670         }
671     }
672
673     /// Directory for libraries built from C/C++ code and shared between stages.
674     fn native_dir(&self, target: Interned<String>) -> PathBuf {
675         self.out.join(&*target).join("native")
676     }
677
678     /// Root output directory for rust_test_helpers library compiled for
679     /// `target`
680     fn test_helpers_out(&self, target: Interned<String>) -> PathBuf {
681         self.native_dir(target).join("rust-test-helpers")
682     }
683
684     /// Adds the `RUST_TEST_THREADS` env var if necessary
685     fn add_rust_test_threads(&self, cmd: &mut Command) {
686         if env::var_os("RUST_TEST_THREADS").is_none() {
687             cmd.env("RUST_TEST_THREADS", self.jobs().to_string());
688         }
689     }
690
691     /// Returns the libdir of the snapshot compiler.
692     fn rustc_snapshot_libdir(&self) -> PathBuf {
693         self.rustc_snapshot_sysroot().join(libdir(&self.config.build))
694     }
695
696     /// Returns the sysroot of the snapshot compiler.
697     fn rustc_snapshot_sysroot(&self) -> &Path {
698         self.initial_rustc.parent().unwrap().parent().unwrap()
699     }
700
701     /// Runs a command, printing out nice contextual information if it fails.
702     fn run(&self, cmd: &mut Command) {
703         if self.config.dry_run {
704             return;
705         }
706         self.verbose(&format!("running: {:?}", cmd));
707         run(cmd)
708     }
709
710     /// Runs a command, printing out nice contextual information if it fails.
711     fn run_quiet(&self, cmd: &mut Command) {
712         if self.config.dry_run {
713             return;
714         }
715         self.verbose(&format!("running: {:?}", cmd));
716         run_suppressed(cmd)
717     }
718
719     /// Runs a command, printing out nice contextual information if it fails.
720     /// Exits if the command failed to execute at all, otherwise returns its
721     /// `status.success()`.
722     fn try_run(&self, cmd: &mut Command) -> bool {
723         if self.config.dry_run {
724             return true;
725         }
726         self.verbose(&format!("running: {:?}", cmd));
727         try_run(cmd)
728     }
729
730     /// Runs a command, printing out nice contextual information if it fails.
731     /// Exits if the command failed to execute at all, otherwise returns its
732     /// `status.success()`.
733     fn try_run_quiet(&self, cmd: &mut Command) -> bool {
734         if self.config.dry_run {
735             return true;
736         }
737         self.verbose(&format!("running: {:?}", cmd));
738         try_run_suppressed(cmd)
739     }
740
741     pub fn is_verbose(&self) -> bool {
742         self.verbosity > 0
743     }
744
745     /// Prints a message if this build is configured in verbose mode.
746     fn verbose(&self, msg: &str) {
747         if self.is_verbose() {
748             println!("{}", msg);
749         }
750     }
751
752     pub fn is_verbose_than(&self, level: usize) -> bool {
753         self.verbosity > level
754     }
755
756     /// Prints a message if this build is configured in more verbose mode than `level`.
757     fn verbose_than(&self, level: usize, msg: &str) {
758         if self.is_verbose_than(level) {
759             println!("{}", msg);
760         }
761     }
762
763     fn info(&self, msg: &str) {
764         if self.config.dry_run {
765             return;
766         }
767         println!("{}", msg);
768     }
769
770     /// Returns the number of parallel jobs that have been configured for this
771     /// build.
772     fn jobs(&self) -> u32 {
773         self.config.jobs.unwrap_or_else(|| num_cpus::get() as u32)
774     }
775
776     fn debuginfo_map_to(&self, which: GitRepo) -> Option<String> {
777         if !self.config.rust_remap_debuginfo {
778             return None;
779         }
780
781         match which {
782             GitRepo::Rustc => {
783                 let sha = self.rust_sha().unwrap_or(channel::CFG_RELEASE_NUM);
784                 Some(format!("/rustc/{}", sha))
785             }
786             GitRepo::Llvm => Some(String::from("/rustc/llvm")),
787         }
788     }
789
790     /// Returns the path to the C compiler for the target specified.
791     fn cc(&self, target: Interned<String>) -> &Path {
792         self.cc[&target].path()
793     }
794
795     /// Returns a list of flags to pass to the C compiler for the target
796     /// specified.
797     fn cflags(&self, target: Interned<String>, which: GitRepo) -> Vec<String> {
798         // Filter out -O and /O (the optimization flags) that we picked up from
799         // cc-rs because the build scripts will determine that for themselves.
800         let mut base = self.cc[&target]
801             .args()
802             .iter()
803             .map(|s| s.to_string_lossy().into_owned())
804             .filter(|s| !s.starts_with("-O") && !s.starts_with("/O"))
805             .collect::<Vec<String>>();
806
807         // If we're compiling on macOS then we add a few unconditional flags
808         // indicating that we want libc++ (more filled out than libstdc++) and
809         // we want to compile for 10.7. This way we can ensure that
810         // LLVM/etc are all properly compiled.
811         if target.contains("apple-darwin") {
812             base.push("-stdlib=libc++".into());
813         }
814
815         // Work around an apparently bad MinGW / GCC optimization,
816         // See: http://lists.llvm.org/pipermail/cfe-dev/2016-December/051980.html
817         // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78936
818         if &*target == "i686-pc-windows-gnu" {
819             base.push("-fno-omit-frame-pointer".into());
820         }
821
822         if let Some(map_to) = self.debuginfo_map_to(which) {
823             let map = format!("{}={}", self.src.display(), map_to);
824             let cc = self.cc(target);
825             if cc.ends_with("clang") || cc.ends_with("gcc") {
826                 base.push(format!("-fdebug-prefix-map={}", map));
827             } else if cc.ends_with("clang-cl.exe") {
828                 base.push("-Xclang".into());
829                 base.push(format!("-fdebug-prefix-map={}", map));
830             }
831         }
832         base
833     }
834
835     /// Returns the path to the `ar` archive utility for the target specified.
836     fn ar(&self, target: Interned<String>) -> Option<&Path> {
837         self.ar.get(&target).map(|p| &**p)
838     }
839
840     /// Returns the path to the `ranlib` utility for the target specified.
841     fn ranlib(&self, target: Interned<String>) -> Option<&Path> {
842         self.ranlib.get(&target).map(|p| &**p)
843     }
844
845     /// Returns the path to the C++ compiler for the target specified.
846     fn cxx(&self, target: Interned<String>) -> Result<&Path, String> {
847         match self.cxx.get(&target) {
848             Some(p) => Ok(p.path()),
849             None => {
850                 Err(format!("target `{}` is not configured as a host, only as a target", target))
851             }
852         }
853     }
854
855     /// Returns the path to the linker for the given target if it needs to be overridden.
856     fn linker(&self, target: Interned<String>, can_use_lld: bool) -> Option<&Path> {
857         if let Some(linker) = self.config.target_config.get(&target).and_then(|c| c.linker.as_ref())
858         {
859             Some(linker)
860         } else if target != self.config.build
861             && util::use_host_linker(&target)
862             && !target.contains("msvc")
863         {
864             Some(self.cc(target))
865         } else if can_use_lld && self.config.use_lld && self.build == target {
866             Some(&self.initial_lld)
867         } else {
868             None
869         }
870     }
871
872     /// Returns if this target should statically link the C runtime, if specified
873     fn crt_static(&self, target: Interned<String>) -> Option<bool> {
874         if target.contains("pc-windows-msvc") {
875             Some(true)
876         } else {
877             self.config.target_config.get(&target).and_then(|t| t.crt_static)
878         }
879     }
880
881     /// Returns the "musl root" for this `target`, if defined
882     fn musl_root(&self, target: Interned<String>) -> Option<&Path> {
883         self.config
884             .target_config
885             .get(&target)
886             .and_then(|t| t.musl_root.as_ref())
887             .or_else(|| self.config.musl_root.as_ref())
888             .map(|p| &**p)
889     }
890
891     /// Returns the sysroot for the wasi target, if defined
892     fn wasi_root(&self, target: Interned<String>) -> Option<&Path> {
893         self.config.target_config.get(&target).and_then(|t| t.wasi_root.as_ref()).map(|p| &**p)
894     }
895
896     /// Returns `true` if this is a no-std `target`, if defined
897     fn no_std(&self, target: Interned<String>) -> Option<bool> {
898         self.config.target_config.get(&target).map(|t| t.no_std)
899     }
900
901     /// Returns `true` if the target will be tested using the `remote-test-client`
902     /// and `remote-test-server` binaries.
903     fn remote_tested(&self, target: Interned<String>) -> bool {
904         self.qemu_rootfs(target).is_some()
905             || target.contains("android")
906             || env::var_os("TEST_DEVICE_ADDR").is_some()
907     }
908
909     /// Returns the root of the "rootfs" image that this target will be using,
910     /// if one was configured.
911     ///
912     /// If `Some` is returned then that means that tests for this target are
913     /// emulated with QEMU and binaries will need to be shipped to the emulator.
914     fn qemu_rootfs(&self, target: Interned<String>) -> Option<&Path> {
915         self.config.target_config.get(&target).and_then(|t| t.qemu_rootfs.as_ref()).map(|p| &**p)
916     }
917
918     /// Path to the python interpreter to use
919     fn python(&self) -> &Path {
920         self.config.python.as_ref().unwrap()
921     }
922
923     /// Temporary directory that extended error information is emitted to.
924     fn extended_error_dir(&self) -> PathBuf {
925         self.out.join("tmp/extended-error-metadata")
926     }
927
928     /// Tests whether the `compiler` compiling for `target` should be forced to
929     /// use a stage1 compiler instead.
930     ///
931     /// Currently, by default, the build system does not perform a "full
932     /// bootstrap" by default where we compile the compiler three times.
933     /// Instead, we compile the compiler two times. The final stage (stage2)
934     /// just copies the libraries from the previous stage, which is what this
935     /// method detects.
936     ///
937     /// Here we return `true` if:
938     ///
939     /// * The build isn't performing a full bootstrap
940     /// * The `compiler` is in the final stage, 2
941     /// * We're not cross-compiling, so the artifacts are already available in
942     ///   stage1
943     ///
944     /// When all of these conditions are met the build will lift artifacts from
945     /// the previous stage forward.
946     fn force_use_stage1(&self, compiler: Compiler, target: Interned<String>) -> bool {
947         !self.config.full_bootstrap
948             && compiler.stage >= 2
949             && (self.hosts.iter().any(|h| *h == target) || target == self.build)
950     }
951
952     /// Given `num` in the form "a.b.c" return a "release string" which
953     /// describes the release version number.
954     ///
955     /// For example on nightly this returns "a.b.c-nightly", on beta it returns
956     /// "a.b.c-beta.1" and on stable it just returns "a.b.c".
957     fn release(&self, num: &str) -> String {
958         match &self.config.channel[..] {
959             "stable" => num.to_string(),
960             "beta" => {
961                 if self.rust_info.is_git() {
962                     format!("{}-beta.{}", num, self.beta_prerelease_version())
963                 } else {
964                     format!("{}-beta", num)
965                 }
966             }
967             "nightly" => format!("{}-nightly", num),
968             _ => format!("{}-dev", num),
969         }
970     }
971
972     fn beta_prerelease_version(&self) -> u32 {
973         if let Some(s) = self.prerelease_version.get() {
974             return s;
975         }
976
977         // Figure out how many merge commits happened since we branched off master.
978         // That's our beta number!
979         // (Note that we use a `..` range, not the `...` symmetric difference.)
980         let count = output(
981             Command::new("git")
982                 .arg("rev-list")
983                 .arg("--count")
984                 .arg("--merges")
985                 .arg("refs/remotes/origin/master..HEAD")
986                 .current_dir(&self.src),
987         );
988         let n = count.trim().parse().unwrap();
989         self.prerelease_version.set(Some(n));
990         n
991     }
992
993     /// Returns the value of `release` above for Rust itself.
994     fn rust_release(&self) -> String {
995         self.release(channel::CFG_RELEASE_NUM)
996     }
997
998     /// Returns the "package version" for a component given the `num` release
999     /// number.
1000     ///
1001     /// The package version is typically what shows up in the names of tarballs.
1002     /// For channels like beta/nightly it's just the channel name, otherwise
1003     /// it's the `num` provided.
1004     fn package_vers(&self, num: &str) -> String {
1005         match &self.config.channel[..] {
1006             "stable" => num.to_string(),
1007             "beta" => "beta".to_string(),
1008             "nightly" => "nightly".to_string(),
1009             _ => format!("{}-dev", num),
1010         }
1011     }
1012
1013     /// Returns the value of `package_vers` above for Rust itself.
1014     fn rust_package_vers(&self) -> String {
1015         self.package_vers(channel::CFG_RELEASE_NUM)
1016     }
1017
1018     /// Returns the value of `package_vers` above for Cargo
1019     fn cargo_package_vers(&self) -> String {
1020         self.package_vers(&self.release_num("cargo"))
1021     }
1022
1023     /// Returns the value of `package_vers` above for rls
1024     fn rls_package_vers(&self) -> String {
1025         self.package_vers(&self.release_num("rls"))
1026     }
1027
1028     /// Returns the value of `package_vers` above for clippy
1029     fn clippy_package_vers(&self) -> String {
1030         self.package_vers(&self.release_num("clippy"))
1031     }
1032
1033     /// Returns the value of `package_vers` above for miri
1034     fn miri_package_vers(&self) -> String {
1035         self.package_vers(&self.release_num("miri"))
1036     }
1037
1038     /// Returns the value of `package_vers` above for rustfmt
1039     fn rustfmt_package_vers(&self) -> String {
1040         self.package_vers(&self.release_num("rustfmt"))
1041     }
1042
1043     fn llvm_tools_package_vers(&self) -> String {
1044         self.package_vers(channel::CFG_RELEASE_NUM)
1045     }
1046
1047     fn llvm_tools_vers(&self) -> String {
1048         self.rust_version()
1049     }
1050
1051     fn llvm_link_tools_dynamically(&self, target: Interned<String>) -> bool {
1052         target.contains("linux-gnu") || target.contains("apple-darwin")
1053     }
1054
1055     /// Returns the `version` string associated with this compiler for Rust
1056     /// itself.
1057     ///
1058     /// Note that this is a descriptive string which includes the commit date,
1059     /// sha, version, etc.
1060     fn rust_version(&self) -> String {
1061         self.rust_info.version(self, channel::CFG_RELEASE_NUM)
1062     }
1063
1064     /// Returns the full commit hash.
1065     fn rust_sha(&self) -> Option<&str> {
1066         self.rust_info.sha()
1067     }
1068
1069     /// Returns the `a.b.c` version that the given package is at.
1070     fn release_num(&self, package: &str) -> String {
1071         let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1072         let toml = t!(fs::read_to_string(&toml_file_name));
1073         for line in toml.lines() {
1074             let prefix = "version = \"";
1075             let suffix = "\"";
1076             if line.starts_with(prefix) && line.ends_with(suffix) {
1077                 return line[prefix.len()..line.len() - suffix.len()].to_string();
1078             }
1079         }
1080
1081         panic!("failed to find version in {}'s Cargo.toml", package)
1082     }
1083
1084     /// Returns `true` if unstable features should be enabled for the compiler
1085     /// we're building.
1086     fn unstable_features(&self) -> bool {
1087         match &self.config.channel[..] {
1088             "stable" | "beta" => false,
1089             "nightly" | _ => true,
1090         }
1091     }
1092
1093     fn in_tree_crates(&self, root: &str) -> Vec<&Crate> {
1094         let mut ret = Vec::new();
1095         let mut list = vec![INTERNER.intern_str(root)];
1096         let mut visited = HashSet::new();
1097         while let Some(krate) = list.pop() {
1098             let krate = &self.crates[&krate];
1099             if krate.is_local(self) {
1100                 ret.push(krate);
1101             }
1102             for dep in &krate.deps {
1103                 if visited.insert(dep) && dep != "build_helper" {
1104                     list.push(*dep);
1105                 }
1106             }
1107         }
1108         ret
1109     }
1110
1111     fn read_stamp_file(&self, stamp: &Path) -> Vec<(PathBuf, DependencyType)> {
1112         if self.config.dry_run {
1113             return Vec::new();
1114         }
1115
1116         let mut paths = Vec::new();
1117         let contents = t!(fs::read(stamp), &stamp);
1118         // This is the method we use for extracting paths from the stamp file passed to us. See
1119         // run_cargo for more information (in compile.rs).
1120         for part in contents.split(|b| *b == 0) {
1121             if part.is_empty() {
1122                 continue;
1123             }
1124             let dependency_type = match part[0] as char {
1125                 'h' => DependencyType::Host,
1126                 's' => DependencyType::TargetSelfContained,
1127                 't' => DependencyType::Target,
1128                 _ => unreachable!(),
1129             };
1130             let path = PathBuf::from(t!(str::from_utf8(&part[1..])));
1131             paths.push((path, dependency_type));
1132         }
1133         paths
1134     }
1135
1136     /// Copies a file from `src` to `dst`
1137     pub fn copy(&self, src: &Path, dst: &Path) {
1138         if self.config.dry_run {
1139             return;
1140         }
1141         self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst));
1142         if src == dst {
1143             return;
1144         }
1145         let _ = fs::remove_file(&dst);
1146         let metadata = t!(src.symlink_metadata());
1147         if metadata.file_type().is_symlink() {
1148             let link = t!(fs::read_link(src));
1149             t!(symlink_file(link, dst));
1150         } else if let Ok(()) = fs::hard_link(src, dst) {
1151             // Attempt to "easy copy" by creating a hard link
1152             // (symlinks don't work on windows), but if that fails
1153             // just fall back to a slow `copy` operation.
1154         } else {
1155             if let Err(e) = fs::copy(src, dst) {
1156                 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1157             }
1158             t!(fs::set_permissions(dst, metadata.permissions()));
1159             let atime = FileTime::from_last_access_time(&metadata);
1160             let mtime = FileTime::from_last_modification_time(&metadata);
1161             t!(filetime::set_file_times(dst, atime, mtime));
1162         }
1163     }
1164
1165     /// Search-and-replaces within a file. (Not maximally efficiently: allocates a
1166     /// new string for each replacement.)
1167     pub fn replace_in_file(&self, path: &Path, replacements: &[(&str, &str)]) {
1168         if self.config.dry_run {
1169             return;
1170         }
1171         let mut contents = String::new();
1172         let mut file = t!(OpenOptions::new().read(true).write(true).open(path));
1173         t!(file.read_to_string(&mut contents));
1174         for &(target, replacement) in replacements {
1175             contents = contents.replace(target, replacement);
1176         }
1177         t!(file.seek(SeekFrom::Start(0)));
1178         t!(file.set_len(0));
1179         t!(file.write_all(contents.as_bytes()));
1180     }
1181
1182     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1183     /// when this function is called.
1184     pub fn cp_r(&self, src: &Path, dst: &Path) {
1185         if self.config.dry_run {
1186             return;
1187         }
1188         for f in self.read_dir(src) {
1189             let path = f.path();
1190             let name = path.file_name().unwrap();
1191             let dst = dst.join(name);
1192             if t!(f.file_type()).is_dir() {
1193                 t!(fs::create_dir_all(&dst));
1194                 self.cp_r(&path, &dst);
1195             } else {
1196                 let _ = fs::remove_file(&dst);
1197                 self.copy(&path, &dst);
1198             }
1199         }
1200     }
1201
1202     /// Copies the `src` directory recursively to `dst`. Both are assumed to exist
1203     /// when this function is called. Unwanted files or directories can be skipped
1204     /// by returning `false` from the filter function.
1205     pub fn cp_filtered(&self, src: &Path, dst: &Path, filter: &dyn Fn(&Path) -> bool) {
1206         // Immediately recurse with an empty relative path
1207         self.recurse_(src, dst, Path::new(""), filter)
1208     }
1209
1210     // Inner function does the actual work
1211     fn recurse_(&self, src: &Path, dst: &Path, relative: &Path, filter: &dyn Fn(&Path) -> bool) {
1212         for f in self.read_dir(src) {
1213             let path = f.path();
1214             let name = path.file_name().unwrap();
1215             let dst = dst.join(name);
1216             let relative = relative.join(name);
1217             // Only copy file or directory if the filter function returns true
1218             if filter(&relative) {
1219                 if t!(f.file_type()).is_dir() {
1220                     let _ = fs::remove_dir_all(&dst);
1221                     self.create_dir(&dst);
1222                     self.recurse_(&path, &dst, &relative, filter);
1223                 } else {
1224                     let _ = fs::remove_file(&dst);
1225                     self.copy(&path, &dst);
1226                 }
1227             }
1228         }
1229     }
1230
1231     fn copy_to_folder(&self, src: &Path, dest_folder: &Path) {
1232         let file_name = src.file_name().unwrap();
1233         let dest = dest_folder.join(file_name);
1234         self.copy(src, &dest);
1235     }
1236
1237     fn install(&self, src: &Path, dstdir: &Path, perms: u32) {
1238         if self.config.dry_run {
1239             return;
1240         }
1241         let dst = dstdir.join(src.file_name().unwrap());
1242         self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst));
1243         t!(fs::create_dir_all(dstdir));
1244         drop(fs::remove_file(&dst));
1245         {
1246             if !src.exists() {
1247                 panic!("Error: File \"{}\" not found!", src.display());
1248             }
1249             let metadata = t!(src.symlink_metadata());
1250             if let Err(e) = fs::copy(&src, &dst) {
1251                 panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e)
1252             }
1253             t!(fs::set_permissions(&dst, metadata.permissions()));
1254             let atime = FileTime::from_last_access_time(&metadata);
1255             let mtime = FileTime::from_last_modification_time(&metadata);
1256             t!(filetime::set_file_times(&dst, atime, mtime));
1257         }
1258         chmod(&dst, perms);
1259     }
1260
1261     fn create(&self, path: &Path, s: &str) {
1262         if self.config.dry_run {
1263             return;
1264         }
1265         t!(fs::write(path, s));
1266     }
1267
1268     fn read(&self, path: &Path) -> String {
1269         if self.config.dry_run {
1270             return String::new();
1271         }
1272         t!(fs::read_to_string(path))
1273     }
1274
1275     fn create_dir(&self, dir: &Path) {
1276         if self.config.dry_run {
1277             return;
1278         }
1279         t!(fs::create_dir_all(dir))
1280     }
1281
1282     fn remove_dir(&self, dir: &Path) {
1283         if self.config.dry_run {
1284             return;
1285         }
1286         t!(fs::remove_dir_all(dir))
1287     }
1288
1289     fn read_dir(&self, dir: &Path) -> impl Iterator<Item = fs::DirEntry> {
1290         let iter = match fs::read_dir(dir) {
1291             Ok(v) => v,
1292             Err(_) if self.config.dry_run => return vec![].into_iter(),
1293             Err(err) => panic!("could not read dir {:?}: {:?}", dir, err),
1294         };
1295         iter.map(|e| t!(e)).collect::<Vec<_>>().into_iter()
1296     }
1297
1298     fn remove(&self, f: &Path) {
1299         if self.config.dry_run {
1300             return;
1301         }
1302         fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f));
1303     }
1304 }
1305
1306 #[cfg(unix)]
1307 fn chmod(path: &Path, perms: u32) {
1308     use std::os::unix::fs::*;
1309     t!(fs::set_permissions(path, fs::Permissions::from_mode(perms)));
1310 }
1311 #[cfg(windows)]
1312 fn chmod(_path: &Path, _perms: u32) {}
1313
1314 impl Compiler {
1315     pub fn with_stage(mut self, stage: u32) -> Compiler {
1316         self.stage = stage;
1317         self
1318     }
1319
1320     /// Returns `true` if this is a snapshot compiler for `build`'s configuration
1321     pub fn is_snapshot(&self, build: &Build) -> bool {
1322         self.stage == 0 && self.host == build.build
1323     }
1324
1325     /// Returns if this compiler should be treated as a final stage one in the
1326     /// current build session.
1327     /// This takes into account whether we're performing a full bootstrap or
1328     /// not; don't directly compare the stage with `2`!
1329     pub fn is_final_stage(&self, build: &Build) -> bool {
1330         let final_stage = if build.config.full_bootstrap { 2 } else { 1 };
1331         self.stage >= final_stage
1332     }
1333 }
1334
1335 fn envify(s: &str) -> String {
1336     s.chars()
1337         .map(|c| match c {
1338             '-' => '_',
1339             c => c,
1340         })
1341         .flat_map(|c| c.to_uppercase())
1342         .collect()
1343 }