]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/session.rs
Auto merge of #81635 - michaelwoerister:structured_def_path_hash, r=pnkfelix
[rust.git] / compiler / rustc_session / src / session.rs
1 use crate::cgu_reuse_tracker::CguReuseTracker;
2 use crate::code_stats::CodeStats;
3 pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo};
4 use crate::config::{self, CrateType, OutputType, PrintRequest, SanitizerSet, SwitchWithOptPath};
5 use crate::filesearch;
6 use crate::lint::{self, LintId};
7 use crate::parse::ParseSess;
8 use crate::search_paths::{PathKind, SearchPath};
9
10 pub use rustc_ast::attr::MarkedAttrs;
11 pub use rustc_ast::Attribute;
12 use rustc_data_structures::flock;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::jobserver::{self, Client};
15 use rustc_data_structures::profiling::{duration_to_secs_str, SelfProfiler, SelfProfilerRef};
16 use rustc_data_structures::sync::{
17     self, AtomicU64, AtomicUsize, Lock, Lrc, OnceCell, OneThread, Ordering, Ordering::SeqCst,
18 };
19 use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitterWriter;
20 use rustc_errors::emitter::{Emitter, EmitterWriter, HumanReadableErrorType};
21 use rustc_errors::json::JsonEmitter;
22 use rustc_errors::registry::Registry;
23 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, ErrorReported};
24 use rustc_lint_defs::FutureBreakage;
25 pub use rustc_span::crate_disambiguator::CrateDisambiguator;
26 use rustc_span::edition::Edition;
27 use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
28 use rustc_span::{sym, SourceFileHashAlgorithm, Symbol};
29 use rustc_target::asm::InlineAsmArch;
30 use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel};
31 use rustc_target::spec::{SplitDebuginfo, Target, TargetTriple, TlsModel};
32
33 use std::cell::{self, RefCell};
34 use std::env;
35 use std::fmt;
36 use std::io::Write;
37 use std::num::NonZeroU32;
38 use std::ops::{Div, Mul};
39 use std::path::PathBuf;
40 use std::str::FromStr;
41 use std::sync::Arc;
42 use std::time::Duration;
43
44 pub trait SessionLintStore: sync::Send + sync::Sync {
45     fn name_to_lint(&self, lint_name: &str) -> LintId;
46 }
47
48 pub struct OptimizationFuel {
49     /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
50     remaining: u64,
51     /// We're rejecting all further optimizations.
52     out_of_fuel: bool,
53 }
54
55 /// The behavior of the CTFE engine when an error occurs with regards to backtraces.
56 #[derive(Clone, Copy)]
57 pub enum CtfeBacktrace {
58     /// Do nothing special, return the error as usual without a backtrace.
59     Disabled,
60     /// Capture a backtrace at the point the error is created and return it in the error
61     /// (to be printed later if/when the error ever actually gets shown to the user).
62     Capture,
63     /// Capture a backtrace at the point the error is created and immediately print it out.
64     Immediate,
65 }
66
67 /// New-type wrapper around `usize` for representing limits. Ensures that comparisons against
68 /// limits are consistent throughout the compiler.
69 #[derive(Clone, Copy, Debug)]
70 pub struct Limit(pub usize);
71
72 impl Limit {
73     /// Create a new limit from a `usize`.
74     pub fn new(value: usize) -> Self {
75         Limit(value)
76     }
77
78     /// Check that `value` is within the limit. Ensures that the same comparisons are used
79     /// throughout the compiler, as mismatches can cause ICEs, see #72540.
80     #[inline]
81     pub fn value_within_limit(&self, value: usize) -> bool {
82         value <= self.0
83     }
84 }
85
86 impl fmt::Display for Limit {
87     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88         write!(f, "{}", self.0)
89     }
90 }
91
92 impl Div<usize> for Limit {
93     type Output = Limit;
94
95     fn div(self, rhs: usize) -> Self::Output {
96         Limit::new(self.0 / rhs)
97     }
98 }
99
100 impl Mul<usize> for Limit {
101     type Output = Limit;
102
103     fn mul(self, rhs: usize) -> Self::Output {
104         Limit::new(self.0 * rhs)
105     }
106 }
107
108 /// Represents the data associated with a compilation
109 /// session for a single crate.
110 pub struct Session {
111     pub target: Target,
112     pub host: Target,
113     pub opts: config::Options,
114     pub host_tlib_path: SearchPath,
115     /// `None` if the host and target are the same.
116     pub target_tlib_path: Option<SearchPath>,
117     pub parse_sess: ParseSess,
118     pub sysroot: PathBuf,
119     /// The name of the root source file of the crate, in the local file system.
120     /// `None` means that there is no source file.
121     pub local_crate_source_file: Option<PathBuf>,
122     /// The directory the compiler has been executed in plus a flag indicating
123     /// if the value stored here has been affected by path remapping.
124     pub working_dir: (PathBuf, bool),
125
126     /// Set of `(DiagnosticId, Option<Span>, message)` tuples tracking
127     /// (sub)diagnostics that have been set once, but should not be set again,
128     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
129     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
130     crate_types: OnceCell<Vec<CrateType>>,
131     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
132     /// arguments passed to the compiler. Its value together with the crate-name
133     /// forms a unique global identifier for the crate. It is used to allow
134     /// multiple crates with the same name to coexist. See the
135     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
136     pub crate_disambiguator: OnceCell<CrateDisambiguator>,
137
138     features: OnceCell<rustc_feature::Features>,
139
140     lint_store: OnceCell<Lrc<dyn SessionLintStore>>,
141
142     /// The maximum recursion limit for potentially infinitely recursive
143     /// operations such as auto-dereference and monomorphization.
144     pub recursion_limit: OnceCell<Limit>,
145
146     /// The maximum length of types during monomorphization.
147     pub type_length_limit: OnceCell<Limit>,
148
149     /// The maximum blocks a const expression can evaluate.
150     pub const_eval_limit: OnceCell<Limit>,
151
152     incr_comp_session: OneThread<RefCell<IncrCompSession>>,
153     /// Used for incremental compilation tests. Will only be populated if
154     /// `-Zquery-dep-graph` is specified.
155     pub cgu_reuse_tracker: CguReuseTracker,
156
157     /// Used by `-Z self-profile`.
158     pub prof: SelfProfilerRef,
159
160     /// Some measurements that are being gathered during compilation.
161     pub perf_stats: PerfStats,
162
163     /// Data about code being compiled, gathered during compilation.
164     pub code_stats: CodeStats,
165
166     /// If `-zfuel=crate=n` is specified, `Some(crate)`.
167     optimization_fuel_crate: Option<String>,
168
169     /// Tracks fuel info if `-zfuel=crate=n` is specified.
170     optimization_fuel: Lock<OptimizationFuel>,
171
172     // The next two are public because the driver needs to read them.
173     /// If `-zprint-fuel=crate`, `Some(crate)`.
174     pub print_fuel_crate: Option<String>,
175     /// Always set to zero and incremented so that we can print fuel expended by a crate.
176     pub print_fuel: AtomicU64,
177
178     /// Loaded up early on in the initialization of this `Session` to avoid
179     /// false positives about a job server in our environment.
180     pub jobserver: Client,
181
182     /// Cap lint level specified by a driver specifically.
183     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
184
185     /// `Span`s of trait methods that weren't found to avoid emitting object safety errors
186     pub trait_methods_not_found: Lock<FxHashSet<Span>>,
187
188     /// Mapping from ident span to path span for paths that don't exist as written, but that
189     /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
190     pub confused_type_with_std_module: Lock<FxHashMap<Span, Span>>,
191
192     /// Path for libraries that will take preference over libraries shipped by Rust.
193     /// Used by windows-gnu targets to priortize system mingw-w64 libraries.
194     pub system_library_path: OneThread<RefCell<Option<Option<PathBuf>>>>,
195
196     /// Tracks the current behavior of the CTFE engine when an error occurs.
197     /// Options range from returning the error without a backtrace to returning an error
198     /// and immediately printing the backtrace to stderr.
199     pub ctfe_backtrace: Lock<CtfeBacktrace>,
200
201     /// This tracks where `-Zunleash-the-miri-inside-of-you` was used to get around a
202     /// const check, optionally with the relevant feature gate.  We use this to
203     /// warn about unleashing, but with a single diagnostic instead of dozens that
204     /// drown everything else in noise.
205     miri_unleashed_features: Lock<Vec<(Span, Option<Symbol>)>>,
206
207     /// Base directory containing the `src/` for the Rust standard library, and
208     /// potentially `rustc` as well, if we can can find it. Right now it's always
209     /// `$sysroot/lib/rustlib/src/rust` (i.e. the `rustup` `rust-src` component).
210     ///
211     /// This directory is what the virtual `/rustc/$hash` is translated back to,
212     /// if Rust was built with path remapping to `/rustc/$hash` enabled
213     /// (the `rust.remap-debuginfo` option in `config.toml`).
214     pub real_rust_source_base_dir: Option<PathBuf>,
215
216     /// Architecture to use for interpreting asm!.
217     pub asm_arch: Option<InlineAsmArch>,
218
219     /// Set of enabled features for the current target.
220     pub target_features: FxHashSet<Symbol>,
221
222     known_attrs: Lock<MarkedAttrs>,
223     used_attrs: Lock<MarkedAttrs>,
224
225     /// `Span`s for `if` conditions that we have suggested turning into `if let`.
226     pub if_let_suggestions: Lock<FxHashSet<Span>>,
227 }
228
229 pub struct PerfStats {
230     /// The accumulated time spent on computing symbol hashes.
231     pub symbol_hash_time: Lock<Duration>,
232     /// Total number of values canonicalized queries constructed.
233     pub queries_canonicalized: AtomicUsize,
234     /// Number of times this query is invoked.
235     pub normalize_generic_arg_after_erasing_regions: AtomicUsize,
236     /// Number of times this query is invoked.
237     pub normalize_projection_ty: AtomicUsize,
238 }
239
240 /// Enum to support dispatch of one-time diagnostics (in `Session.diag_once`).
241 enum DiagnosticBuilderMethod {
242     Note,
243     SpanNote,
244     SpanSuggestion(String), // suggestion
245                             // Add more variants as needed to support one-time diagnostics.
246 }
247
248 /// Trait implemented by error types. This should not be implemented manually. Instead, use
249 /// `#[derive(SessionDiagnostic)]` -- see [rustc_macros::SessionDiagnostic].
250 pub trait SessionDiagnostic<'a> {
251     /// Write out as a diagnostic out of `sess`.
252     #[must_use]
253     fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a>;
254 }
255
256 /// Diagnostic message ID, used by `Session.one_time_diagnostics` to avoid
257 /// emitting the same message more than once.
258 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
259 pub enum DiagnosticMessageId {
260     ErrorId(u16), // EXXXX error code as integer
261     LintId(lint::LintId),
262     StabilityId(Option<NonZeroU32>), // issue number
263 }
264
265 impl From<&'static lint::Lint> for DiagnosticMessageId {
266     fn from(lint: &'static lint::Lint) -> Self {
267         DiagnosticMessageId::LintId(lint::LintId::of(lint))
268     }
269 }
270
271 impl Session {
272     pub fn miri_unleashed_feature(&self, span: Span, feature_gate: Option<Symbol>) {
273         self.miri_unleashed_features.lock().push((span, feature_gate));
274     }
275
276     fn check_miri_unleashed_features(&self) {
277         let unleashed_features = self.miri_unleashed_features.lock();
278         if !unleashed_features.is_empty() {
279             let mut must_err = false;
280             // Create a diagnostic pointing at where things got unleashed.
281             let mut diag = self.struct_warn("skipping const checks");
282             for &(span, feature_gate) in unleashed_features.iter() {
283                 // FIXME: `span_label` doesn't do anything, so we use "help" as a hack.
284                 if let Some(feature_gate) = feature_gate {
285                     diag.span_help(span, &format!("skipping check for `{}` feature", feature_gate));
286                     // The unleash flag must *not* be used to just "hack around" feature gates.
287                     must_err = true;
288                 } else {
289                     diag.span_help(span, "skipping check that does not even have a feature gate");
290                 }
291             }
292             diag.emit();
293             // If we should err, make sure we did.
294             if must_err && !self.has_errors() {
295                 // We have skipped a feature gate, and not run into other errors... reject.
296                 self.err(
297                     "`-Zunleash-the-miri-inside-of-you` may not be used to circumvent feature \
298                      gates, except when testing error paths in the CTFE engine",
299                 );
300             }
301         }
302     }
303
304     /// Invoked all the way at the end to finish off diagnostics printing.
305     pub fn finish_diagnostics(&self, registry: &Registry) {
306         self.check_miri_unleashed_features();
307         self.diagnostic().print_error_count(registry);
308         self.emit_future_breakage();
309     }
310
311     fn emit_future_breakage(&self) {
312         if !self.opts.debugging_opts.emit_future_incompat_report {
313             return;
314         }
315
316         let diags = self.diagnostic().take_future_breakage_diagnostics();
317         if diags.is_empty() {
318             return;
319         }
320         // If any future-breakage lints were registered, this lint store
321         // should be available
322         let lint_store = self.lint_store.get().expect("`lint_store` not initialized!");
323         let diags_and_breakage: Vec<(FutureBreakage, Diagnostic)> = diags
324             .into_iter()
325             .map(|diag| {
326                 let lint_name = match &diag.code {
327                     Some(DiagnosticId::Lint { name, has_future_breakage: true }) => name,
328                     _ => panic!("Unexpected code in diagnostic {:?}", diag),
329                 };
330                 let lint = lint_store.name_to_lint(&lint_name);
331                 let future_breakage =
332                     lint.lint.future_incompatible.unwrap().future_breakage.unwrap();
333                 (future_breakage, diag)
334             })
335             .collect();
336         self.parse_sess.span_diagnostic.emit_future_breakage_report(diags_and_breakage);
337     }
338
339     pub fn local_crate_disambiguator(&self) -> CrateDisambiguator {
340         self.crate_disambiguator.get().copied().unwrap()
341     }
342
343     pub fn crate_types(&self) -> &[CrateType] {
344         self.crate_types.get().unwrap().as_slice()
345     }
346
347     pub fn init_crate_types(&self, crate_types: Vec<CrateType>) {
348         self.crate_types.set(crate_types).expect("`crate_types` was initialized twice")
349     }
350
351     #[inline]
352     pub fn recursion_limit(&self) -> Limit {
353         self.recursion_limit.get().copied().unwrap()
354     }
355
356     #[inline]
357     pub fn type_length_limit(&self) -> Limit {
358         self.type_length_limit.get().copied().unwrap()
359     }
360
361     pub fn const_eval_limit(&self) -> Limit {
362         self.const_eval_limit.get().copied().unwrap()
363     }
364
365     pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
366         self.diagnostic().struct_span_warn(sp, msg)
367     }
368     pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(
369         &self,
370         sp: S,
371         msg: &str,
372         code: DiagnosticId,
373     ) -> DiagnosticBuilder<'_> {
374         self.diagnostic().struct_span_warn_with_code(sp, msg, code)
375     }
376     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
377         self.diagnostic().struct_warn(msg)
378     }
379     pub fn struct_span_allow<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
380         self.diagnostic().struct_span_allow(sp, msg)
381     }
382     pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
383         self.diagnostic().struct_allow(msg)
384     }
385     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
386         self.diagnostic().struct_span_err(sp, msg)
387     }
388     pub fn struct_span_err_with_code<S: Into<MultiSpan>>(
389         &self,
390         sp: S,
391         msg: &str,
392         code: DiagnosticId,
393     ) -> DiagnosticBuilder<'_> {
394         self.diagnostic().struct_span_err_with_code(sp, msg, code)
395     }
396     // FIXME: This method should be removed (every error should have an associated error code).
397     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
398         self.diagnostic().struct_err(msg)
399     }
400     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
401         self.diagnostic().struct_err_with_code(msg, code)
402     }
403     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'_> {
404         self.diagnostic().struct_span_fatal(sp, msg)
405     }
406     pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(
407         &self,
408         sp: S,
409         msg: &str,
410         code: DiagnosticId,
411     ) -> DiagnosticBuilder<'_> {
412         self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
413     }
414     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
415         self.diagnostic().struct_fatal(msg)
416     }
417
418     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
419         self.diagnostic().span_fatal(sp, msg).raise()
420     }
421     pub fn span_fatal_with_code<S: Into<MultiSpan>>(
422         &self,
423         sp: S,
424         msg: &str,
425         code: DiagnosticId,
426     ) -> ! {
427         self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
428     }
429     pub fn fatal(&self, msg: &str) -> ! {
430         self.diagnostic().fatal(msg).raise()
431     }
432     pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
433         if is_warning {
434             self.span_warn(sp, msg);
435         } else {
436             self.span_err(sp, msg);
437         }
438     }
439     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
440         self.diagnostic().span_err(sp, msg)
441     }
442     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
443         self.diagnostic().span_err_with_code(sp, &msg, code)
444     }
445     pub fn err(&self, msg: &str) {
446         self.diagnostic().err(msg)
447     }
448     pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) {
449         err.into_diagnostic(self).emit()
450     }
451     pub fn err_count(&self) -> usize {
452         self.diagnostic().err_count()
453     }
454     pub fn has_errors(&self) -> bool {
455         self.diagnostic().has_errors()
456     }
457     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
458         self.diagnostic().has_errors_or_delayed_span_bugs()
459     }
460     pub fn abort_if_errors(&self) {
461         self.diagnostic().abort_if_errors();
462     }
463     pub fn compile_status(&self) -> Result<(), ErrorReported> {
464         if self.has_errors() {
465             self.diagnostic().emit_stashed_diagnostics();
466             Err(ErrorReported)
467         } else {
468             Ok(())
469         }
470     }
471     // FIXME(matthewjasper) Remove this method, it should never be needed.
472     pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
473     where
474         F: FnOnce() -> T,
475     {
476         let old_count = self.err_count();
477         let result = f();
478         let errors = self.err_count() - old_count;
479         if errors == 0 { Ok(result) } else { Err(ErrorReported) }
480     }
481     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
482         self.diagnostic().span_warn(sp, msg)
483     }
484     pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
485         self.diagnostic().span_warn_with_code(sp, msg, code)
486     }
487     pub fn warn(&self, msg: &str) {
488         self.diagnostic().warn(msg)
489     }
490     pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
491         match opt_sp {
492             Some(sp) => self.span_warn(sp, msg),
493             None => self.warn(msg),
494         }
495     }
496     /// Delay a span_bug() call until abort_if_errors()
497     #[track_caller]
498     pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
499         self.diagnostic().delay_span_bug(sp, msg)
500     }
501
502     /// Used for code paths of expensive computations that should only take place when
503     /// warnings or errors are emitted. If no messages are emitted ("good path"), then
504     /// it's likely a bug.
505     pub fn delay_good_path_bug(&self, msg: &str) {
506         if self.opts.debugging_opts.print_type_sizes
507             || self.opts.debugging_opts.query_dep_graph
508             || self.opts.debugging_opts.dump_mir.is_some()
509             || self.opts.debugging_opts.unpretty.is_some()
510             || self.opts.output_types.contains_key(&OutputType::Mir)
511             || std::env::var_os("RUSTC_LOG").is_some()
512         {
513             return;
514         }
515
516         self.diagnostic().delay_good_path_bug(msg)
517     }
518
519     pub fn note_without_error(&self, msg: &str) {
520         self.diagnostic().note_without_error(msg)
521     }
522     pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
523         self.diagnostic().span_note_without_error(sp, msg)
524     }
525     pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
526         self.diagnostic().struct_note_without_error(msg)
527     }
528
529     pub fn diagnostic(&self) -> &rustc_errors::Handler {
530         &self.parse_sess.span_diagnostic
531     }
532
533     /// Analogous to calling methods on the given `DiagnosticBuilder`, but
534     /// deduplicates on lint ID, span (if any), and message for this `Session`
535     fn diag_once<'a, 'b>(
536         &'a self,
537         diag_builder: &'b mut DiagnosticBuilder<'a>,
538         method: DiagnosticBuilderMethod,
539         msg_id: DiagnosticMessageId,
540         message: &str,
541         span_maybe: Option<Span>,
542     ) {
543         let id_span_message = (msg_id, span_maybe, message.to_owned());
544         let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
545         if fresh {
546             match method {
547                 DiagnosticBuilderMethod::Note => {
548                     diag_builder.note(message);
549                 }
550                 DiagnosticBuilderMethod::SpanNote => {
551                     let span = span_maybe.expect("`span_note` needs a span");
552                     diag_builder.span_note(span, message);
553                 }
554                 DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
555                     let span = span_maybe.expect("`span_suggestion_*` needs a span");
556                     diag_builder.span_suggestion(
557                         span,
558                         message,
559                         suggestion,
560                         Applicability::Unspecified,
561                     );
562                 }
563             }
564         }
565     }
566
567     pub fn diag_span_note_once<'a, 'b>(
568         &'a self,
569         diag_builder: &'b mut DiagnosticBuilder<'a>,
570         msg_id: DiagnosticMessageId,
571         span: Span,
572         message: &str,
573     ) {
574         self.diag_once(
575             diag_builder,
576             DiagnosticBuilderMethod::SpanNote,
577             msg_id,
578             message,
579             Some(span),
580         );
581     }
582
583     pub fn diag_note_once<'a, 'b>(
584         &'a self,
585         diag_builder: &'b mut DiagnosticBuilder<'a>,
586         msg_id: DiagnosticMessageId,
587         message: &str,
588     ) {
589         self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
590     }
591
592     pub fn diag_span_suggestion_once<'a, 'b>(
593         &'a self,
594         diag_builder: &'b mut DiagnosticBuilder<'a>,
595         msg_id: DiagnosticMessageId,
596         span: Span,
597         message: &str,
598         suggestion: String,
599     ) {
600         self.diag_once(
601             diag_builder,
602             DiagnosticBuilderMethod::SpanSuggestion(suggestion),
603             msg_id,
604             message,
605             Some(span),
606         );
607     }
608
609     #[inline]
610     pub fn source_map(&self) -> &SourceMap {
611         self.parse_sess.source_map()
612     }
613     pub fn verbose(&self) -> bool {
614         self.opts.debugging_opts.verbose
615     }
616     pub fn time_passes(&self) -> bool {
617         self.opts.debugging_opts.time_passes || self.opts.debugging_opts.time
618     }
619     pub fn instrument_mcount(&self) -> bool {
620         self.opts.debugging_opts.instrument_mcount
621     }
622     pub fn time_llvm_passes(&self) -> bool {
623         self.opts.debugging_opts.time_llvm_passes
624     }
625     pub fn meta_stats(&self) -> bool {
626         self.opts.debugging_opts.meta_stats
627     }
628     pub fn asm_comments(&self) -> bool {
629         self.opts.debugging_opts.asm_comments
630     }
631     pub fn verify_llvm_ir(&self) -> bool {
632         self.opts.debugging_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
633     }
634     pub fn borrowck_stats(&self) -> bool {
635         self.opts.debugging_opts.borrowck_stats
636     }
637     pub fn print_llvm_passes(&self) -> bool {
638         self.opts.debugging_opts.print_llvm_passes
639     }
640     pub fn binary_dep_depinfo(&self) -> bool {
641         self.opts.debugging_opts.binary_dep_depinfo
642     }
643     pub fn mir_opt_level(&self) -> usize {
644         self.opts
645             .debugging_opts
646             .mir_opt_level
647             .unwrap_or_else(|| if self.opts.optimize != config::OptLevel::No { 2 } else { 1 })
648     }
649
650     /// Gets the features enabled for the current compilation session.
651     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
652     /// dependency tracking. Use tcx.features() instead.
653     #[inline]
654     pub fn features_untracked(&self) -> &rustc_feature::Features {
655         self.features.get().unwrap()
656     }
657
658     pub fn init_features(&self, features: rustc_feature::Features) {
659         match self.features.set(features) {
660             Ok(()) => {}
661             Err(_) => panic!("`features` was initialized twice"),
662         }
663     }
664
665     pub fn init_lint_store(&self, lint_store: Lrc<dyn SessionLintStore>) {
666         self.lint_store
667             .set(lint_store)
668             .map_err(|_| ())
669             .expect("`lint_store` was initialized twice");
670     }
671
672     /// Calculates the flavor of LTO to use for this compilation.
673     pub fn lto(&self) -> config::Lto {
674         // If our target has codegen requirements ignore the command line
675         if self.target.requires_lto {
676             return config::Lto::Fat;
677         }
678
679         // If the user specified something, return that. If they only said `-C
680         // lto` and we've for whatever reason forced off ThinLTO via the CLI,
681         // then ensure we can't use a ThinLTO.
682         match self.opts.cg.lto {
683             config::LtoCli::Unspecified => {
684                 // The compiler was invoked without the `-Clto` flag. Fall
685                 // through to the default handling
686             }
687             config::LtoCli::No => {
688                 // The user explicitly opted out of any kind of LTO
689                 return config::Lto::No;
690             }
691             config::LtoCli::Yes | config::LtoCli::Fat | config::LtoCli::NoParam => {
692                 // All of these mean fat LTO
693                 return config::Lto::Fat;
694             }
695             config::LtoCli::Thin => {
696                 return if self.opts.cli_forced_thinlto_off {
697                     config::Lto::Fat
698                 } else {
699                     config::Lto::Thin
700                 };
701             }
702         }
703
704         // Ok at this point the target doesn't require anything and the user
705         // hasn't asked for anything. Our next decision is whether or not
706         // we enable "auto" ThinLTO where we use multiple codegen units and
707         // then do ThinLTO over those codegen units. The logic below will
708         // either return `No` or `ThinLocal`.
709
710         // If processing command line options determined that we're incompatible
711         // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option.
712         if self.opts.cli_forced_thinlto_off {
713             return config::Lto::No;
714         }
715
716         // If `-Z thinlto` specified process that, but note that this is mostly
717         // a deprecated option now that `-C lto=thin` exists.
718         if let Some(enabled) = self.opts.debugging_opts.thinlto {
719             if enabled {
720                 return config::Lto::ThinLocal;
721             } else {
722                 return config::Lto::No;
723             }
724         }
725
726         // If there's only one codegen unit and LTO isn't enabled then there's
727         // no need for ThinLTO so just return false.
728         if self.codegen_units() == 1 {
729             return config::Lto::No;
730         }
731
732         // Now we're in "defaults" territory. By default we enable ThinLTO for
733         // optimized compiles (anything greater than O0).
734         match self.opts.optimize {
735             config::OptLevel::No => config::Lto::No,
736             _ => config::Lto::ThinLocal,
737         }
738     }
739
740     /// Returns the panic strategy for this compile session. If the user explicitly selected one
741     /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
742     pub fn panic_strategy(&self) -> PanicStrategy {
743         self.opts.cg.panic.unwrap_or(self.target.panic_strategy)
744     }
745     pub fn fewer_names(&self) -> bool {
746         if let Some(fewer_names) = self.opts.debugging_opts.fewer_names {
747             fewer_names
748         } else {
749             let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly)
750                 || self.opts.output_types.contains_key(&OutputType::Bitcode)
751                 // AddressSanitizer and MemorySanitizer use alloca name when reporting an issue.
752                 || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY);
753             !more_names
754         }
755     }
756
757     pub fn unstable_options(&self) -> bool {
758         self.opts.debugging_opts.unstable_options
759     }
760     pub fn is_nightly_build(&self) -> bool {
761         self.opts.unstable_features.is_nightly_build()
762     }
763     pub fn overflow_checks(&self) -> bool {
764         self.opts
765             .cg
766             .overflow_checks
767             .or(self.opts.debugging_opts.force_overflow_checks)
768             .unwrap_or(self.opts.debug_assertions)
769     }
770
771     /// Check whether this compile session and crate type use static crt.
772     pub fn crt_static(&self, crate_type: Option<CrateType>) -> bool {
773         if !self.target.crt_static_respected {
774             // If the target does not opt in to crt-static support, use its default.
775             return self.target.crt_static_default;
776         }
777
778         let requested_features = self.opts.cg.target_feature.split(',');
779         let found_negative = requested_features.clone().any(|r| r == "-crt-static");
780         let found_positive = requested_features.clone().any(|r| r == "+crt-static");
781
782         if found_positive || found_negative {
783             found_positive
784         } else if crate_type == Some(CrateType::ProcMacro)
785             || crate_type == None && self.opts.crate_types.contains(&CrateType::ProcMacro)
786         {
787             // FIXME: When crate_type is not available,
788             // we use compiler options to determine the crate_type.
789             // We can't check `#![crate_type = "proc-macro"]` here.
790             false
791         } else {
792             self.target.crt_static_default
793         }
794     }
795
796     pub fn relocation_model(&self) -> RelocModel {
797         self.opts.cg.relocation_model.unwrap_or(self.target.relocation_model)
798     }
799
800     pub fn code_model(&self) -> Option<CodeModel> {
801         self.opts.cg.code_model.or(self.target.code_model)
802     }
803
804     pub fn tls_model(&self) -> TlsModel {
805         self.opts.debugging_opts.tls_model.unwrap_or(self.target.tls_model)
806     }
807
808     pub fn is_wasi_reactor(&self) -> bool {
809         self.target.options.os == "wasi"
810             && matches!(
811                 self.opts.debugging_opts.wasi_exec_model,
812                 Some(config::WasiExecModel::Reactor)
813             )
814     }
815
816     pub fn split_debuginfo(&self) -> SplitDebuginfo {
817         self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo)
818     }
819
820     pub fn target_can_use_split_dwarf(&self) -> bool {
821         !self.target.is_like_windows && !self.target.is_like_osx
822     }
823
824     pub fn must_not_eliminate_frame_pointers(&self) -> bool {
825         // "mcount" function relies on stack pointer.
826         // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
827         if self.instrument_mcount() {
828             true
829         } else if let Some(x) = self.opts.cg.force_frame_pointers {
830             x
831         } else {
832             !self.target.eliminate_frame_pointer
833         }
834     }
835
836     pub fn must_emit_unwind_tables(&self) -> bool {
837         // This is used to control the emission of the `uwtable` attribute on
838         // LLVM functions.
839         //
840         // At the very least, unwind tables are needed when compiling with
841         // `-C panic=unwind`.
842         //
843         // On some targets (including windows), however, exceptions include
844         // other events such as illegal instructions, segfaults, etc. This means
845         // that on Windows we end up still needing unwind tables even if the `-C
846         // panic=abort` flag is passed.
847         //
848         // You can also find more info on why Windows needs unwind tables in:
849         //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
850         //
851         // If a target requires unwind tables, then they must be emitted.
852         // Otherwise, we can defer to the `-C force-unwind-tables=<yes/no>`
853         // value, if it is provided, or disable them, if not.
854         if self.panic_strategy() == PanicStrategy::Unwind {
855             true
856         } else if self.target.requires_uwtable {
857             true
858         } else {
859             self.opts.cg.force_unwind_tables.unwrap_or(false)
860         }
861     }
862
863     /// Returns the symbol name for the registrar function,
864     /// given the crate `Svh` and the function `DefIndex`.
865     pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
866         format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
867     }
868
869     pub fn generate_proc_macro_decls_symbol(&self, disambiguator: CrateDisambiguator) -> String {
870         format!("__rustc_proc_macro_decls_{}__", disambiguator.to_fingerprint().to_hex())
871     }
872
873     pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
874         filesearch::FileSearch::new(
875             &self.sysroot,
876             self.opts.target_triple.triple(),
877             &self.opts.search_paths,
878             // `target_tlib_path == None` means it's the same as `host_tlib_path`.
879             self.target_tlib_path.as_ref().unwrap_or(&self.host_tlib_path),
880             kind,
881         )
882     }
883     pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> {
884         filesearch::FileSearch::new(
885             &self.sysroot,
886             config::host_triple(),
887             &self.opts.search_paths,
888             &self.host_tlib_path,
889             kind,
890         )
891     }
892
893     pub fn set_incr_session_load_dep_graph(&self, load: bool) {
894         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
895
896         if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session {
897             *load_dep_graph = load;
898         }
899     }
900
901     pub fn incr_session_load_dep_graph(&self) -> bool {
902         let incr_comp_session = self.incr_comp_session.borrow();
903         match *incr_comp_session {
904             IncrCompSession::Active { load_dep_graph, .. } => load_dep_graph,
905             _ => false,
906         }
907     }
908
909     pub fn init_incr_comp_session(
910         &self,
911         session_dir: PathBuf,
912         lock_file: flock::Lock,
913         load_dep_graph: bool,
914     ) {
915         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
916
917         if let IncrCompSession::NotInitialized = *incr_comp_session {
918         } else {
919             panic!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
920         }
921
922         *incr_comp_session =
923             IncrCompSession::Active { session_directory: session_dir, lock_file, load_dep_graph };
924     }
925
926     pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
927         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
928
929         if let IncrCompSession::Active { .. } = *incr_comp_session {
930         } else {
931             panic!("trying to finalize `IncrCompSession` `{:?}`", *incr_comp_session);
932         }
933
934         // Note: this will also drop the lock file, thus unlocking the directory.
935         *incr_comp_session = IncrCompSession::Finalized { session_directory: new_directory_path };
936     }
937
938     pub fn mark_incr_comp_session_as_invalid(&self) {
939         let mut incr_comp_session = self.incr_comp_session.borrow_mut();
940
941         let session_directory = match *incr_comp_session {
942             IncrCompSession::Active { ref session_directory, .. } => session_directory.clone(),
943             IncrCompSession::InvalidBecauseOfErrors { .. } => return,
944             _ => panic!("trying to invalidate `IncrCompSession` `{:?}`", *incr_comp_session),
945         };
946
947         // Note: this will also drop the lock file, thus unlocking the directory.
948         *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
949     }
950
951     pub fn incr_comp_session_dir(&self) -> cell::Ref<'_, PathBuf> {
952         let incr_comp_session = self.incr_comp_session.borrow();
953         cell::Ref::map(incr_comp_session, |incr_comp_session| match *incr_comp_session {
954             IncrCompSession::NotInitialized => panic!(
955                 "trying to get session directory from `IncrCompSession`: {:?}",
956                 *incr_comp_session,
957             ),
958             IncrCompSession::Active { ref session_directory, .. }
959             | IncrCompSession::Finalized { ref session_directory }
960             | IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
961                 session_directory
962             }
963         })
964     }
965
966     pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<'_, PathBuf>> {
967         self.opts.incremental.as_ref().map(|_| self.incr_comp_session_dir())
968     }
969
970     pub fn print_perf_stats(&self) {
971         eprintln!(
972             "Total time spent computing symbol hashes:      {}",
973             duration_to_secs_str(*self.perf_stats.symbol_hash_time.lock())
974         );
975         eprintln!(
976             "Total queries canonicalized:                   {}",
977             self.perf_stats.queries_canonicalized.load(Ordering::Relaxed)
978         );
979         eprintln!(
980             "normalize_generic_arg_after_erasing_regions:   {}",
981             self.perf_stats.normalize_generic_arg_after_erasing_regions.load(Ordering::Relaxed)
982         );
983         eprintln!(
984             "normalize_projection_ty:                       {}",
985             self.perf_stats.normalize_projection_ty.load(Ordering::Relaxed)
986         );
987     }
988
989     /// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
990     /// This expends fuel if applicable, and records fuel if applicable.
991     pub fn consider_optimizing<T: Fn() -> String>(&self, crate_name: &str, msg: T) -> bool {
992         let mut ret = true;
993         if let Some(ref c) = self.optimization_fuel_crate {
994             if c == crate_name {
995                 assert_eq!(self.threads(), 1);
996                 let mut fuel = self.optimization_fuel.lock();
997                 ret = fuel.remaining != 0;
998                 if fuel.remaining == 0 && !fuel.out_of_fuel {
999                     self.warn(&format!("optimization-fuel-exhausted: {}", msg()));
1000                     fuel.out_of_fuel = true;
1001                 } else if fuel.remaining > 0 {
1002                     fuel.remaining -= 1;
1003                 }
1004             }
1005         }
1006         if let Some(ref c) = self.print_fuel_crate {
1007             if c == crate_name {
1008                 assert_eq!(self.threads(), 1);
1009                 self.print_fuel.fetch_add(1, SeqCst);
1010             }
1011         }
1012         ret
1013     }
1014
1015     /// Returns the number of query threads that should be used for this
1016     /// compilation
1017     pub fn threads(&self) -> usize {
1018         self.opts.debugging_opts.threads
1019     }
1020
1021     /// Returns the number of codegen units that should be used for this
1022     /// compilation
1023     pub fn codegen_units(&self) -> usize {
1024         if let Some(n) = self.opts.cli_forced_codegen_units {
1025             return n;
1026         }
1027         if let Some(n) = self.target.default_codegen_units {
1028             return n as usize;
1029         }
1030
1031         // If incremental compilation is turned on, we default to a high number
1032         // codegen units in order to reduce the "collateral damage" small
1033         // changes cause.
1034         if self.opts.incremental.is_some() {
1035             return 256;
1036         }
1037
1038         // Why is 16 codegen units the default all the time?
1039         //
1040         // The main reason for enabling multiple codegen units by default is to
1041         // leverage the ability for the codegen backend to do codegen and
1042         // optimization in parallel. This allows us, especially for large crates, to
1043         // make good use of all available resources on the machine once we've
1044         // hit that stage of compilation. Large crates especially then often
1045         // take a long time in codegen/optimization and this helps us amortize that
1046         // cost.
1047         //
1048         // Note that a high number here doesn't mean that we'll be spawning a
1049         // large number of threads in parallel. The backend of rustc contains
1050         // global rate limiting through the `jobserver` crate so we'll never
1051         // overload the system with too much work, but rather we'll only be
1052         // optimizing when we're otherwise cooperating with other instances of
1053         // rustc.
1054         //
1055         // Rather a high number here means that we should be able to keep a lot
1056         // of idle cpus busy. By ensuring that no codegen unit takes *too* long
1057         // to build we'll be guaranteed that all cpus will finish pretty closely
1058         // to one another and we should make relatively optimal use of system
1059         // resources
1060         //
1061         // Note that the main cost of codegen units is that it prevents LLVM
1062         // from inlining across codegen units. Users in general don't have a lot
1063         // of control over how codegen units are split up so it's our job in the
1064         // compiler to ensure that undue performance isn't lost when using
1065         // codegen units (aka we can't require everyone to slap `#[inline]` on
1066         // everything).
1067         //
1068         // If we're compiling at `-O0` then the number doesn't really matter too
1069         // much because performance doesn't matter and inlining is ok to lose.
1070         // In debug mode we just want to try to guarantee that no cpu is stuck
1071         // doing work that could otherwise be farmed to others.
1072         //
1073         // In release mode, however (O1 and above) performance does indeed
1074         // matter! To recover the loss in performance due to inlining we'll be
1075         // enabling ThinLTO by default (the function for which is just below).
1076         // This will ensure that we recover any inlining wins we otherwise lost
1077         // through codegen unit partitioning.
1078         //
1079         // ---
1080         //
1081         // Ok that's a lot of words but the basic tl;dr; is that we want a high
1082         // number here -- but not too high. Additionally we're "safe" to have it
1083         // always at the same number at all optimization levels.
1084         //
1085         // As a result 16 was chosen here! Mostly because it was a power of 2
1086         // and most benchmarks agreed it was roughly a local optimum. Not very
1087         // scientific.
1088         16
1089     }
1090
1091     pub fn teach(&self, code: &DiagnosticId) -> bool {
1092         self.opts.debugging_opts.teach && self.diagnostic().must_teach(code)
1093     }
1094
1095     pub fn rust_2015(&self) -> bool {
1096         self.opts.edition == Edition::Edition2015
1097     }
1098
1099     /// Are we allowed to use features from the Rust 2018 edition?
1100     pub fn rust_2018(&self) -> bool {
1101         self.opts.edition >= Edition::Edition2018
1102     }
1103
1104     /// Are we allowed to use features from the Rust 2021 edition?
1105     pub fn rust_2021(&self) -> bool {
1106         self.opts.edition >= Edition::Edition2021
1107     }
1108
1109     pub fn edition(&self) -> Edition {
1110         self.opts.edition
1111     }
1112
1113     /// Returns `true` if we cannot skip the PLT for shared library calls.
1114     pub fn needs_plt(&self) -> bool {
1115         // Check if the current target usually needs PLT to be enabled.
1116         // The user can use the command line flag to override it.
1117         let needs_plt = self.target.needs_plt;
1118
1119         let dbg_opts = &self.opts.debugging_opts;
1120
1121         let relro_level = dbg_opts.relro_level.unwrap_or(self.target.relro_level);
1122
1123         // Only enable this optimization by default if full relro is also enabled.
1124         // In this case, lazy binding was already unavailable, so nothing is lost.
1125         // This also ensures `-Wl,-z,now` is supported by the linker.
1126         let full_relro = RelroLevel::Full == relro_level;
1127
1128         // If user didn't explicitly forced us to use / skip the PLT,
1129         // then try to skip it where possible.
1130         dbg_opts.plt.unwrap_or(needs_plt || !full_relro)
1131     }
1132
1133     /// Checks if LLVM lifetime markers should be emitted.
1134     pub fn emit_lifetime_markers(&self) -> bool {
1135         self.opts.optimize != config::OptLevel::No
1136         // AddressSanitizer uses lifetimes to detect use after scope bugs.
1137         // MemorySanitizer uses lifetimes to detect use of uninitialized stack variables.
1138         // HWAddressSanitizer will use lifetimes to detect use after scope bugs in the future.
1139         || self.opts.debugging_opts.sanitizer.intersects(SanitizerSet::ADDRESS | SanitizerSet::MEMORY | SanitizerSet::HWADDRESS)
1140     }
1141
1142     pub fn link_dead_code(&self) -> bool {
1143         self.opts.cg.link_dead_code.unwrap_or(false)
1144     }
1145
1146     pub fn mark_attr_known(&self, attr: &Attribute) {
1147         self.known_attrs.lock().mark(attr)
1148     }
1149
1150     pub fn is_attr_known(&self, attr: &Attribute) -> bool {
1151         self.known_attrs.lock().is_marked(attr)
1152     }
1153
1154     pub fn mark_attr_used(&self, attr: &Attribute) {
1155         self.used_attrs.lock().mark(attr)
1156     }
1157
1158     pub fn is_attr_used(&self, attr: &Attribute) -> bool {
1159         self.used_attrs.lock().is_marked(attr)
1160     }
1161
1162     /// Returns `true` if the attribute's path matches the argument. If it
1163     /// matches, then the attribute is marked as used.
1164     ///
1165     /// This method should only be used by rustc, other tools can use
1166     /// `Attribute::has_name` instead, because only rustc is supposed to report
1167     /// the `unused_attributes` lint. (`MetaItem` and `NestedMetaItem` are
1168     /// produced by lowering an `Attribute` and don't have identity, so they
1169     /// only have the `has_name` method, and you need to mark the original
1170     /// `Attribute` as used when necessary.)
1171     pub fn check_name(&self, attr: &Attribute, name: Symbol) -> bool {
1172         let matches = attr.has_name(name);
1173         if matches {
1174             self.mark_attr_used(attr);
1175         }
1176         matches
1177     }
1178
1179     pub fn is_proc_macro_attr(&self, attr: &Attribute) -> bool {
1180         [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
1181             .iter()
1182             .any(|kind| self.check_name(attr, *kind))
1183     }
1184
1185     pub fn contains_name(&self, attrs: &[Attribute], name: Symbol) -> bool {
1186         attrs.iter().any(|item| self.check_name(item, name))
1187     }
1188
1189     pub fn find_by_name<'a>(
1190         &'a self,
1191         attrs: &'a [Attribute],
1192         name: Symbol,
1193     ) -> Option<&'a Attribute> {
1194         attrs.iter().find(|attr| self.check_name(attr, name))
1195     }
1196
1197     pub fn filter_by_name<'a>(
1198         &'a self,
1199         attrs: &'a [Attribute],
1200         name: Symbol,
1201     ) -> impl Iterator<Item = &'a Attribute> {
1202         attrs.iter().filter(move |attr| self.check_name(attr, name))
1203     }
1204
1205     pub fn first_attr_value_str_by_name(
1206         &self,
1207         attrs: &[Attribute],
1208         name: Symbol,
1209     ) -> Option<Symbol> {
1210         attrs.iter().find(|at| self.check_name(at, name)).and_then(|at| at.value_str())
1211     }
1212 }
1213
1214 fn default_emitter(
1215     sopts: &config::Options,
1216     registry: rustc_errors::registry::Registry,
1217     source_map: Lrc<SourceMap>,
1218     emitter_dest: Option<Box<dyn Write + Send>>,
1219 ) -> Box<dyn Emitter + sync::Send> {
1220     let macro_backtrace = sopts.debugging_opts.macro_backtrace;
1221     match (sopts.error_format, emitter_dest) {
1222         (config::ErrorOutputType::HumanReadable(kind), dst) => {
1223             let (short, color_config) = kind.unzip();
1224
1225             if let HumanReadableErrorType::AnnotateSnippet(_) = kind {
1226                 let emitter =
1227                     AnnotateSnippetEmitterWriter::new(Some(source_map), short, macro_backtrace);
1228                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1229             } else {
1230                 let emitter = match dst {
1231                     None => EmitterWriter::stderr(
1232                         color_config,
1233                         Some(source_map),
1234                         short,
1235                         sopts.debugging_opts.teach,
1236                         sopts.debugging_opts.terminal_width,
1237                         macro_backtrace,
1238                     ),
1239                     Some(dst) => EmitterWriter::new(
1240                         dst,
1241                         Some(source_map),
1242                         short,
1243                         false, // no teach messages when writing to a buffer
1244                         false, // no colors when writing to a buffer
1245                         None,  // no terminal width
1246                         macro_backtrace,
1247                     ),
1248                 };
1249                 Box::new(emitter.ui_testing(sopts.debugging_opts.ui_testing))
1250             }
1251         }
1252         (config::ErrorOutputType::Json { pretty, json_rendered }, None) => Box::new(
1253             JsonEmitter::stderr(
1254                 Some(registry),
1255                 source_map,
1256                 pretty,
1257                 json_rendered,
1258                 sopts.debugging_opts.terminal_width,
1259                 macro_backtrace,
1260             )
1261             .ui_testing(sopts.debugging_opts.ui_testing),
1262         ),
1263         (config::ErrorOutputType::Json { pretty, json_rendered }, Some(dst)) => Box::new(
1264             JsonEmitter::new(
1265                 dst,
1266                 Some(registry),
1267                 source_map,
1268                 pretty,
1269                 json_rendered,
1270                 sopts.debugging_opts.terminal_width,
1271                 macro_backtrace,
1272             )
1273             .ui_testing(sopts.debugging_opts.ui_testing),
1274         ),
1275     }
1276 }
1277
1278 pub enum DiagnosticOutput {
1279     Default,
1280     Raw(Box<dyn Write + Send>),
1281 }
1282
1283 pub fn build_session(
1284     sopts: config::Options,
1285     local_crate_source_file: Option<PathBuf>,
1286     registry: rustc_errors::registry::Registry,
1287     diagnostics_output: DiagnosticOutput,
1288     driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
1289     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
1290     target_override: Option<Target>,
1291 ) -> Session {
1292     // FIXME: This is not general enough to make the warning lint completely override
1293     // normal diagnostic warnings, since the warning lint can also be denied and changed
1294     // later via the source code.
1295     let warnings_allow = sopts
1296         .lint_opts
1297         .iter()
1298         .filter(|&&(ref key, _)| *key == "warnings")
1299         .map(|&(_, ref level)| *level == lint::Allow)
1300         .last()
1301         .unwrap_or(false);
1302     let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow);
1303     let can_emit_warnings = !(warnings_allow || cap_lints_allow);
1304
1305     let write_dest = match diagnostics_output {
1306         DiagnosticOutput::Default => None,
1307         DiagnosticOutput::Raw(write) => Some(write),
1308     };
1309
1310     let target_cfg = config::build_target_config(&sopts, target_override);
1311     let host_triple = TargetTriple::from_triple(config::host_triple());
1312     let host = Target::search(&host_triple).unwrap_or_else(|e| {
1313         early_error(sopts.error_format, &format!("Error loading host specification: {}", e))
1314     });
1315
1316     let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
1317     let hash_kind = sopts.debugging_opts.src_hash_algorithm.unwrap_or_else(|| {
1318         if target_cfg.is_like_msvc {
1319             SourceFileHashAlgorithm::Sha1
1320         } else {
1321             SourceFileHashAlgorithm::Md5
1322         }
1323     });
1324     let source_map = Lrc::new(SourceMap::with_file_loader_and_hash_kind(
1325         loader,
1326         sopts.file_path_mapping(),
1327         hash_kind,
1328     ));
1329     let emitter = default_emitter(&sopts, registry, source_map.clone(), write_dest);
1330
1331     let span_diagnostic = rustc_errors::Handler::with_emitter_and_flags(
1332         emitter,
1333         sopts.debugging_opts.diagnostic_handler_flags(can_emit_warnings),
1334     );
1335
1336     let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.debugging_opts.self_profile
1337     {
1338         let directory =
1339             if let Some(ref directory) = d { directory } else { std::path::Path::new(".") };
1340
1341         let profiler = SelfProfiler::new(
1342             directory,
1343             sopts.crate_name.as_deref(),
1344             &sopts.debugging_opts.self_profile_events,
1345         );
1346         match profiler {
1347             Ok(profiler) => Some(Arc::new(profiler)),
1348             Err(e) => {
1349                 early_warn(sopts.error_format, &format!("failed to create profiler: {}", e));
1350                 None
1351             }
1352         }
1353     } else {
1354         None
1355     };
1356
1357     let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map);
1358     parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release;
1359     let sysroot = match &sopts.maybe_sysroot {
1360         Some(sysroot) => sysroot.clone(),
1361         None => filesearch::get_or_default_sysroot(),
1362     };
1363
1364     let host_triple = config::host_triple();
1365     let target_triple = sopts.target_triple.triple();
1366     let host_tlib_path = SearchPath::from_sysroot_and_triple(&sysroot, host_triple);
1367     let target_tlib_path = if host_triple == target_triple {
1368         None
1369     } else {
1370         Some(SearchPath::from_sysroot_and_triple(&sysroot, target_triple))
1371     };
1372
1373     let file_path_mapping = sopts.file_path_mapping();
1374
1375     let local_crate_source_file =
1376         local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
1377
1378     let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone());
1379     let optimization_fuel = Lock::new(OptimizationFuel {
1380         remaining: sopts.debugging_opts.fuel.as_ref().map_or(0, |i| i.1),
1381         out_of_fuel: false,
1382     });
1383     let print_fuel_crate = sopts.debugging_opts.print_fuel.clone();
1384     let print_fuel = AtomicU64::new(0);
1385
1386     let working_dir = env::current_dir().unwrap_or_else(|e| {
1387         parse_sess.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
1388     });
1389     let working_dir = file_path_mapping.map_prefix(working_dir);
1390
1391     let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph {
1392         CguReuseTracker::new()
1393     } else {
1394         CguReuseTracker::new_disabled()
1395     };
1396
1397     let prof = SelfProfilerRef::new(
1398         self_profiler,
1399         sopts.debugging_opts.time_passes || sopts.debugging_opts.time,
1400         sopts.debugging_opts.time_passes,
1401     );
1402
1403     let ctfe_backtrace = Lock::new(match env::var("RUSTC_CTFE_BACKTRACE") {
1404         Ok(ref val) if val == "immediate" => CtfeBacktrace::Immediate,
1405         Ok(ref val) if val != "0" => CtfeBacktrace::Capture,
1406         _ => CtfeBacktrace::Disabled,
1407     });
1408
1409     // Try to find a directory containing the Rust `src`, for more details see
1410     // the doc comment on the `real_rust_source_base_dir` field.
1411     let real_rust_source_base_dir = {
1412         // This is the location used by the `rust-src` `rustup` component.
1413         let mut candidate = sysroot.join("lib/rustlib/src/rust");
1414         if let Ok(metadata) = candidate.symlink_metadata() {
1415             // Replace the symlink rustbuild creates, with its destination.
1416             // We could try to use `fs::canonicalize` instead, but that might
1417             // produce unnecessarily verbose path.
1418             if metadata.file_type().is_symlink() {
1419                 if let Ok(symlink_dest) = std::fs::read_link(&candidate) {
1420                     candidate = symlink_dest;
1421                 }
1422             }
1423         }
1424
1425         // Only use this directory if it has a file we can expect to always find.
1426         if candidate.join("library/std/src/lib.rs").is_file() { Some(candidate) } else { None }
1427     };
1428
1429     let asm_arch =
1430         if target_cfg.allow_asm { InlineAsmArch::from_str(&target_cfg.arch).ok() } else { None };
1431
1432     let sess = Session {
1433         target: target_cfg,
1434         host,
1435         opts: sopts,
1436         host_tlib_path,
1437         target_tlib_path,
1438         parse_sess,
1439         sysroot,
1440         local_crate_source_file,
1441         working_dir,
1442         one_time_diagnostics: Default::default(),
1443         crate_types: OnceCell::new(),
1444         crate_disambiguator: OnceCell::new(),
1445         features: OnceCell::new(),
1446         lint_store: OnceCell::new(),
1447         recursion_limit: OnceCell::new(),
1448         type_length_limit: OnceCell::new(),
1449         const_eval_limit: OnceCell::new(),
1450         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
1451         cgu_reuse_tracker,
1452         prof,
1453         perf_stats: PerfStats {
1454             symbol_hash_time: Lock::new(Duration::from_secs(0)),
1455             queries_canonicalized: AtomicUsize::new(0),
1456             normalize_generic_arg_after_erasing_regions: AtomicUsize::new(0),
1457             normalize_projection_ty: AtomicUsize::new(0),
1458         },
1459         code_stats: Default::default(),
1460         optimization_fuel_crate,
1461         optimization_fuel,
1462         print_fuel_crate,
1463         print_fuel,
1464         jobserver: jobserver::client(),
1465         driver_lint_caps,
1466         trait_methods_not_found: Lock::new(Default::default()),
1467         confused_type_with_std_module: Lock::new(Default::default()),
1468         system_library_path: OneThread::new(RefCell::new(Default::default())),
1469         ctfe_backtrace,
1470         miri_unleashed_features: Lock::new(Default::default()),
1471         real_rust_source_base_dir,
1472         asm_arch,
1473         target_features: FxHashSet::default(),
1474         known_attrs: Lock::new(MarkedAttrs::new()),
1475         used_attrs: Lock::new(MarkedAttrs::new()),
1476         if_let_suggestions: Default::default(),
1477     };
1478
1479     validate_commandline_args_with_session_available(&sess);
1480
1481     sess
1482 }
1483
1484 // If it is useful to have a Session available already for validating a
1485 // commandline argument, you can do so here.
1486 fn validate_commandline_args_with_session_available(sess: &Session) {
1487     // Since we don't know if code in an rlib will be linked to statically or
1488     // dynamically downstream, rustc generates `__imp_` symbols that help linkers
1489     // on Windows deal with this lack of knowledge (#27438). Unfortunately,
1490     // these manually generated symbols confuse LLD when it tries to merge
1491     // bitcode during ThinLTO. Therefore we disallow dynamic linking on Windows
1492     // when compiling for LLD ThinLTO. This way we can validly just not generate
1493     // the `dllimport` attributes and `__imp_` symbols in that case.
1494     if sess.opts.cg.linker_plugin_lto.enabled()
1495         && sess.opts.cg.prefer_dynamic
1496         && sess.target.is_like_windows
1497     {
1498         sess.err(
1499             "Linker plugin based LTO is not supported together with \
1500                   `-C prefer-dynamic` when targeting Windows-like targets",
1501         );
1502     }
1503
1504     // Make sure that any given profiling data actually exists so LLVM can't
1505     // decide to silently skip PGO.
1506     if let Some(ref path) = sess.opts.cg.profile_use {
1507         if !path.exists() {
1508             sess.err(&format!(
1509                 "File `{}` passed to `-C profile-use` does not exist.",
1510                 path.display()
1511             ));
1512         }
1513     }
1514
1515     // Unwind tables cannot be disabled if the target requires them.
1516     if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables {
1517         if sess.panic_strategy() == PanicStrategy::Unwind && !include_uwtables {
1518             sess.err(
1519                 "panic=unwind requires unwind tables, they cannot be disabled \
1520                      with `-C force-unwind-tables=no`.",
1521             );
1522         }
1523
1524         if sess.target.requires_uwtable && !include_uwtables {
1525             sess.err(
1526                 "target requires unwind tables, they cannot be disabled with \
1527                      `-C force-unwind-tables=no`.",
1528             );
1529         }
1530     }
1531
1532     // PGO does not work reliably with panic=unwind on Windows. Let's make it
1533     // an error to combine the two for now. It always runs into an assertions
1534     // if LLVM is built with assertions, but without assertions it sometimes
1535     // does not crash and will probably generate a corrupted binary.
1536     // We should only display this error if we're actually going to run PGO.
1537     // If we're just supposed to print out some data, don't show the error (#61002).
1538     if sess.opts.cg.profile_generate.enabled()
1539         && sess.target.is_like_msvc
1540         && sess.panic_strategy() == PanicStrategy::Unwind
1541         && sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs)
1542     {
1543         sess.err(
1544             "Profile-guided optimization does not yet work in conjunction \
1545                   with `-Cpanic=unwind` on Windows when targeting MSVC. \
1546                   See issue #61002 <https://github.com/rust-lang/rust/issues/61002> \
1547                   for more information.",
1548         );
1549     }
1550
1551     const ASAN_SUPPORTED_TARGETS: &[&str] = &[
1552         "aarch64-apple-darwin",
1553         "aarch64-fuchsia",
1554         "aarch64-unknown-linux-gnu",
1555         "x86_64-apple-darwin",
1556         "x86_64-fuchsia",
1557         "x86_64-unknown-freebsd",
1558         "x86_64-unknown-linux-gnu",
1559     ];
1560     const LSAN_SUPPORTED_TARGETS: &[&str] = &[
1561         "aarch64-apple-darwin",
1562         "aarch64-unknown-linux-gnu",
1563         "x86_64-apple-darwin",
1564         "x86_64-unknown-linux-gnu",
1565     ];
1566     const MSAN_SUPPORTED_TARGETS: &[&str] =
1567         &["aarch64-unknown-linux-gnu", "x86_64-unknown-freebsd", "x86_64-unknown-linux-gnu"];
1568     const TSAN_SUPPORTED_TARGETS: &[&str] = &[
1569         "aarch64-apple-darwin",
1570         "aarch64-unknown-linux-gnu",
1571         "x86_64-apple-darwin",
1572         "x86_64-unknown-freebsd",
1573         "x86_64-unknown-linux-gnu",
1574     ];
1575     const HWASAN_SUPPORTED_TARGETS: &[&str] =
1576         &["aarch64-linux-android", "aarch64-unknown-linux-gnu"];
1577
1578     // Sanitizers can only be used on some tested platforms.
1579     for s in sess.opts.debugging_opts.sanitizer {
1580         let supported_targets = match s {
1581             SanitizerSet::ADDRESS => ASAN_SUPPORTED_TARGETS,
1582             SanitizerSet::LEAK => LSAN_SUPPORTED_TARGETS,
1583             SanitizerSet::MEMORY => MSAN_SUPPORTED_TARGETS,
1584             SanitizerSet::THREAD => TSAN_SUPPORTED_TARGETS,
1585             SanitizerSet::HWADDRESS => HWASAN_SUPPORTED_TARGETS,
1586             _ => panic!("unrecognized sanitizer {}", s),
1587         };
1588         if !supported_targets.contains(&&*sess.opts.target_triple.triple()) {
1589             sess.err(&format!(
1590                 "`-Zsanitizer={}` only works with targets: {}",
1591                 s,
1592                 supported_targets.join(", ")
1593             ));
1594         }
1595         let conflicting = sess.opts.debugging_opts.sanitizer - s;
1596         if !conflicting.is_empty() {
1597             sess.err(&format!(
1598                 "`-Zsanitizer={}` is incompatible with `-Zsanitizer={}`",
1599                 s, conflicting,
1600             ));
1601             // Don't report additional errors.
1602             break;
1603         }
1604     }
1605 }
1606
1607 /// Holds data on the current incremental compilation session, if there is one.
1608 #[derive(Debug)]
1609 pub enum IncrCompSession {
1610     /// This is the state the session will be in until the incr. comp. dir is
1611     /// needed.
1612     NotInitialized,
1613     /// This is the state during which the session directory is private and can
1614     /// be modified.
1615     Active { session_directory: PathBuf, lock_file: flock::Lock, load_dep_graph: bool },
1616     /// This is the state after the session directory has been finalized. In this
1617     /// state, the contents of the directory must not be modified any more.
1618     Finalized { session_directory: PathBuf },
1619     /// This is an error state that is reached when some compilation error has
1620     /// occurred. It indicates that the contents of the session directory must
1621     /// not be used, since they might be invalid.
1622     InvalidBecauseOfErrors { session_directory: PathBuf },
1623 }
1624
1625 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
1626     let emitter: Box<dyn Emitter + sync::Send> = match output {
1627         config::ErrorOutputType::HumanReadable(kind) => {
1628             let (short, color_config) = kind.unzip();
1629             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1630         }
1631         config::ErrorOutputType::Json { pretty, json_rendered } => {
1632             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1633         }
1634     };
1635     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1636     handler.struct_fatal(msg).emit();
1637     rustc_errors::FatalError.raise();
1638 }
1639
1640 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
1641     let emitter: Box<dyn Emitter + sync::Send> = match output {
1642         config::ErrorOutputType::HumanReadable(kind) => {
1643             let (short, color_config) = kind.unzip();
1644             Box::new(EmitterWriter::stderr(color_config, None, short, false, None, false))
1645         }
1646         config::ErrorOutputType::Json { pretty, json_rendered } => {
1647             Box::new(JsonEmitter::basic(pretty, json_rendered, None, false))
1648         }
1649     };
1650     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1651     handler.struct_warn(msg).emit();
1652 }