]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/util.rs
Rollup merge of #99717 - JohnTitor:upd-docs-issue-tmpl, r=Mark-Simulacrum
[rust.git] / compiler / rustc_interface / src / util.rs
1 use libloading::Library;
2 use rustc_ast as ast;
3 use rustc_codegen_ssa::traits::CodegenBackend;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 #[cfg(parallel_compiler)]
6 use rustc_data_structures::jobserver;
7 use rustc_data_structures::sync::Lrc;
8 use rustc_errors::registry::Registry;
9 #[cfg(parallel_compiler)]
10 use rustc_middle::ty::tls;
11 use rustc_parse::validate_attr;
12 #[cfg(parallel_compiler)]
13 use rustc_query_impl::{QueryContext, QueryCtxt};
14 use rustc_session as session;
15 use rustc_session::config::CheckCfg;
16 use rustc_session::config::{self, CrateType};
17 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
18 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
19 use rustc_session::parse::CrateConfig;
20 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
21 use rustc_span::edition::Edition;
22 use rustc_span::lev_distance::find_best_match_for_name;
23 use rustc_span::source_map::FileLoader;
24 use rustc_span::symbol::{sym, Symbol};
25 use std::env;
26 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
27 use std::mem;
28 #[cfg(not(parallel_compiler))]
29 use std::panic;
30 use std::path::{Path, PathBuf};
31 use std::sync::atomic::{AtomicBool, Ordering};
32 use std::sync::OnceLock;
33 use std::thread;
34 use tracing::info;
35
36 /// Function pointer type that constructs a new CodegenBackend.
37 pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
38
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
41 ///
42 /// This is performed by checking whether a set of permitted features
43 /// is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45     cfg: &mut CrateConfig,
46     sess: &mut Session,
47     codegen_backend: &dyn CodegenBackend,
48 ) {
49     let tf = sym::target_feature;
50
51     let unstable_target_features = codegen_backend.target_features(sess, true);
52     sess.unstable_target_features.extend(unstable_target_features.iter().cloned());
53
54     let target_features = codegen_backend.target_features(sess, false);
55     sess.target_features.extend(target_features.iter().cloned());
56
57     cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
58
59     if sess.crt_static(None) {
60         cfg.insert((tf, Some(sym::crt_dash_static)));
61     }
62 }
63
64 pub fn create_session(
65     sopts: config::Options,
66     cfg: FxHashSet<(String, Option<String>)>,
67     check_cfg: CheckCfg,
68     diagnostic_output: DiagnosticOutput,
69     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
70     input_path: Option<PathBuf>,
71     lint_caps: FxHashMap<lint::LintId, lint::Level>,
72     make_codegen_backend: Option<
73         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
74     >,
75     descriptions: Registry,
76 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
77     let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
78         make_codegen_backend(&sopts)
79     } else {
80         get_codegen_backend(
81             &sopts.maybe_sysroot,
82             sopts.unstable_opts.codegen_backend.as_ref().map(|name| &name[..]),
83         )
84     };
85
86     // target_override is documented to be called before init(), so this is okay
87     let target_override = codegen_backend.target_override(&sopts);
88
89     let bundle = match rustc_errors::fluent_bundle(
90         sopts.maybe_sysroot.clone(),
91         sysroot_candidates(),
92         sopts.unstable_opts.translate_lang.clone(),
93         sopts.unstable_opts.translate_additional_ftl.as_deref(),
94         sopts.unstable_opts.translate_directionality_markers,
95     ) {
96         Ok(bundle) => bundle,
97         Err(e) => {
98             early_error(sopts.error_format, &format!("failed to load fluent bundle: {e}"));
99         }
100     };
101
102     let mut sess = session::build_session(
103         sopts,
104         input_path,
105         bundle,
106         descriptions,
107         diagnostic_output,
108         lint_caps,
109         file_loader,
110         target_override,
111     );
112
113     codegen_backend.init(&sess);
114
115     let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
116     add_configuration(&mut cfg, &mut sess, &*codegen_backend);
117
118     let mut check_cfg = config::to_crate_check_config(check_cfg);
119     check_cfg.fill_well_known();
120     check_cfg.fill_actual(&cfg);
121
122     sess.parse_sess.config = cfg;
123     sess.parse_sess.check_config = check_cfg;
124
125     (Lrc::new(sess), Lrc::new(codegen_backend))
126 }
127
128 const STACK_SIZE: usize = 8 * 1024 * 1024;
129
130 fn get_stack_size() -> Option<usize> {
131     // FIXME: Hacks on hacks. If the env is trying to override the stack size
132     // then *don't* set it explicitly.
133     env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
134 }
135
136 /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need
137 /// for `'static` bounds.
138 #[cfg(not(parallel_compiler))]
139 fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
140     // SAFETY: join() is called immediately, so any closure captures are still
141     // alive.
142     match unsafe { cfg.spawn_unchecked(f) }.unwrap().join() {
143         Ok(v) => v,
144         Err(e) => panic::resume_unwind(e),
145     }
146 }
147
148 #[cfg(not(parallel_compiler))]
149 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
150     edition: Edition,
151     _threads: usize,
152     f: F,
153 ) -> R {
154     let mut cfg = thread::Builder::new().name("rustc".to_string());
155
156     if let Some(size) = get_stack_size() {
157         cfg = cfg.stack_size(size);
158     }
159
160     let main_handler = move || rustc_span::create_session_globals_then(edition, f);
161
162     scoped_thread(cfg, main_handler)
163 }
164
165 /// Creates a new thread and forwards information in thread locals to it.
166 /// The new thread runs the deadlock handler.
167 /// Must only be called when a deadlock is about to happen.
168 #[cfg(parallel_compiler)]
169 unsafe fn handle_deadlock() {
170     let registry = rustc_rayon_core::Registry::current();
171
172     let query_map = tls::with(|tcx| {
173         QueryCtxt::from_tcx(tcx)
174             .try_collect_active_jobs()
175             .expect("active jobs shouldn't be locked in deadlock handler")
176     });
177     thread::spawn(move || rustc_query_impl::deadlock(query_map, &registry));
178 }
179
180 #[cfg(parallel_compiler)]
181 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
182     edition: Edition,
183     threads: usize,
184     f: F,
185 ) -> R {
186     let mut config = rayon::ThreadPoolBuilder::new()
187         .thread_name(|_| "rustc".to_string())
188         .acquire_thread_handler(jobserver::acquire_thread)
189         .release_thread_handler(jobserver::release_thread)
190         .num_threads(threads)
191         .deadlock_handler(|| unsafe { handle_deadlock() });
192
193     if let Some(size) = get_stack_size() {
194         config = config.stack_size(size);
195     }
196
197     let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
198
199     rustc_span::create_session_globals_then(edition, || {
200         rustc_span::with_session_globals(|session_globals| {
201             // The main handler runs for each Rayon worker thread and sets up
202             // the thread local rustc uses. `session_globals` is captured and set
203             // on the new threads.
204             let main_handler = move |thread: rayon::ThreadBuilder| {
205                 rustc_span::set_session_globals_then(session_globals, || thread.run())
206             };
207
208             config.build_scoped(main_handler, with_pool).unwrap()
209         })
210     })
211 }
212
213 fn load_backend_from_dylib(path: &Path) -> MakeBackendFn {
214     let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| {
215         let err = format!("couldn't load codegen backend {:?}: {}", path, err);
216         early_error(ErrorOutputType::default(), &err);
217     });
218
219     let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") }
220         .unwrap_or_else(|e| {
221             let err = format!("couldn't load codegen backend: {}", e);
222             early_error(ErrorOutputType::default(), &err);
223         });
224
225     // Intentionally leak the dynamic library. We can't ever unload it
226     // since the library can make things that will live arbitrarily long.
227     let backend_sym = unsafe { backend_sym.into_raw() };
228     mem::forget(lib);
229
230     *backend_sym
231 }
232
233 /// Get the codegen backend based on the name and specified sysroot.
234 ///
235 /// A name of `None` indicates that the default backend should be used.
236 pub fn get_codegen_backend(
237     maybe_sysroot: &Option<PathBuf>,
238     backend_name: Option<&str>,
239 ) -> Box<dyn CodegenBackend> {
240     static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
241
242     let load = LOAD.get_or_init(|| {
243         let default_codegen_backend = option_env!("CFG_DEFAULT_CODEGEN_BACKEND").unwrap_or("llvm");
244
245         match backend_name.unwrap_or(default_codegen_backend) {
246             filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
247             #[cfg(feature = "llvm")]
248             "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
249             backend_name => get_codegen_sysroot(maybe_sysroot, backend_name),
250         }
251     });
252
253     // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
254     // backend we hope that the backend links against the same rustc_driver version. If this is not
255     // the case, we get UB.
256     unsafe { load() }
257 }
258
259 // This is used for rustdoc, but it uses similar machinery to codegen backend
260 // loading, so we leave the code here. It is potentially useful for other tools
261 // that want to invoke the rustc binary while linking to rustc as well.
262 pub fn rustc_path<'a>() -> Option<&'a Path> {
263     static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
264
265     const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
266
267     RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
268 }
269
270 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
271     sysroot_candidates().iter().find_map(|sysroot| {
272         let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
273             "rustc.exe"
274         } else {
275             "rustc"
276         });
277         candidate.exists().then_some(candidate)
278     })
279 }
280
281 fn sysroot_candidates() -> Vec<PathBuf> {
282     let target = session::config::host_triple();
283     let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
284     let path = current_dll_path().and_then(|s| s.canonicalize().ok());
285     if let Some(dll) = path {
286         // use `parent` twice to chop off the file name and then also the
287         // directory containing the dll which should be either `lib` or `bin`.
288         if let Some(path) = dll.parent().and_then(|p| p.parent()) {
289             // The original `path` pointed at the `rustc_driver` crate's dll.
290             // Now that dll should only be in one of two locations. The first is
291             // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
292             // other is the target's libdir, for example
293             // `$sysroot/lib/rustlib/$target/lib/*.dll`.
294             //
295             // We don't know which, so let's assume that if our `path` above
296             // ends in `$target` we *could* be in the target libdir, and always
297             // assume that we may be in the main libdir.
298             sysroot_candidates.push(path.to_owned());
299
300             if path.ends_with(target) {
301                 sysroot_candidates.extend(
302                     path.parent() // chop off `$target`
303                         .and_then(|p| p.parent()) // chop off `rustlib`
304                         .and_then(|p| p.parent()) // chop off `lib`
305                         .map(|s| s.to_owned()),
306                 );
307             }
308         }
309     }
310
311     return sysroot_candidates;
312
313     #[cfg(unix)]
314     fn current_dll_path() -> Option<PathBuf> {
315         use std::ffi::{CStr, OsStr};
316         use std::os::unix::prelude::*;
317
318         unsafe {
319             let addr = current_dll_path as usize as *mut _;
320             let mut info = mem::zeroed();
321             if libc::dladdr(addr, &mut info) == 0 {
322                 info!("dladdr failed");
323                 return None;
324             }
325             if info.dli_fname.is_null() {
326                 info!("dladdr returned null pointer");
327                 return None;
328             }
329             let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
330             let os = OsStr::from_bytes(bytes);
331             Some(PathBuf::from(os))
332         }
333     }
334
335     #[cfg(windows)]
336     fn current_dll_path() -> Option<PathBuf> {
337         use std::ffi::OsString;
338         use std::io;
339         use std::os::windows::prelude::*;
340         use std::ptr;
341
342         use winapi::um::libloaderapi::{
343             GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
344         };
345
346         unsafe {
347             let mut module = ptr::null_mut();
348             let r = GetModuleHandleExW(
349                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
350                 current_dll_path as usize as *mut _,
351                 &mut module,
352             );
353             if r == 0 {
354                 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
355                 return None;
356             }
357             let mut space = Vec::with_capacity(1024);
358             let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
359             if r == 0 {
360                 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
361                 return None;
362             }
363             let r = r as usize;
364             if r >= space.capacity() {
365                 info!("our buffer was too small? {}", io::Error::last_os_error());
366                 return None;
367             }
368             space.set_len(r);
369             let os = OsString::from_wide(&space);
370             Some(PathBuf::from(os))
371         }
372     }
373 }
374
375 fn get_codegen_sysroot(maybe_sysroot: &Option<PathBuf>, backend_name: &str) -> MakeBackendFn {
376     // For now we only allow this function to be called once as it'll dlopen a
377     // few things, which seems to work best if we only do that once. In
378     // general this assertion never trips due to the once guard in `get_codegen_backend`,
379     // but there's a few manual calls to this function in this file we protect
380     // against.
381     static LOADED: AtomicBool = AtomicBool::new(false);
382     assert!(
383         !LOADED.fetch_or(true, Ordering::SeqCst),
384         "cannot load the default codegen backend twice"
385     );
386
387     let target = session::config::host_triple();
388     let sysroot_candidates = sysroot_candidates();
389
390     let sysroot = maybe_sysroot
391         .iter()
392         .chain(sysroot_candidates.iter())
393         .map(|sysroot| {
394             filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
395         })
396         .find(|f| {
397             info!("codegen backend candidate: {}", f.display());
398             f.exists()
399         });
400     let sysroot = sysroot.unwrap_or_else(|| {
401         let candidates = sysroot_candidates
402             .iter()
403             .map(|p| p.display().to_string())
404             .collect::<Vec<_>>()
405             .join("\n* ");
406         let err = format!(
407             "failed to find a `codegen-backends` folder \
408                            in the sysroot candidates:\n* {}",
409             candidates
410         );
411         early_error(ErrorOutputType::default(), &err);
412     });
413     info!("probing {} for a codegen backend", sysroot.display());
414
415     let d = sysroot.read_dir().unwrap_or_else(|e| {
416         let err = format!(
417             "failed to load default codegen backend, couldn't \
418                            read `{}`: {}",
419             sysroot.display(),
420             e
421         );
422         early_error(ErrorOutputType::default(), &err);
423     });
424
425     let mut file: Option<PathBuf> = None;
426
427     let expected_names = &[
428         format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
429         format!("rustc_codegen_{}", backend_name),
430     ];
431     for entry in d.filter_map(|e| e.ok()) {
432         let path = entry.path();
433         let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
434         if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
435             continue;
436         }
437         let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
438         if !expected_names.iter().any(|expected| expected == name) {
439             continue;
440         }
441         if let Some(ref prev) = file {
442             let err = format!(
443                 "duplicate codegen backends found\n\
444                                first:  {}\n\
445                                second: {}\n\
446             ",
447                 prev.display(),
448                 path.display()
449             );
450             early_error(ErrorOutputType::default(), &err);
451         }
452         file = Some(path.clone());
453     }
454
455     match file {
456         Some(ref s) => load_backend_from_dylib(s),
457         None => {
458             let err = format!("unsupported builtin codegen backend `{}`", backend_name);
459             early_error(ErrorOutputType::default(), &err);
460         }
461     }
462 }
463
464 pub(crate) fn check_attr_crate_type(
465     sess: &Session,
466     attrs: &[ast::Attribute],
467     lint_buffer: &mut LintBuffer,
468 ) {
469     // Unconditionally collect crate types from attributes to make them used
470     for a in attrs.iter() {
471         if a.has_name(sym::crate_type) {
472             if let Some(n) = a.value_str() {
473                 if categorize_crate_type(n).is_some() {
474                     return;
475                 }
476
477                 if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
478                     let span = spanned.span;
479                     let lev_candidate = find_best_match_for_name(
480                         &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
481                         n,
482                         None,
483                     );
484                     if let Some(candidate) = lev_candidate {
485                         lint_buffer.buffer_lint_with_diagnostic(
486                             lint::builtin::UNKNOWN_CRATE_TYPES,
487                             ast::CRATE_NODE_ID,
488                             span,
489                             "invalid `crate_type` value",
490                             BuiltinLintDiagnostics::UnknownCrateTypes(
491                                 span,
492                                 "did you mean".to_string(),
493                                 format!("\"{}\"", candidate),
494                             ),
495                         );
496                     } else {
497                         lint_buffer.buffer_lint(
498                             lint::builtin::UNKNOWN_CRATE_TYPES,
499                             ast::CRATE_NODE_ID,
500                             span,
501                             "invalid `crate_type` value",
502                         );
503                     }
504                 }
505             } else {
506                 // This is here mainly to check for using a macro, such as
507                 // #![crate_type = foo!()]. That is not supported since the
508                 // crate type needs to be known very early in compilation long
509                 // before expansion. Otherwise, validation would normally be
510                 // caught in AstValidator (via `check_builtin_attribute`), but
511                 // by the time that runs the macro is expanded, and it doesn't
512                 // give an error.
513                 validate_attr::emit_fatal_malformed_builtin_attribute(
514                     &sess.parse_sess,
515                     a,
516                     sym::crate_type,
517                 );
518             }
519         }
520     }
521 }
522
523 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
524     (sym::rlib, CrateType::Rlib),
525     (sym::dylib, CrateType::Dylib),
526     (sym::cdylib, CrateType::Cdylib),
527     (sym::lib, config::default_lib_output()),
528     (sym::staticlib, CrateType::Staticlib),
529     (sym::proc_dash_macro, CrateType::ProcMacro),
530     (sym::bin, CrateType::Executable),
531 ];
532
533 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
534     Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
535 }
536
537 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
538     // Unconditionally collect crate types from attributes to make them used
539     let attr_types: Vec<CrateType> = attrs
540         .iter()
541         .filter_map(|a| {
542             if a.has_name(sym::crate_type) {
543                 match a.value_str() {
544                     Some(s) => categorize_crate_type(s),
545                     _ => None,
546                 }
547             } else {
548                 None
549             }
550         })
551         .collect();
552
553     // If we're generating a test executable, then ignore all other output
554     // styles at all other locations
555     if session.opts.test {
556         return vec![CrateType::Executable];
557     }
558
559     // Only check command line flags if present. If no types are specified by
560     // command line, then reuse the empty `base` Vec to hold the types that
561     // will be found in crate attributes.
562     // JUSTIFICATION: before wrapper fn is available
563     #[cfg_attr(not(bootstrap), allow(rustc::bad_opt_access))]
564     let mut base = session.opts.crate_types.clone();
565     if base.is_empty() {
566         base.extend(attr_types);
567         if base.is_empty() {
568             base.push(output::default_output_for_target(session));
569         } else {
570             base.sort();
571             base.dedup();
572         }
573     }
574
575     base.retain(|crate_type| {
576         let res = !output::invalid_output_for_target(session, *crate_type);
577
578         if !res {
579             session.warn(&format!(
580                 "dropping unsupported crate type `{}` for target `{}`",
581                 *crate_type, session.opts.target_triple
582             ));
583         }
584
585         res
586     });
587
588     base
589 }
590
591 pub fn build_output_filenames(
592     input: &Input,
593     odir: &Option<PathBuf>,
594     ofile: &Option<PathBuf>,
595     temps_dir: &Option<PathBuf>,
596     attrs: &[ast::Attribute],
597     sess: &Session,
598 ) -> OutputFilenames {
599     match *ofile {
600         None => {
601             // "-" as input file will cause the parser to read from stdin so we
602             // have to make up a name
603             // We want to toss everything after the final '.'
604             let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
605
606             // If a crate name is present, we use it as the link name
607             let stem = sess
608                 .opts
609                 .crate_name
610                 .clone()
611                 .or_else(|| rustc_attr::find_crate_name(sess, attrs).map(|n| n.to_string()))
612                 .unwrap_or_else(|| input.filestem().to_owned());
613
614             OutputFilenames::new(
615                 dirpath,
616                 stem,
617                 None,
618                 temps_dir.clone(),
619                 sess.opts.cg.extra_filename.clone(),
620                 sess.opts.output_types.clone(),
621             )
622         }
623
624         Some(ref out_file) => {
625             let unnamed_output_types =
626                 sess.opts.output_types.values().filter(|a| a.is_none()).count();
627             let ofile = if unnamed_output_types > 1 {
628                 sess.warn(
629                     "due to multiple output types requested, the explicitly specified \
630                      output file name will be adapted for each output type",
631                 );
632                 None
633             } else {
634                 if !sess.opts.cg.extra_filename.is_empty() {
635                     sess.warn("ignoring -C extra-filename flag due to -o flag");
636                 }
637                 Some(out_file.clone())
638             };
639             if *odir != None {
640                 sess.warn("ignoring --out-dir flag due to -o flag");
641             }
642
643             OutputFilenames::new(
644                 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
645                 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
646                 ofile,
647                 temps_dir.clone(),
648                 sess.opts.cg.extra_filename.clone(),
649                 sess.opts.output_types.clone(),
650             )
651         }
652     }
653 }
654
655 /// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)"
656 pub fn version_str() -> Option<&'static str> {
657     option_env!("CFG_VERSION")
658 }
659
660 /// Returns a version string such as "0.12.0-dev".
661 pub fn release_str() -> Option<&'static str> {
662     option_env!("CFG_RELEASE")
663 }
664
665 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
666 pub fn commit_hash_str() -> Option<&'static str> {
667     option_env!("CFG_VER_HASH")
668 }
669
670 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
671 pub fn commit_date_str() -> Option<&'static str> {
672     option_env!("CFG_VER_DATE")
673 }